blob: d4a4b3d0dbad5ed1db2168ea455760eb09328851 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
John McCall7cd088e2010-08-24 07:21:54 +000012#include "clang/Sema/Template.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
John McCall92b7f702010-03-11 07:50:04 +000015#include "clang/AST/DeclFriend.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
John McCall4e2cbb22010-10-20 05:44:58 +000019#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor5f3aeb62010-10-13 00:27:52 +000020#include "clang/AST/TypeVisitor.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/Lookup.h"
25#include "clang/Sema/ParsedTemplate.h"
26#include "clang/Sema/Scope.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramer013b3662012-01-30 16:17:39 +000030#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000031#include "llvm/ADT/SmallString.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000032#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000033using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000034using namespace sema;
Douglas Gregor72c3f312008-12-05 18:15:24 +000035
John McCall78b81052010-11-10 02:40:36 +000036// Exported for use by Parser.
37SourceRange
38clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
39 unsigned N) {
40 if (!N) return SourceRange();
41 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
42}
43
Douglas Gregor2dd078a2009-09-02 22:59:36 +000044/// \brief Determine whether the declaration found is acceptable as the name
45/// of a template and, if so, return that template declaration. Otherwise,
46/// returns NULL.
John McCallad00b772010-06-16 08:42:20 +000047static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +000048 NamedDecl *Orig,
49 bool AllowFunctionTemplates) {
John McCallad00b772010-06-16 08:42:20 +000050 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000051
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +000052 if (isa<TemplateDecl>(D)) {
53 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
54 return 0;
55
John McCallad00b772010-06-16 08:42:20 +000056 return Orig;
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +000057 }
Mike Stump1eb44332009-09-09 15:08:12 +000058
Douglas Gregor2dd078a2009-09-02 22:59:36 +000059 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
60 // C++ [temp.local]p1:
61 // Like normal (non-template) classes, class templates have an
62 // injected-class-name (Clause 9). The injected-class-name
63 // can be used with or without a template-argument-list. When
64 // it is used without a template-argument-list, it is
65 // equivalent to the injected-class-name followed by the
66 // template-parameters of the class template enclosed in
67 // <>. When it is used with a template-argument-list, it
68 // refers to the specified class template specialization,
69 // which could be the current specialization or another
70 // specialization.
71 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000072 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000073 if (Record->getDescribedClassTemplate())
74 return Record->getDescribedClassTemplate();
75
76 if (ClassTemplateSpecializationDecl *Spec
77 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
78 return Spec->getSpecializedTemplate();
79 }
Mike Stump1eb44332009-09-09 15:08:12 +000080
Douglas Gregor2dd078a2009-09-02 22:59:36 +000081 return 0;
82 }
Mike Stump1eb44332009-09-09 15:08:12 +000083
Douglas Gregor2dd078a2009-09-02 22:59:36 +000084 return 0;
85}
86
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +000087void Sema::FilterAcceptableTemplateNames(LookupResult &R,
88 bool AllowFunctionTemplates) {
Douglas Gregor01e56ae2010-04-12 20:54:26 +000089 // The set of class templates we've already seen.
90 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCallf7a1a742009-11-24 19:00:30 +000091 LookupResult::Filter filter = R.makeFilter();
92 while (filter.hasNext()) {
93 NamedDecl *Orig = filter.next();
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +000094 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
95 AllowFunctionTemplates);
John McCallf7a1a742009-11-24 19:00:30 +000096 if (!Repl)
97 filter.erase();
Douglas Gregor01e56ae2010-04-12 20:54:26 +000098 else if (Repl != Orig) {
99
100 // C++ [temp.local]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000101 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000102 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000103 // one base class). If all of the injected-class-names that are found
104 // refer to specializations of the same class template, and if the name
Richard Smith3e4c6c42011-05-05 21:57:07 +0000105 // is used as a template-name, the reference refers to the class
106 // template itself and not a specialization thereof, and is not
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000107 // ambiguous.
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000108 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
109 if (!ClassTemplates.insert(ClassTmpl)) {
110 filter.erase();
111 continue;
112 }
John McCall8ba66912010-08-13 07:02:08 +0000113
114 // FIXME: we promote access to public here as a workaround to
115 // the fact that LookupResult doesn't let us remember that we
116 // found this template through a particular injected class name,
117 // which means we end up doing nasty things to the invariants.
118 // Pretending that access is public is *much* safer.
119 filter.replace(Repl, AS_public);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000120 }
John McCallf7a1a742009-11-24 19:00:30 +0000121 }
122 filter.done();
123}
124
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000125bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
126 bool AllowFunctionTemplates) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000127 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000128 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor312eadb2011-04-24 05:37:28 +0000129 return true;
130
Douglas Gregor3b887352011-04-27 04:48:22 +0000131 return false;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000132}
133
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000134TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000135 CXXScopeSpec &SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000136 bool hasTemplateKeyword,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000137 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +0000138 ParsedType ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000139 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000140 TemplateTy &TemplateResult,
141 bool &MemberOfUnknownSpecialization) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000142 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000143
Douglas Gregor014e88d2009-11-03 23:16:33 +0000144 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000145 MemberOfUnknownSpecialization = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000146
Douglas Gregor014e88d2009-11-03 23:16:33 +0000147 switch (Name.getKind()) {
148 case UnqualifiedId::IK_Identifier:
149 TName = DeclarationName(Name.Identifier);
150 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000151
Douglas Gregor014e88d2009-11-03 23:16:33 +0000152 case UnqualifiedId::IK_OperatorFunctionId:
153 TName = Context.DeclarationNames.getCXXOperatorName(
154 Name.OperatorFunctionId.Operator);
155 break;
156
Sean Hunte6252d12009-11-28 08:58:14 +0000157 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000158 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
159 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000160
Douglas Gregor014e88d2009-11-03 23:16:33 +0000161 default:
162 return TNK_Non_template;
163 }
Mike Stump1eb44332009-09-09 15:08:12 +0000164
John McCallb3d87482010-08-24 05:47:05 +0000165 QualType ObjectType = ObjectTypePtr.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Daniel Dunbar96a00142012-03-09 18:35:03 +0000167 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000168 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
169 MemberOfUnknownSpecialization);
John McCall67d22fb2010-08-28 20:17:00 +0000170 if (R.empty()) return TNK_Non_template;
171 if (R.isAmbiguous()) {
172 // Suppress diagnostics; we'll redo this lookup later.
John McCallb8592062010-08-13 02:23:42 +0000173 R.suppressDiagnostics();
John McCall67d22fb2010-08-28 20:17:00 +0000174
175 // FIXME: we might have ambiguous templates, in which case we
176 // should at least parse them properly!
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000177 return TNK_Non_template;
John McCallb8592062010-08-13 02:23:42 +0000178 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000179
John McCall0bd6feb2009-12-02 08:04:21 +0000180 TemplateName Template;
181 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000182
John McCall0bd6feb2009-12-02 08:04:21 +0000183 unsigned ResultCount = R.end() - R.begin();
184 if (ResultCount > 1) {
185 // We assume that we'll preserve the qualifier from a function
186 // template name in other ways.
187 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
188 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000189
190 // We'll do this lookup again later.
191 R.suppressDiagnostics();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000192 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000193 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
194
195 if (SS.isSet() && !SS.isInvalid()) {
196 NestedNameSpecifier *Qualifier
197 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c153532010-08-06 12:11:11 +0000198 Template = Context.getQualifiedTemplateName(Qualifier,
199 hasTemplateKeyword, TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000200 } else {
201 Template = TemplateName(TD);
202 }
203
John McCallb8592062010-08-13 02:23:42 +0000204 if (isa<FunctionTemplateDecl>(TD)) {
John McCall0bd6feb2009-12-02 08:04:21 +0000205 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000206
207 // We'll do this lookup again later.
208 R.suppressDiagnostics();
209 } else {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000210 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
211 isa<TypeAliasTemplateDecl>(TD));
John McCall0bd6feb2009-12-02 08:04:21 +0000212 TemplateKind = TNK_Type_template;
213 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000214 }
Mike Stump1eb44332009-09-09 15:08:12 +0000215
John McCall0bd6feb2009-12-02 08:04:21 +0000216 TemplateResult = TemplateTy::make(Template);
217 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000218}
219
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000220bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor84d0a192010-01-12 21:28:44 +0000221 SourceLocation IILoc,
222 Scope *S,
223 const CXXScopeSpec *SS,
224 TemplateTy &SuggestedTemplate,
225 TemplateNameKind &SuggestedKind) {
226 // We can't recover unless there's a dependent scope specifier preceding the
227 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000228 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000229 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
230 computeDeclContext(*SS))
231 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000232
Douglas Gregor84d0a192010-01-12 21:28:44 +0000233 // The code is missing a 'template' keyword prior to the dependent template
234 // name.
235 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
236 Diag(IILoc, diag::err_template_kw_missing)
237 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000238 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000239 SuggestedTemplate
Douglas Gregor84d0a192010-01-12 21:28:44 +0000240 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
241 SuggestedKind = TNK_Dependent_template_name;
242 return true;
243}
244
John McCallf7a1a742009-11-24 19:00:30 +0000245void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000246 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000247 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000248 bool EnteringContext,
249 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000250 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000251 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000252 DeclContext *LookupCtx = 0;
253 bool isDependent = false;
254 if (!ObjectType.isNull()) {
255 // This nested-name-specifier occurs in a member access expression, e.g.,
256 // x->B::f, and we are looking into the type of the object.
257 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
258 LookupCtx = computeDeclContext(ObjectType);
259 isDependent = ObjectType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000260 assert((isDependent || !ObjectType->isIncompleteType()) &&
John McCallf7a1a742009-11-24 19:00:30 +0000261 "Caller should have completed object type");
Douglas Gregor1d7049a2012-01-12 16:11:24 +0000262
263 // Template names cannot appear inside an Objective-C class or object type.
264 if (ObjectType->isObjCObjectOrInterfaceType()) {
265 Found.clear();
266 return;
267 }
John McCallf7a1a742009-11-24 19:00:30 +0000268 } else if (SS.isSet()) {
269 // This nested-name-specifier occurs after another nested-name-specifier,
270 // so long into the context associated with the prior nested-name-specifier.
271 LookupCtx = computeDeclContext(SS, EnteringContext);
272 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000273
John McCallf7a1a742009-11-24 19:00:30 +0000274 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000275 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000276 return;
277 }
278
279 bool ObjectTypeSearchedInScope = false;
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000280 bool AllowFunctionTemplatesInLookup = true;
John McCallf7a1a742009-11-24 19:00:30 +0000281 if (LookupCtx) {
282 // Perform "qualified" name lookup into the declaration context we
283 // computed, which is either the type of the base of a member access
284 // expression or the declaration context associated with a prior
285 // nested-name-specifier.
286 LookupQualifiedName(Found, LookupCtx);
John McCallf7a1a742009-11-24 19:00:30 +0000287 if (!ObjectType.isNull() && Found.empty()) {
288 // C++ [basic.lookup.classref]p1:
289 // In a class member access expression (5.2.5), if the . or -> token is
290 // immediately followed by an identifier followed by a <, the
291 // identifier must be looked up to determine whether the < is the
292 // beginning of a template argument list (14.2) or a less-than operator.
293 // The identifier is first looked up in the class of the object
294 // expression. If the identifier is not found, it is then looked up in
295 // the context of the entire postfix-expression and shall name a class
296 // or function template.
John McCallf7a1a742009-11-24 19:00:30 +0000297 if (S) LookupName(Found, S);
298 ObjectTypeSearchedInScope = true;
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000299 AllowFunctionTemplatesInLookup = false;
John McCallf7a1a742009-11-24 19:00:30 +0000300 }
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000301 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000302 // We cannot look into a dependent object type or nested nme
303 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000304 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000305 return;
306 } else {
307 // Perform unqualified name lookup in the current scope.
308 LookupName(Found, S);
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000309
310 if (!ObjectType.isNull())
311 AllowFunctionTemplatesInLookup = false;
John McCallf7a1a742009-11-24 19:00:30 +0000312 }
313
Douglas Gregor2e933882010-01-12 17:06:20 +0000314 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000315 // If we did not find any names, attempt to correct any typos.
316 DeclarationName Name = Found.getLookupName();
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000317 Found.clear();
Kaelyn Uhrainf8ec8c92012-01-13 23:10:36 +0000318 // Simple filter callback that, for keywords, only accepts the C++ *_cast
319 CorrectionCandidateCallback FilterCCC;
320 FilterCCC.WantTypeSpecifiers = false;
321 FilterCCC.WantExpressionKeywords = false;
322 FilterCCC.WantRemainingKeywords = false;
323 FilterCCC.WantCXXNamedCasts = true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000324 if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(),
325 Found.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000326 FilterCCC, LookupCtx)) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000327 Found.setLookupName(Corrected.getCorrection());
328 if (Corrected.getCorrectionDecl())
329 Found.addDecl(Corrected.getCorrectionDecl());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000330 FilterAcceptableTemplateNames(Found);
John McCallad00b772010-06-16 08:42:20 +0000331 if (!Found.empty()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000332 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
333 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregorbfea2392009-12-31 08:11:17 +0000334 if (LookupCtx)
335 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000336 << Name << LookupCtx << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +0000337 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
338 CorrectedStr);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000339 else
340 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000341 << Name << CorrectedQuotedStr
342 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000343 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
344 Diag(Template->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000345 << CorrectedQuotedStr;
John McCallad00b772010-06-16 08:42:20 +0000346 }
Douglas Gregorbfea2392009-12-31 08:11:17 +0000347 } else {
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000348 Found.setLookupName(Name);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000349 }
350 }
351
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000352 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000353 if (Found.empty()) {
354 if (isDependent)
355 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000356 return;
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000357 }
John McCallf7a1a742009-11-24 19:00:30 +0000358
Douglas Gregor05e60762012-05-01 20:23:02 +0000359 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
360 !(getLangOpts().CPlusPlus0x && !Found.empty())) {
361 // C++03 [basic.lookup.classref]p1:
John McCallf7a1a742009-11-24 19:00:30 +0000362 // [...] If the lookup in the class of the object expression finds a
363 // template, the name is also looked up in the context of the entire
364 // postfix-expression and [...]
365 //
Douglas Gregor05e60762012-05-01 20:23:02 +0000366 // Note: C++11 does not perform this second lookup.
John McCallf7a1a742009-11-24 19:00:30 +0000367 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
368 LookupOrdinaryName);
369 LookupName(FoundOuter, S);
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000370 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000371
John McCallf7a1a742009-11-24 19:00:30 +0000372 if (FoundOuter.empty()) {
373 // - if the name is not found, the name found in the class of the
374 // object expression is used, otherwise
Douglas Gregora6d1e762011-08-10 21:59:45 +0000375 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
376 FoundOuter.isAmbiguous()) {
John McCallf7a1a742009-11-24 19:00:30 +0000377 // - if the name is found in the context of the entire
378 // postfix-expression and does not name a class template, the name
379 // found in the class of the object expression is used, otherwise
Douglas Gregora6d1e762011-08-10 21:59:45 +0000380 FoundOuter.clear();
John McCallad00b772010-06-16 08:42:20 +0000381 } else if (!Found.isSuppressingDiagnostics()) {
John McCallf7a1a742009-11-24 19:00:30 +0000382 // - if the name found is a class template, it must refer to the same
383 // entity as the one found in the class of the object expression,
384 // otherwise the program is ill-formed.
385 if (!Found.isSingleResult() ||
386 Found.getFoundDecl()->getCanonicalDecl()
387 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000388 Diag(Found.getNameLoc(),
Jeffrey Yasskin21d07e42010-06-05 01:39:57 +0000389 diag::ext_nested_name_member_ref_lookup_ambiguous)
390 << Found.getLookupName()
391 << ObjectType;
John McCallf7a1a742009-11-24 19:00:30 +0000392 Diag(Found.getRepresentativeDecl()->getLocation(),
393 diag::note_ambig_member_ref_object_type)
394 << ObjectType;
395 Diag(FoundOuter.getFoundDecl()->getLocation(),
396 diag::note_ambig_member_ref_scope);
397
398 // Recover by taking the template that we found in the object
399 // expression's type.
400 }
401 }
402 }
403}
404
John McCall2f841ba2009-12-02 03:53:29 +0000405/// ActOnDependentIdExpression - Handle a dependent id-expression that
406/// was just parsed. This is only possible with an explicit scope
407/// specifier naming a dependent type.
John McCall60d7b3a2010-08-24 06:29:42 +0000408ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000409Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000410 SourceLocation TemplateKWLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +0000411 const DeclarationNameInfo &NameInfo,
John McCall2f841ba2009-12-02 03:53:29 +0000412 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000413 const TemplateArgumentListInfo *TemplateArgs) {
John McCallea1471e2010-05-20 01:18:31 +0000414 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000415
John McCall2f841ba2009-12-02 03:53:29 +0000416 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000417 isa<CXXMethodDecl>(DC) &&
418 cast<CXXMethodDecl>(DC)->isInstance()) {
419 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000420
John McCallf7a1a742009-11-24 19:00:30 +0000421 // Since the 'this' expression is synthesized, we don't need to
422 // perform the double-lookup check.
423 NamedDecl *FirstQualifierInScope = 0;
424
John McCallaa81e162009-12-01 22:10:20 +0000425 return Owned(CXXDependentScopeMemberExpr::Create(Context,
426 /*This*/ 0, ThisType,
427 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000428 /*Op*/ SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +0000429 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000430 TemplateKWLoc,
John McCallf7a1a742009-11-24 19:00:30 +0000431 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +0000432 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000433 TemplateArgs));
434 }
435
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000436 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +0000437}
438
John McCall60d7b3a2010-08-24 06:29:42 +0000439ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000440Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000441 SourceLocation TemplateKWLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +0000442 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000443 const TemplateArgumentListInfo *TemplateArgs) {
444 return Owned(DependentScopeDeclRefExpr::Create(Context,
Douglas Gregor00cf3cc2011-02-25 20:49:16 +0000445 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000446 TemplateKWLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +0000447 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000448 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000449}
450
Douglas Gregor72c3f312008-12-05 18:15:24 +0000451/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
452/// that the template parameter 'PrevDecl' is being shadowed by a new
453/// declaration at location Loc. Returns true to indicate that this is
454/// an error, and false otherwise.
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000455void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000456 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000457
458 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikie4e4d0842012-03-11 07:00:24 +0000459 if (getLangOpts().MicrosoftExt)
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000460 return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000461
462 // C++ [temp.local]p4:
463 // A template-parameter shall not be redeclared within its
464 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000465 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000466 << cast<NamedDecl>(PrevDecl)->getDeclName();
467 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000468 return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000469}
470
Douglas Gregor2943aed2009-03-03 04:44:36 +0000471/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000472/// the parameter D to reference the templated declaration and return a pointer
473/// to the template declaration. Otherwise, do nothing to D and return null.
John McCalld226f652010-08-21 09:40:31 +0000474TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
475 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
476 D = Temp->getTemplatedDecl();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000477 return Temp;
478 }
479 return 0;
480}
481
Douglas Gregorba68eca2011-01-05 17:40:24 +0000482ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
483 SourceLocation EllipsisLoc) const {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000484 assert(Kind == Template &&
Douglas Gregorba68eca2011-01-05 17:40:24 +0000485 "Only template template arguments can be pack expansions here");
486 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
487 "Template template argument pack expansion without packs");
488 ParsedTemplateArgument Result(*this);
489 Result.EllipsisLoc = EllipsisLoc;
490 return Result;
491}
492
Douglas Gregor788cd062009-11-11 01:00:40 +0000493static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
494 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000495
Douglas Gregor788cd062009-11-11 01:00:40 +0000496 switch (Arg.getKind()) {
497 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000498 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000499 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000500 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000501 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000502 return TemplateArgumentLoc(TemplateArgument(T), DI);
503 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000504
Douglas Gregor788cd062009-11-11 01:00:40 +0000505 case ParsedTemplateArgument::NonType: {
506 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
507 return TemplateArgumentLoc(TemplateArgument(E), E);
508 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000509
Douglas Gregor788cd062009-11-11 01:00:40 +0000510 case ParsedTemplateArgument::Template: {
John McCall2b5289b2010-08-23 07:28:44 +0000511 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor2be29f42011-01-14 23:41:42 +0000512 TemplateArgument TArg;
513 if (Arg.getEllipsisLoc().isValid())
514 TArg = TemplateArgument(Template, llvm::Optional<unsigned int>());
515 else
516 TArg = Template;
517 return TemplateArgumentLoc(TArg,
Douglas Gregorb6744ef2011-03-02 17:09:35 +0000518 Arg.getScopeSpec().getWithLocInContext(
519 SemaRef.Context),
Douglas Gregorba68eca2011-01-05 17:40:24 +0000520 Arg.getLocation(),
521 Arg.getEllipsisLoc());
Douglas Gregor788cd062009-11-11 01:00:40 +0000522 }
523 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000524
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000525 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000526}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000527
Douglas Gregor788cd062009-11-11 01:00:40 +0000528/// \brief Translates template arguments as provided by the parser
529/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000530void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
531 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000532 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000533 TemplateArgs.addArgument(translateTemplateArgument(*this,
534 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000535}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000536
Douglas Gregor72c3f312008-12-05 18:15:24 +0000537/// ActOnTypeParameter - Called when a C++ template type parameter
538/// (e.g., "typename T") has been parsed. Typename specifies whether
539/// the keyword "typename" was used to declare the type parameter
540/// (otherwise, "class" was used), and KeyLoc is the location of the
541/// "class" or "typename" keyword. ParamName is the name of the
542/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000543/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000544/// If the type parameter has a default argument, it will be added
545/// later via ActOnTypeParameterDefault.
John McCalld226f652010-08-21 09:40:31 +0000546Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
547 SourceLocation EllipsisLoc,
548 SourceLocation KeyLoc,
549 IdentifierInfo *ParamName,
550 SourceLocation ParamNameLoc,
551 unsigned Depth, unsigned Position,
552 SourceLocation EqualLoc,
John McCallb3d87482010-08-24 05:47:05 +0000553 ParsedType DefaultArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000554 assert(S->isTemplateParamScope() &&
555 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000556 bool Invalid = false;
557
558 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000559 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000560 LookupOrdinaryName,
561 ForRedeclaration);
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000562 if (PrevDecl && PrevDecl->isTemplateParameter()) {
563 DiagnoseTemplateParameterShadow(ParamNameLoc, PrevDecl);
564 PrevDecl = 0;
565 }
Douglas Gregor72c3f312008-12-05 18:15:24 +0000566 }
567
Douglas Gregorddc29e12009-02-06 22:42:48 +0000568 SourceLocation Loc = ParamNameLoc;
569 if (!ParamName)
570 Loc = KeyLoc;
571
Douglas Gregor72c3f312008-12-05 18:15:24 +0000572 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000573 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000574 KeyLoc, Loc, Depth, Position, ParamName,
575 Typename, Ellipsis);
Douglas Gregor9a299e02011-03-04 17:52:15 +0000576 Param->setAccess(AS_public);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000577 if (Invalid)
578 Param->setInvalidDecl();
579
580 if (ParamName) {
581 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000582 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000583 IdResolver.AddDecl(Param);
584 }
585
Douglas Gregor61c4d282011-01-05 15:48:55 +0000586 // C++0x [temp.param]p9:
587 // A default template-argument may be specified for any kind of
588 // template-parameter that is not a template parameter pack.
589 if (DefaultArg && Ellipsis) {
590 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
591 DefaultArg = ParsedType();
592 }
593
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000594 // Handle the default argument, if provided.
595 if (DefaultArg) {
596 TypeSourceInfo *DefaultTInfo;
597 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000598
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000599 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000600
Douglas Gregor6f526752010-12-16 08:48:57 +0000601 // Check for unexpanded parameter packs.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000602 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6f526752010-12-16 08:48:57 +0000603 UPPC_DefaultArgument))
604 return Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000605
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000606 // Check the template argument itself.
607 if (CheckTemplateArgument(Param, DefaultTInfo)) {
608 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000609 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000610 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000611
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000612 Param->setDefaultArgument(DefaultTInfo, false);
613 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000614
John McCalld226f652010-08-21 09:40:31 +0000615 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000616}
617
Douglas Gregor2943aed2009-03-03 04:44:36 +0000618/// \brief Check that the type of a non-type template parameter is
619/// well-formed.
620///
621/// \returns the (possibly-promoted) parameter type if valid;
622/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000623QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000624Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000625 // We don't allow variably-modified types as the type of non-type template
626 // parameters.
627 if (T->isVariablyModifiedType()) {
628 Diag(Loc, diag::err_variably_modified_nontype_template_param)
629 << T;
630 return QualType();
631 }
632
Douglas Gregor2943aed2009-03-03 04:44:36 +0000633 // C++ [temp.param]p4:
634 //
635 // A non-type template-parameter shall have one of the following
636 // (optionally cv-qualified) types:
637 //
638 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000639 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000640 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000641 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000642 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000643 T->isReferenceType() ||
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000644 // -- pointer to member,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000645 T->isMemberPointerType() ||
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000646 // -- std::nullptr_t.
647 T->isNullPtrType() ||
Douglas Gregor2943aed2009-03-03 04:44:36 +0000648 // If T is a dependent type, we can't do the check now, so we
649 // assume that it is well-formed.
Richard Smithe37f4842012-03-13 07:21:50 +0000650 T->isDependentType()) {
651 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
652 // are ignored when determining its type.
653 return T.getUnqualifiedType();
654 }
655
Douglas Gregor2943aed2009-03-03 04:44:36 +0000656 // C++ [temp.param]p8:
657 //
658 // A non-type template-parameter of type "array of T" or
659 // "function returning T" is adjusted to be of type "pointer to
660 // T" or "pointer to function returning T", respectively.
661 else if (T->isArrayType())
662 // FIXME: Keep the type prior to promotion?
663 return Context.getArrayDecayedType(T);
664 else if (T->isFunctionType())
665 // FIXME: Keep the type prior to promotion?
666 return Context.getPointerType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000667
Douglas Gregor2943aed2009-03-03 04:44:36 +0000668 Diag(Loc, diag::err_template_nontype_parm_bad_type)
669 << T;
670
671 return QualType();
672}
673
John McCalld226f652010-08-21 09:40:31 +0000674Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
675 unsigned Depth,
676 unsigned Position,
677 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000678 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000679 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
680 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000681
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000682 assert(S->isTemplateParamScope() &&
683 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000684 bool Invalid = false;
685
686 IdentifierInfo *ParamName = D.getIdentifier();
687 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000688 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000689 LookupOrdinaryName,
690 ForRedeclaration);
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000691 if (PrevDecl && PrevDecl->isTemplateParameter()) {
692 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
693 PrevDecl = 0;
694 }
Douglas Gregor72c3f312008-12-05 18:15:24 +0000695 }
696
Douglas Gregor4d2abba2010-12-16 15:36:43 +0000697 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
698 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000699 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000700 Invalid = true;
701 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000702
Douglas Gregor10738d32010-12-23 23:51:58 +0000703 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000704 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000705 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar96a00142012-03-09 18:35:03 +0000706 D.getLocStart(),
John McCall7a9813c2010-01-22 00:28:27 +0000707 D.getIdentifierLoc(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000708 Depth, Position, ParamName, T,
Douglas Gregor10738d32010-12-23 23:51:58 +0000709 IsParameterPack, TInfo);
Douglas Gregor9a299e02011-03-04 17:52:15 +0000710 Param->setAccess(AS_public);
711
Douglas Gregor72c3f312008-12-05 18:15:24 +0000712 if (Invalid)
713 Param->setInvalidDecl();
714
715 if (D.getIdentifier()) {
716 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000717 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000718 IdResolver.AddDecl(Param);
719 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000720
Douglas Gregor61c4d282011-01-05 15:48:55 +0000721 // C++0x [temp.param]p9:
722 // A default template-argument may be specified for any kind of
723 // template-parameter that is not a template parameter pack.
724 if (Default && IsParameterPack) {
725 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
726 Default = 0;
727 }
728
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000729 // Check the well-formedness of the default template argument, if provided.
Douglas Gregor10738d32010-12-23 23:51:58 +0000730 if (Default) {
Douglas Gregor6f526752010-12-16 08:48:57 +0000731 // Check for unexpanded parameter packs.
732 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
733 return Param;
734
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000735 TemplateArgument Converted;
John Wiegley429bb272011-04-08 18:41:53 +0000736 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
737 if (DefaultRes.isInvalid()) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000738 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000739 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000740 }
John Wiegley429bb272011-04-08 18:41:53 +0000741 Default = DefaultRes.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000742
John McCall9ae2f072010-08-23 23:25:46 +0000743 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000744 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000745
John McCalld226f652010-08-21 09:40:31 +0000746 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000747}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000748
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000749/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett699c9042012-06-15 07:13:21 +0000750/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000751/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000752Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
753 SourceLocation TmpLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +0000754 TemplateParameterList *Params,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000755 SourceLocation EllipsisLoc,
John McCalld226f652010-08-21 09:40:31 +0000756 IdentifierInfo *Name,
757 SourceLocation NameLoc,
758 unsigned Depth,
759 unsigned Position,
760 SourceLocation EqualLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000761 ParsedTemplateArgument Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000762 assert(S->isTemplateParamScope() &&
763 "Template template parameter not in template parameter scope!");
764
765 // Construct the parameter object.
Douglas Gregor61c4d282011-01-05 15:48:55 +0000766 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000767 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000768 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000769 NameLoc.isInvalid()? TmpLoc : NameLoc,
770 Depth, Position, IsParameterPack,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000771 Name, Params);
Douglas Gregor9a299e02011-03-04 17:52:15 +0000772 Param->setAccess(AS_public);
773
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000774 // If the template template parameter has a name, then link the identifier
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000775 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000776 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000777 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000778 IdResolver.AddDecl(Param);
779 }
780
Douglas Gregor6f526752010-12-16 08:48:57 +0000781 if (Params->size() == 0) {
782 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
783 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
784 Param->setInvalidDecl();
785 }
786
Douglas Gregor61c4d282011-01-05 15:48:55 +0000787 // C++0x [temp.param]p9:
788 // A default template-argument may be specified for any kind of
789 // template-parameter that is not a template parameter pack.
790 if (IsParameterPack && !Default.isInvalid()) {
791 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
792 Default = ParsedTemplateArgument();
793 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000794
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000795 if (!Default.isInvalid()) {
796 // Check only that we have a template template argument. We don't want to
797 // try to check well-formedness now, because our template template parameter
798 // might have dependent types in its template parameters, which we wouldn't
799 // be able to match now.
800 //
801 // If none of the template template parameter's template arguments mention
802 // other template parameters, we could actually perform more checking here.
803 // However, it isn't worth doing.
804 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
805 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
806 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
807 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000808 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000809 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000810
Douglas Gregor6f526752010-12-16 08:48:57 +0000811 // Check for unexpanded parameter packs.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000812 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6f526752010-12-16 08:48:57 +0000813 DefaultArg.getArgument().getAsTemplate(),
814 UPPC_DefaultArgument))
815 return Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000816
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000817 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000818 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000819
John McCalld226f652010-08-21 09:40:31 +0000820 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000821}
822
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000823/// ActOnTemplateParameterList - Builds a TemplateParameterList that
824/// contains the template parameters in Params/NumParams.
Richard Trieu90ab75b2011-09-09 03:18:59 +0000825TemplateParameterList *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000826Sema::ActOnTemplateParameterList(unsigned Depth,
827 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000828 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000829 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000830 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000831 SourceLocation RAngleLoc) {
832 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000833 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000834
Douglas Gregorddc29e12009-02-06 22:42:48 +0000835 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000836 (NamedDecl**)Params, NumParams,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000837 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000838}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000839
John McCallb6217662010-03-15 10:12:16 +0000840static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
841 if (SS.isSet())
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000842 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCallb6217662010-03-15 10:12:16 +0000843}
844
John McCallf312b1e2010-08-26 23:41:50 +0000845DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000846Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000847 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000848 IdentifierInfo *Name, SourceLocation NameLoc,
849 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000850 TemplateParameterList *TemplateParams,
Douglas Gregore7612302011-09-09 19:05:14 +0000851 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +0000852 unsigned NumOuterTemplateParamLists,
853 TemplateParameterList** OuterTemplateParamLists) {
Mike Stump1eb44332009-09-09 15:08:12 +0000854 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000855 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000856 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000857 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000858
859 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000860 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000861 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000862
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000863 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
864 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000865
866 // There is no such thing as an unnamed class template.
867 if (!Name) {
868 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000869 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000870 }
871
Richard Smith71c598f2012-04-21 01:27:54 +0000872 // Find any previous declaration with this name. For a friend with no
873 // scope explicitly specified, we only look for tag declarations (per
874 // C++11 [basic.lookup.elab]p2).
Douglas Gregor05396e22009-08-25 17:23:04 +0000875 DeclContext *SemanticContext;
Richard Smith71c598f2012-04-21 01:27:54 +0000876 LookupResult Previous(*this, Name, NameLoc,
877 (SS.isEmpty() && TUK == TUK_Friend)
878 ? LookupTagName : LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000879 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000880 if (SS.isNotEmpty() && !SS.isInvalid()) {
881 SemanticContext = computeDeclContext(SS, true);
882 if (!SemanticContext) {
Douglas Gregor8b0fa522012-03-30 16:20:47 +0000883 // FIXME: Horrible, horrible hack! We can't currently represent this
884 // in the AST, and historically we have just ignored such friend
885 // class templates, so don't complain here.
886 if (TUK != TUK_Friend)
887 Diag(NameLoc, diag::err_template_qualified_declarator_no_match)
888 << SS.getScopeRep() << SS.getRange();
Douglas Gregor05396e22009-08-25 17:23:04 +0000889 return true;
890 }
Mike Stump1eb44332009-09-09 15:08:12 +0000891
John McCall77bb1aa2010-05-01 00:40:08 +0000892 if (RequireCompleteDeclContext(SS, SemanticContext))
893 return true;
894
Douglas Gregor20606502011-10-14 15:31:12 +0000895 // If we're adding a template to a dependent context, we may need to
896 // rebuilding some of the types used within the template parameter list,
897 // now that we know what the current instantiation is.
898 if (SemanticContext->isDependentContext()) {
899 ContextRAII SavedContext(*this, SemanticContext);
900 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
901 Invalid = true;
Douglas Gregor69605872012-03-28 16:01:27 +0000902 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
903 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith71c598f2012-04-21 01:27:54 +0000904
John McCalla24dc2e2009-11-17 02:14:36 +0000905 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000906 } else {
907 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000908 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000909 }
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Douglas Gregor57265e32010-04-12 16:00:01 +0000911 if (Previous.isAmbiguous())
912 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000913
Douglas Gregorddc29e12009-02-06 22:42:48 +0000914 NamedDecl *PrevDecl = 0;
915 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000916 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000917
Douglas Gregorddc29e12009-02-06 22:42:48 +0000918 // If there is a previous declaration with the same name, check
919 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000920 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000921 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000922
923 // We may have found the injected-class-name of a class template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000924 // class template partial specialization, or class template specialization.
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000925 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000926 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000927 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
928 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000929 PrevClassTemplate
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000930 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
931 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
932 PrevClassTemplate
933 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
934 ->getSpecializedTemplate();
935 }
936 }
937
John McCall65c49462009-12-18 11:25:59 +0000938 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000939 // C++ [namespace.memdef]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000940 // [...] When looking for a prior declaration of a class or a function
941 // declared as a friend, and when the name of the friend class or
John McCalle129d442009-12-17 23:21:11 +0000942 // function is neither a qualified name nor a template-id, scopes outside
943 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000944 if (!SS.isSet()) {
945 DeclContext *OutermostContext = CurContext;
946 while (!OutermostContext->isFileContext())
947 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000948
Richard Smithc93e0142012-04-20 07:12:26 +0000949 if (PrevDecl &&
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000950 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
951 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
952 SemanticContext = PrevDecl->getDeclContext();
953 } else {
954 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000955 // context we computed is the semantic context for our new
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000956 // declaration.
957 PrevDecl = PrevClassTemplate = 0;
958 SemanticContext = OutermostContext;
Richard Smith71c598f2012-04-21 01:27:54 +0000959
960 // Check that the chosen semantic context doesn't already contain a
961 // declaration of this name as a non-tag type.
962 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
963 ForRedeclaration);
964 DeclContext *LookupContext = SemanticContext;
965 while (LookupContext->isTransparentContext())
966 LookupContext = LookupContext->getLookupParent();
967 LookupQualifiedName(Previous, LookupContext);
968
969 if (Previous.isAmbiguous())
970 return true;
971
972 if (Previous.begin() != Previous.end())
973 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000974 }
John McCalle129d442009-12-17 23:21:11 +0000975 }
John McCalle129d442009-12-17 23:21:11 +0000976 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
977 PrevDecl = PrevClassTemplate = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000978
Douglas Gregorddc29e12009-02-06 22:42:48 +0000979 if (PrevClassTemplate) {
Richard Smith6e21b162012-04-22 02:13:50 +0000980 // Ensure that the template parameter lists are compatible. Skip this check
981 // for a friend in a dependent context: the template parameter list itself
982 // could be dependent.
983 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
984 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000985 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000986 /*Complain=*/true,
987 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000988 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000989
990 // C++ [temp.class]p4:
991 // In a redeclaration, partial specialization, explicit
992 // specialization or explicit instantiation of a class template,
993 // the class-key shall agree in kind with the original class
994 // template declaration (7.1.5.3).
995 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieubbf34c02011-06-10 03:11:26 +0000996 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
997 TUK == TUK_Definition, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000998 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000999 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +00001000 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001001 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +00001002 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +00001003 }
1004
Douglas Gregorddc29e12009-02-06 22:42:48 +00001005 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +00001006 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001007 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001008 Diag(NameLoc, diag::err_redefinition) << Name;
1009 Diag(Def->getLocation(), diag::note_previous_definition);
1010 // FIXME: Would it make sense to try to "forget" the previous
1011 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +00001012 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +00001013 }
Douglas Gregor6311d2b2011-09-09 18:32:39 +00001014 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00001015 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1016 // Maybe we will complain about the shadowed template parameter.
1017 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1018 // Just pretend that we didn't see the previous declaration.
1019 PrevDecl = 0;
1020 } else if (PrevDecl) {
1021 // C++ [temp]p5:
1022 // A class template shall not have the same name as any other
1023 // template, class, function, object, enumeration, enumerator,
1024 // namespace, or type in the same scope (3.3), except as specified
1025 // in (14.5.4).
1026 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1027 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +00001028 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +00001029 }
1030
Douglas Gregord684b002009-02-10 19:49:53 +00001031 // Check the template parameter list of this declaration, possibly
1032 // merging in the template parameter list from the previous class
Richard Smith6e21b162012-04-22 02:13:50 +00001033 // template declaration. Skip this check for a friend in a dependent
1034 // context, because the template parameter list might be dependent.
1035 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1036 CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001037 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +00001038 (SS.isSet() && SemanticContext &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +00001039 SemanticContext->isRecord() &&
1040 SemanticContext->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +00001041 ? TPC_ClassTemplateMember
1042 : TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +00001043 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Douglas Gregor57265e32010-04-12 16:00:01 +00001045 if (SS.isSet()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001046 // If the name of the template was qualified, we must be defining the
Douglas Gregor57265e32010-04-12 16:00:01 +00001047 // template out-of-line.
Richard Smith6e21b162012-04-22 02:13:50 +00001048 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1049 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1050 : diag::err_member_def_does_not_match)
Douglas Gregor57265e32010-04-12 16:00:01 +00001051 << Name << SemanticContext << SS.getRange();
Douglas Gregorea9f54a2011-11-01 21:35:16 +00001052 Invalid = true;
1053 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001054 }
1055
Mike Stump1eb44332009-09-09 15:08:12 +00001056 CXXRecordDecl *NewClass =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001057 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump1eb44332009-09-09 15:08:12 +00001058 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +00001059 PrevClassTemplate->getTemplatedDecl() : 0,
1060 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +00001061 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00001062 if (NumOuterTemplateParamLists > 0)
1063 NewClass->setTemplateParameterListsInfo(Context,
1064 NumOuterTemplateParamLists,
1065 OuterTemplateParamLists);
Douglas Gregorddc29e12009-02-06 22:42:48 +00001066
Eli Friedman572ae0a2012-02-10 02:02:21 +00001067 // Add alignment attributes if necessary; these attributes are checked when
1068 // the ASTContext lays out the structure.
Eli Friedman2016c8c2012-08-08 21:08:34 +00001069 if (TUK == TUK_Definition) {
1070 AddAlignmentAttributesForRecord(NewClass);
1071 AddMsStructLayoutForRecord(NewClass);
1072 }
Eli Friedman572ae0a2012-02-10 02:02:21 +00001073
Douglas Gregorddc29e12009-02-06 22:42:48 +00001074 ClassTemplateDecl *NewTemplate
1075 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1076 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001077 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +00001078 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregor6311d2b2011-09-09 18:32:39 +00001079
Douglas Gregor2ccd89c2011-12-20 18:11:52 +00001080 if (ModulePrivateLoc.isValid())
Douglas Gregor6311d2b2011-09-09 18:32:39 +00001081 NewTemplate->setModulePrivate();
Douglas Gregor8d267c52011-09-09 02:06:17 +00001082
Douglas Gregoraafc0cc2009-05-15 19:11:46 +00001083 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +00001084 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +00001085 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +00001086 assert(T->isDependentType() && "Class template type is not dependent?");
1087 (void)T;
1088
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001089 // If we are providing an explicit specialization of a member that is a
Douglas Gregorfd056bc2009-10-13 16:30:37 +00001090 // class template, make a note of that.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001091 if (PrevClassTemplate &&
Douglas Gregorfd056bc2009-10-13 16:30:37 +00001092 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1093 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001094
Anders Carlsson4cbe82c2009-03-26 01:24:28 +00001095 // Set the access specifier.
Douglas Gregor42acead2012-03-17 23:06:31 +00001096 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall05b23ea2009-09-14 21:59:20 +00001097 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Douglas Gregorddc29e12009-02-06 22:42:48 +00001099 // Set the lexical context of these templates
1100 NewClass->setLexicalDeclContext(CurContext);
1101 NewTemplate->setLexicalDeclContext(CurContext);
1102
John McCall0f434ec2009-07-31 02:45:11 +00001103 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001104 NewClass->startDefinition();
1105
1106 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001107 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +00001108
Rafael Espindola4bda1d82012-08-22 14:52:14 +00001109 if (PrevClassTemplate)
1110 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1111
Rafael Espindola6b603702012-07-13 18:04:45 +00001112 AddPushedVisibilityAttribute(NewClass);
1113
John McCall05b23ea2009-09-14 21:59:20 +00001114 if (TUK != TUK_Friend)
1115 PushOnScopeChains(NewTemplate, S);
1116 else {
Douglas Gregord85bea22009-09-26 06:47:28 +00001117 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +00001118 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +00001119 NewClass->setAccess(PrevClassTemplate->getAccess());
1120 }
John McCall05b23ea2009-09-14 21:59:20 +00001121
Douglas Gregord85bea22009-09-26 06:47:28 +00001122 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
1123 PrevClassTemplate != NULL);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001124
John McCall05b23ea2009-09-14 21:59:20 +00001125 // Friend templates are visible in fairly strange ways.
1126 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001127 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001128 DC->makeDeclVisibleInContext(NewTemplate);
John McCall05b23ea2009-09-14 21:59:20 +00001129 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1130 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001131 /* AddToContext = */ false);
John McCall05b23ea2009-09-14 21:59:20 +00001132 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001133
Douglas Gregord85bea22009-09-26 06:47:28 +00001134 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1135 NewClass->getLocation(),
1136 NewTemplate,
1137 /*FIXME:*/NewClass->getLocation());
1138 Friend->setAccess(AS_public);
1139 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +00001140 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00001141
Douglas Gregord684b002009-02-10 19:49:53 +00001142 if (Invalid) {
1143 NewTemplate->setInvalidDecl();
1144 NewClass->setInvalidDecl();
1145 }
Rafael Espindolad3d02dd2012-07-13 01:19:08 +00001146
Dmitri Gribenko96b09862012-07-31 22:37:06 +00001147 ActOnDocumentableDecl(NewTemplate);
1148
John McCalld226f652010-08-21 09:40:31 +00001149 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +00001150}
1151
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001152/// \brief Diagnose the presence of a default template argument on a
1153/// template parameter, which is ill-formed in certain contexts.
1154///
1155/// \returns true if the default template argument should be dropped.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001156static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001157 Sema::TemplateParamListContext TPC,
1158 SourceLocation ParamLoc,
1159 SourceRange DefArgRange) {
1160 switch (TPC) {
1161 case Sema::TPC_ClassTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +00001162 case Sema::TPC_TypeAliasTemplate:
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001163 return false;
1164
1165 case Sema::TPC_FunctionTemplate:
Douglas Gregord89d86f2011-02-04 04:20:44 +00001166 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001167 // C++ [temp.param]p9:
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001168 // A default template-argument shall not be specified in a
1169 // function template declaration or a function template
1170 // definition [...]
Douglas Gregord89d86f2011-02-04 04:20:44 +00001171 // If a friend function template declaration specifies a default
1172 // template-argument, that declaration shall be a definition and shall be
1173 // the only declaration of the function template in the translation unit.
1174 // (C++98/03 doesn't have this wording; see DR226).
David Blaikie4e4d0842012-03-11 07:00:24 +00001175 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001176 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1177 : diag::ext_template_parameter_default_in_function_template)
1178 << DefArgRange;
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001179 return false;
1180
1181 case Sema::TPC_ClassTemplateMember:
1182 // C++0x [temp.param]p9:
1183 // A default template-argument shall not be specified in the
1184 // template-parameter-lists of the definition of a member of a
1185 // class template that appears outside of the member's class.
1186 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1187 << DefArgRange;
1188 return true;
1189
1190 case Sema::TPC_FriendFunctionTemplate:
1191 // C++ [temp.param]p9:
1192 // A default template-argument shall not be specified in a
1193 // friend template declaration.
1194 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1195 << DefArgRange;
1196 return true;
1197
1198 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1199 // for friend function templates if there is only a single
1200 // declaration (and it is a definition). Strange!
1201 }
1202
David Blaikie7530c032012-01-17 06:56:22 +00001203 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001204}
1205
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001206/// \brief Check for unexpanded parameter packs within the template parameters
1207/// of a template template parameter, recursively.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001208static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1209 TemplateTemplateParmDecl *TTP) {
Richard Smith6964b3f2012-09-07 02:06:42 +00001210 // A template template parameter which is a parameter pack is also a pack
1211 // expansion.
1212 if (TTP->isParameterPack())
1213 return false;
1214
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001215 TemplateParameterList *Params = TTP->getTemplateParameters();
1216 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1217 NamedDecl *P = Params->getParam(I);
1218 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith6964b3f2012-09-07 02:06:42 +00001219 if (!NTTP->isParameterPack() &&
1220 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001221 NTTP->getTypeSourceInfo(),
1222 Sema::UPPC_NonTypeTemplateParameterType))
1223 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001224
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001225 continue;
1226 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001227
1228 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001229 = dyn_cast<TemplateTemplateParmDecl>(P))
1230 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1231 return true;
1232 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001233
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001234 return false;
1235}
1236
Douglas Gregord684b002009-02-10 19:49:53 +00001237/// \brief Checks the validity of a template parameter list, possibly
1238/// considering the template parameter list from a previous
1239/// declaration.
1240///
1241/// If an "old" template parameter list is provided, it must be
1242/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1243/// template parameter list.
1244///
1245/// \param NewParams Template parameter list for a new template
1246/// declaration. This template parameter list will be updated with any
1247/// default arguments that are carried through from the previous
1248/// template parameter list.
1249///
1250/// \param OldParams If provided, template parameter list from a
1251/// previous declaration of the same template. Default template
1252/// arguments will be merged from the old template parameter list to
1253/// the new template parameter list.
1254///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001255/// \param TPC Describes the context in which we are checking the given
1256/// template parameter list.
1257///
Douglas Gregord684b002009-02-10 19:49:53 +00001258/// \returns true if an error occurred, false otherwise.
1259bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001260 TemplateParameterList *OldParams,
1261 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001262 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Douglas Gregord684b002009-02-10 19:49:53 +00001264 // C++ [temp.param]p10:
1265 // The set of default template-arguments available for use with a
1266 // template declaration or definition is obtained by merging the
1267 // default arguments from the definition (if in scope) and all
1268 // declarations in scope in the same way default function
1269 // arguments are (8.3.6).
1270 bool SawDefaultArgument = false;
1271 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001272
Mike Stump1a35fde2009-02-11 23:03:27 +00001273 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001274 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001275 if (OldParams)
1276 OldParam = OldParams->begin();
1277
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001278 bool RemoveDefaultArguments = false;
Douglas Gregord684b002009-02-10 19:49:53 +00001279 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1280 NewParamEnd = NewParams->end();
1281 NewParam != NewParamEnd; ++NewParam) {
1282 // Variables used to diagnose redundant default arguments
1283 bool RedundantDefaultArg = false;
1284 SourceLocation OldDefaultLoc;
1285 SourceLocation NewDefaultLoc;
1286
David Blaikie1368e582011-10-19 05:19:50 +00001287 // Variable used to diagnose missing default arguments
Douglas Gregord684b002009-02-10 19:49:53 +00001288 bool MissingDefaultArg = false;
1289
David Blaikie1368e582011-10-19 05:19:50 +00001290 // Variable used to diagnose non-final parameter packs
1291 bool SawParameterPack = false;
Anders Carlsson49d25572009-06-12 23:20:15 +00001292
Douglas Gregord684b002009-02-10 19:49:53 +00001293 if (TemplateTypeParmDecl *NewTypeParm
1294 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001295 // Check the presence of a default argument here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001296 if (NewTypeParm->hasDefaultArgument() &&
1297 DiagnoseDefaultTemplateArgument(*this, TPC,
1298 NewTypeParm->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001299 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001300 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001301 NewTypeParm->removeDefaultArgument();
1302
1303 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001304 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001305 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Anders Carlsson49d25572009-06-12 23:20:15 +00001307 if (NewTypeParm->isParameterPack()) {
1308 assert(!NewTypeParm->hasDefaultArgument() &&
1309 "Parameter packs can't have a default argument!");
1310 SawParameterPack = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001311 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001312 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001313 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1314 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1315 SawDefaultArgument = true;
1316 RedundantDefaultArg = true;
1317 PreviousDefaultArgLoc = NewDefaultLoc;
1318 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1319 // Merge the default argument from the old declaration to the
1320 // new declaration.
1321 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001322 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001323 true);
1324 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1325 } else if (NewTypeParm->hasDefaultArgument()) {
1326 SawDefaultArgument = true;
1327 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1328 } else if (SawDefaultArgument)
1329 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001330 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001331 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001332 // Check for unexpanded parameter packs.
Richard Smith6964b3f2012-09-07 02:06:42 +00001333 if (!NewNonTypeParm->isParameterPack() &&
1334 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001335 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001336 UPPC_NonTypeTemplateParameterType)) {
1337 Invalid = true;
1338 continue;
1339 }
1340
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001341 // Check the presence of a default argument here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001342 if (NewNonTypeParm->hasDefaultArgument() &&
1343 DiagnoseDefaultTemplateArgument(*this, TPC,
1344 NewNonTypeParm->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001345 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001346 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001347 }
1348
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001349 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001350 NonTypeTemplateParmDecl *OldNonTypeParm
1351 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001352 if (NewNonTypeParm->isParameterPack()) {
1353 assert(!NewNonTypeParm->hasDefaultArgument() &&
1354 "Parameter packs can't have a default argument!");
Richard Smith6964b3f2012-09-07 02:06:42 +00001355 if (!NewNonTypeParm->isPackExpansion())
1356 SawParameterPack = true;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001357 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001358 NewNonTypeParm->hasDefaultArgument()) {
1359 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1360 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1361 SawDefaultArgument = true;
1362 RedundantDefaultArg = true;
1363 PreviousDefaultArgLoc = NewDefaultLoc;
1364 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1365 // Merge the default argument from the old declaration to the
1366 // new declaration.
1367 SawDefaultArgument = true;
1368 // FIXME: We need to create a new kind of "default argument"
Douglas Gregor61c4d282011-01-05 15:48:55 +00001369 // expression that points to a previous non-type template
Douglas Gregord684b002009-02-10 19:49:53 +00001370 // parameter.
1371 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001372 OldNonTypeParm->getDefaultArgument(),
1373 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001374 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1375 } else if (NewNonTypeParm->hasDefaultArgument()) {
1376 SawDefaultArgument = true;
1377 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1378 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001379 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001380 } else {
Douglas Gregord684b002009-02-10 19:49:53 +00001381 TemplateTemplateParmDecl *NewTemplateParm
1382 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001383
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001384 // Check for unexpanded parameter packs, recursively.
Douglas Gregor65019ac2011-10-25 03:44:56 +00001385 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001386 Invalid = true;
1387 continue;
1388 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001389
David Blaikie1368e582011-10-19 05:19:50 +00001390 // Check the presence of a default argument here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001391 if (NewTemplateParm->hasDefaultArgument() &&
1392 DiagnoseDefaultTemplateArgument(*this, TPC,
1393 NewTemplateParm->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001394 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001395 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001396
1397 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001398 TemplateTemplateParmDecl *OldTemplateParm
1399 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001400 if (NewTemplateParm->isParameterPack()) {
1401 assert(!NewTemplateParm->hasDefaultArgument() &&
1402 "Parameter packs can't have a default argument!");
Richard Smith6964b3f2012-09-07 02:06:42 +00001403 if (!NewTemplateParm->isPackExpansion())
1404 SawParameterPack = true;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001405 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001406 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001407 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1408 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001409 SawDefaultArgument = true;
1410 RedundantDefaultArg = true;
1411 PreviousDefaultArgLoc = NewDefaultLoc;
1412 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1413 // Merge the default argument from the old declaration to the
1414 // new declaration.
1415 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001416 // FIXME: We need to create a new kind of "default argument" expression
1417 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001418 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001419 OldTemplateParm->getDefaultArgument(),
1420 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001421 PreviousDefaultArgLoc
1422 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001423 } else if (NewTemplateParm->hasDefaultArgument()) {
1424 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001425 PreviousDefaultArgLoc
1426 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001427 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001428 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001429 }
1430
Richard Smith6964b3f2012-09-07 02:06:42 +00001431 // C++11 [temp.param]p11:
David Blaikie1368e582011-10-19 05:19:50 +00001432 // If a template parameter of a primary class template or alias template
1433 // is a template parameter pack, it shall be the last template parameter.
Richard Smith6964b3f2012-09-07 02:06:42 +00001434 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
David Blaikie1368e582011-10-19 05:19:50 +00001435 (TPC == TPC_ClassTemplate || TPC == TPC_TypeAliasTemplate)) {
1436 Diag((*NewParam)->getLocation(),
1437 diag::err_template_param_pack_must_be_last_template_parameter);
1438 Invalid = true;
1439 }
1440
Douglas Gregord684b002009-02-10 19:49:53 +00001441 if (RedundantDefaultArg) {
1442 // C++ [temp.param]p12:
1443 // A template-parameter shall not be given default arguments
1444 // by two different declarations in the same scope.
1445 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1446 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1447 Invalid = true;
Douglas Gregoree5d21f2011-02-04 03:57:22 +00001448 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregord684b002009-02-10 19:49:53 +00001449 // C++ [temp.param]p11:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001450 // If a template-parameter of a class template has a default
1451 // template-argument, each subsequent template-parameter shall either
Douglas Gregorb49e4152011-01-05 16:21:17 +00001452 // have a default template-argument supplied or be a template parameter
1453 // pack.
Mike Stump1eb44332009-09-09 15:08:12 +00001454 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001455 diag::err_template_param_default_arg_missing);
1456 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1457 Invalid = true;
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001458 RemoveDefaultArguments = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001459 }
1460
1461 // If we have an old template parameter list that we're merging
1462 // in, move on to the next parameter.
1463 if (OldParams)
1464 ++OldParam;
1465 }
1466
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001467 // We were missing some default arguments at the end of the list, so remove
1468 // all of the default arguments.
1469 if (RemoveDefaultArguments) {
1470 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1471 NewParamEnd = NewParams->end();
1472 NewParam != NewParamEnd; ++NewParam) {
1473 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1474 TTP->removeDefaultArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001475 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001476 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1477 NTTP->removeDefaultArgument();
1478 else
1479 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1480 }
1481 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001482
Douglas Gregord684b002009-02-10 19:49:53 +00001483 return Invalid;
1484}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001485
John McCall4e2cbb22010-10-20 05:44:58 +00001486namespace {
1487
1488/// A class which looks for a use of a certain level of template
1489/// parameter.
1490struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1491 typedef RecursiveASTVisitor<DependencyChecker> super;
1492
1493 unsigned Depth;
1494 bool Match;
1495
1496 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1497 NamedDecl *ND = Params->getParam(0);
1498 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1499 Depth = PD->getDepth();
1500 } else if (NonTypeTemplateParmDecl *PD =
1501 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1502 Depth = PD->getDepth();
1503 } else {
1504 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1505 }
1506 }
1507
1508 bool Matches(unsigned ParmDepth) {
1509 if (ParmDepth >= Depth) {
1510 Match = true;
1511 return true;
1512 }
1513 return false;
1514 }
1515
1516 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1517 return !Matches(T->getDepth());
1518 }
1519
1520 bool TraverseTemplateName(TemplateName N) {
1521 if (TemplateTemplateParmDecl *PD =
1522 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1523 if (Matches(PD->getDepth())) return false;
1524 return super::TraverseTemplateName(N);
1525 }
1526
1527 bool VisitDeclRefExpr(DeclRefExpr *E) {
1528 if (NonTypeTemplateParmDecl *PD =
1529 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1530 if (PD->getDepth() == Depth) {
1531 Match = true;
1532 return false;
1533 }
1534 }
1535 return super::VisitDeclRefExpr(E);
1536 }
Douglas Gregor18c83392011-05-13 00:34:01 +00001537
1538 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1539 return TraverseType(T->getInjectedSpecializationType());
1540 }
John McCall4e2cbb22010-10-20 05:44:58 +00001541};
1542}
1543
Douglas Gregorc8406492011-05-10 18:27:06 +00001544/// Determines whether a given type depends on the given parameter
John McCall4e2cbb22010-10-20 05:44:58 +00001545/// list.
1546static bool
Douglas Gregorc8406492011-05-10 18:27:06 +00001547DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCall4e2cbb22010-10-20 05:44:58 +00001548 DependencyChecker Checker(Params);
Douglas Gregorc8406492011-05-10 18:27:06 +00001549 Checker.TraverseType(T);
John McCall4e2cbb22010-10-20 05:44:58 +00001550 return Checker.Match;
1551}
1552
Douglas Gregorc8406492011-05-10 18:27:06 +00001553// Find the source range corresponding to the named type in the given
1554// nested-name-specifier, if any.
1555static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1556 QualType T,
1557 const CXXScopeSpec &SS) {
1558 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1559 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1560 if (const Type *CurType = NNS->getAsType()) {
1561 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1562 return NNSLoc.getTypeLoc().getSourceRange();
1563 } else
1564 break;
1565
1566 NNSLoc = NNSLoc.getPrefix();
1567 }
1568
1569 return SourceRange();
1570}
1571
Mike Stump1eb44332009-09-09 15:08:12 +00001572/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001573/// specifier, returning the template parameter list that applies to the
1574/// name.
1575///
1576/// \param DeclStartLoc the start of the declaration that has a scope
1577/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001578///
Douglas Gregorc8406492011-05-10 18:27:06 +00001579/// \param DeclLoc The location of the declaration itself.
1580///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001581/// \param SS the scope specifier that will be matched to the given template
1582/// parameter lists. This scope specifier precedes a qualified name that is
1583/// being declared.
1584///
1585/// \param ParamLists the template parameter lists, from the outermost to the
1586/// innermost template parameter lists.
1587///
1588/// \param NumParamLists the number of template parameter lists in ParamLists.
1589///
John McCall77e8b112010-04-13 20:37:33 +00001590/// \param IsFriend Whether to apply the slightly different rules for
1591/// matching template parameters to scope specifiers in friend
1592/// declarations.
1593///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001594/// \param IsExplicitSpecialization will be set true if the entity being
1595/// declared is an explicit specialization, false otherwise.
1596///
Mike Stump1eb44332009-09-09 15:08:12 +00001597/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001598/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001599/// parameter list may have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001600/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001601/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001602/// itself a template).
1603TemplateParameterList *
1604Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
Douglas Gregorc8406492011-05-10 18:27:06 +00001605 SourceLocation DeclLoc,
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001606 const CXXScopeSpec &SS,
1607 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001608 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001609 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001610 bool &IsExplicitSpecialization,
1611 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001612 IsExplicitSpecialization = false;
Douglas Gregorc8406492011-05-10 18:27:06 +00001613 Invalid = false;
1614
1615 // The sequence of nested types to which we will match up the template
1616 // parameter lists. We first build this list by starting with the type named
1617 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001618 SmallVector<QualType, 4> NestedTypes;
Douglas Gregorc8406492011-05-10 18:27:06 +00001619 QualType T;
Douglas Gregor714c9922011-05-15 17:27:27 +00001620 if (SS.getScopeRep()) {
1621 if (CXXRecordDecl *Record
1622 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1623 T = Context.getTypeDeclType(Record);
1624 else
1625 T = QualType(SS.getScopeRep()->getAsType(), 0);
1626 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001627
1628 // If we found an explicit specialization that prevents us from needing
1629 // 'template<>' headers, this will be set to the location of that
1630 // explicit specialization.
1631 SourceLocation ExplicitSpecLoc;
1632
1633 while (!T.isNull()) {
1634 NestedTypes.push_back(T);
1635
1636 // Retrieve the parent of a record type.
1637 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1638 // If this type is an explicit specialization, we're done.
1639 if (ClassTemplateSpecializationDecl *Spec
1640 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1641 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1642 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1643 ExplicitSpecLoc = Spec->getLocation();
1644 break;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001645 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001646 } else if (Record->getTemplateSpecializationKind()
1647 == TSK_ExplicitSpecialization) {
1648 ExplicitSpecLoc = Record->getLocation();
John McCall77e8b112010-04-13 20:37:33 +00001649 break;
1650 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001651
1652 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1653 T = Context.getTypeDeclType(Parent);
1654 else
1655 T = QualType();
1656 continue;
1657 }
1658
1659 if (const TemplateSpecializationType *TST
1660 = T->getAs<TemplateSpecializationType>()) {
1661 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1662 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1663 T = Context.getTypeDeclType(Parent);
1664 else
1665 T = QualType();
1666 continue;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001667 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001668 }
1669
1670 // Look one step prior in a dependent template specialization type.
1671 if (const DependentTemplateSpecializationType *DependentTST
1672 = T->getAs<DependentTemplateSpecializationType>()) {
1673 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1674 T = QualType(NNS->getAsType(), 0);
1675 else
1676 T = QualType();
1677 continue;
1678 }
1679
1680 // Look one step prior in a dependent name type.
1681 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1682 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1683 T = QualType(NNS->getAsType(), 0);
1684 else
1685 T = QualType();
1686 continue;
1687 }
1688
1689 // Retrieve the parent of an enumeration type.
1690 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1691 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1692 // check here.
1693 EnumDecl *Enum = EnumT->getDecl();
1694
1695 // Get to the parent type.
1696 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1697 T = Context.getTypeDeclType(Parent);
1698 else
1699 T = QualType();
1700 continue;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001701 }
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Douglas Gregorc8406492011-05-10 18:27:06 +00001703 T = QualType();
1704 }
1705 // Reverse the nested types list, since we want to traverse from the outermost
1706 // to the innermost while checking template-parameter-lists.
1707 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregorb88e8882009-07-30 17:40:51 +00001708
Douglas Gregorc8406492011-05-10 18:27:06 +00001709 // C++0x [temp.expl.spec]p17:
1710 // A member or a member template may be nested within many
1711 // enclosing class templates. In an explicit specialization for
1712 // such a member, the member declaration shall be preceded by a
1713 // template<> for each enclosing class template that is
1714 // explicitly specialized.
Douglas Gregor89b9f102011-06-06 15:22:55 +00001715 bool SawNonEmptyTemplateParameterList = false;
Douglas Gregorc8406492011-05-10 18:27:06 +00001716 unsigned ParamIdx = 0;
1717 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1718 ++TypeIdx) {
1719 T = NestedTypes[TypeIdx];
1720
1721 // Whether we expect a 'template<>' header.
1722 bool NeedEmptyTemplateHeader = false;
1723
1724 // Whether we expect a template header with parameters.
1725 bool NeedNonemptyTemplateHeader = false;
1726
1727 // For a dependent type, the set of template parameters that we
1728 // expect to see.
1729 TemplateParameterList *ExpectedTemplateParams = 0;
1730
Douglas Gregor175c5bb2011-05-11 23:26:17 +00001731 // C++0x [temp.expl.spec]p15:
1732 // A member or a member template may be nested within many enclosing
1733 // class templates. In an explicit specialization for such a member, the
1734 // member declaration shall be preceded by a template<> for each
1735 // enclosing class template that is explicitly specialized.
Douglas Gregorc8406492011-05-10 18:27:06 +00001736 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1737 if (ClassTemplatePartialSpecializationDecl *Partial
1738 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1739 ExpectedTemplateParams = Partial->getTemplateParameters();
1740 NeedNonemptyTemplateHeader = true;
1741 } else if (Record->isDependentType()) {
1742 if (Record->getDescribedClassTemplate()) {
John McCall31f17ec2010-04-27 00:57:59 +00001743 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregorc8406492011-05-10 18:27:06 +00001744 ->getTemplateParameters();
1745 NeedNonemptyTemplateHeader = true;
1746 }
1747 } else if (ClassTemplateSpecializationDecl *Spec
1748 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1749 // C++0x [temp.expl.spec]p4:
1750 // Members of an explicitly specialized class template are defined
1751 // in the same manner as members of normal classes, and not using
1752 // the template<> syntax.
1753 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1754 NeedEmptyTemplateHeader = true;
1755 else
Douglas Gregor95ea4502011-06-01 22:37:07 +00001756 continue;
Douglas Gregorc8406492011-05-10 18:27:06 +00001757 } else if (Record->getTemplateSpecializationKind()) {
1758 if (Record->getTemplateSpecializationKind()
Douglas Gregor175c5bb2011-05-11 23:26:17 +00001759 != TSK_ExplicitSpecialization &&
1760 TypeIdx == NumTypes - 1)
1761 IsExplicitSpecialization = true;
1762
1763 continue;
Douglas Gregorc8406492011-05-10 18:27:06 +00001764 }
1765 } else if (const TemplateSpecializationType *TST
1766 = T->getAs<TemplateSpecializationType>()) {
1767 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1768 ExpectedTemplateParams = Template->getTemplateParameters();
1769 NeedNonemptyTemplateHeader = true;
1770 }
1771 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1772 // FIXME: We actually could/should check the template arguments here
1773 // against the corresponding template parameter list.
1774 NeedNonemptyTemplateHeader = false;
1775 }
1776
Douglas Gregor89b9f102011-06-06 15:22:55 +00001777 // C++ [temp.expl.spec]p16:
1778 // In an explicit specialization declaration for a member of a class
1779 // template or a member template that ap- pears in namespace scope, the
1780 // member template and some of its enclosing class templates may remain
1781 // unspecialized, except that the declaration shall not explicitly
1782 // specialize a class member template if its en- closing class templates
1783 // are not explicitly specialized as well.
1784 if (ParamIdx < NumParamLists) {
1785 if (ParamLists[ParamIdx]->size() == 0) {
1786 if (SawNonEmptyTemplateParameterList) {
1787 Diag(DeclLoc, diag::err_specialize_member_of_template)
1788 << ParamLists[ParamIdx]->getSourceRange();
1789 Invalid = true;
1790 IsExplicitSpecialization = false;
1791 return 0;
1792 }
1793 } else
1794 SawNonEmptyTemplateParameterList = true;
1795 }
1796
Douglas Gregorc8406492011-05-10 18:27:06 +00001797 if (NeedEmptyTemplateHeader) {
1798 // If we're on the last of the types, and we need a 'template<>' header
1799 // here, then it's an explicit specialization.
1800 if (TypeIdx == NumTypes - 1)
1801 IsExplicitSpecialization = true;
1802
1803 if (ParamIdx < NumParamLists) {
1804 if (ParamLists[ParamIdx]->size() > 0) {
1805 // The header has template parameters when it shouldn't. Complain.
1806 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1807 diag::err_template_param_list_matches_nontemplate)
1808 << T
1809 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1810 ParamLists[ParamIdx]->getRAngleLoc())
1811 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1812 Invalid = true;
1813 return 0;
1814 }
1815
1816 // Consume this template header.
1817 ++ParamIdx;
1818 continue;
1819 }
1820
1821 if (!IsFriend) {
1822 // We don't have a template header, but we should.
1823 SourceLocation ExpectedTemplateLoc;
1824 if (NumParamLists > 0)
1825 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1826 else
1827 ExpectedTemplateLoc = DeclStartLoc;
1828
1829 Diag(DeclLoc, diag::err_template_spec_needs_header)
1830 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS)
1831 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1832 }
1833
1834 continue;
1835 }
1836
1837 if (NeedNonemptyTemplateHeader) {
1838 // In friend declarations we can have template-ids which don't
1839 // depend on the corresponding template parameter lists. But
1840 // assume that empty parameter lists are supposed to match this
1841 // template-id.
1842 if (IsFriend && T->isDependentType()) {
1843 if (ParamIdx < NumParamLists &&
1844 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1845 ExpectedTemplateParams = 0;
1846 else
1847 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001848 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001849
Douglas Gregorc8406492011-05-10 18:27:06 +00001850 if (ParamIdx < NumParamLists) {
1851 // Check the template parameter list, if we can.
1852 if (ExpectedTemplateParams &&
1853 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1854 ExpectedTemplateParams,
1855 true, TPL_TemplateMatch))
1856 Invalid = true;
1857
1858 if (!Invalid &&
1859 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1860 TPC_ClassTemplateMember))
1861 Invalid = true;
1862
1863 ++ParamIdx;
1864 continue;
1865 }
1866
1867 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1868 << T
1869 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1870 Invalid = true;
1871 continue;
1872 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001873 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001874
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001875 // If there were at least as many template-ids as there were template
1876 // parameter lists, then there are no template parameter lists remaining for
1877 // the declaration itself.
John McCall4e2cbb22010-10-20 05:44:58 +00001878 if (ParamIdx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001879 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001881 // If there were too many template parameter lists, complain about that now.
Douglas Gregorc8406492011-05-10 18:27:06 +00001882 if (ParamIdx < NumParamLists - 1) {
1883 bool HasAnyExplicitSpecHeader = false;
1884 bool AllExplicitSpecHeaders = true;
1885 for (unsigned I = ParamIdx; I != NumParamLists - 1; ++I) {
1886 if (ParamLists[I]->size() == 0)
1887 HasAnyExplicitSpecHeader = true;
1888 else
1889 AllExplicitSpecHeaders = false;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001890 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001891
1892 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1893 AllExplicitSpecHeaders? diag::warn_template_spec_extra_headers
1894 : diag::err_template_spec_extra_headers)
1895 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1896 ParamLists[NumParamLists - 2]->getRAngleLoc());
1897
1898 // If there was a specialization somewhere, such that 'template<>' is
1899 // not required, and there were any 'template<>' headers, note where the
1900 // specialization occurred.
1901 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1902 Diag(ExplicitSpecLoc,
1903 diag::note_explicit_template_spec_does_not_need_header)
1904 << NestedTypes.back();
1905
1906 // We have a template parameter list with no corresponding scope, which
1907 // means that the resulting template declaration can't be instantiated
1908 // properly (we'll end up with dependent nodes when we shouldn't).
1909 if (!AllExplicitSpecHeaders)
1910 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001911 }
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Douglas Gregor89b9f102011-06-06 15:22:55 +00001913 // C++ [temp.expl.spec]p16:
1914 // In an explicit specialization declaration for a member of a class
1915 // template or a member template that ap- pears in namespace scope, the
1916 // member template and some of its enclosing class templates may remain
1917 // unspecialized, except that the declaration shall not explicitly
1918 // specialize a class member template if its en- closing class templates
1919 // are not explicitly specialized as well.
1920 if (ParamLists[NumParamLists - 1]->size() == 0 &&
1921 SawNonEmptyTemplateParameterList) {
1922 Diag(DeclLoc, diag::err_specialize_member_of_template)
1923 << ParamLists[ParamIdx]->getSourceRange();
1924 Invalid = true;
1925 IsExplicitSpecialization = false;
1926 return 0;
1927 }
1928
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001929 // Return the last template parameter list, which corresponds to the
1930 // entity being declared.
1931 return ParamLists[NumParamLists - 1];
1932}
1933
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001934void Sema::NoteAllFoundTemplates(TemplateName Name) {
1935 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1936 Diag(Template->getLocation(), diag::note_template_declared_here)
1937 << (isa<FunctionTemplateDecl>(Template)? 0
1938 : isa<ClassTemplateDecl>(Template)? 1
Richard Smith3e4c6c42011-05-05 21:57:07 +00001939 : isa<TypeAliasTemplateDecl>(Template)? 2
1940 : 3)
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001941 << Template->getDeclName();
1942 return;
1943 }
1944
1945 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1946 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1947 IEnd = OST->end();
1948 I != IEnd; ++I)
1949 Diag((*I)->getLocation(), diag::note_template_declared_here)
1950 << 0 << (*I)->getDeclName();
1951
1952 return;
1953 }
1954}
1955
Douglas Gregor7532dc62009-03-30 22:58:21 +00001956QualType Sema::CheckTemplateIdType(TemplateName Name,
1957 SourceLocation TemplateLoc,
Douglas Gregor67714232011-03-03 02:41:12 +00001958 TemplateArgumentListInfo &TemplateArgs) {
John McCall14606042011-06-30 08:33:18 +00001959 DependentTemplateName *DTN
1960 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001961 if (DTN && DTN->isIdentifier())
1962 // When building a template-id where the template-name is dependent,
1963 // assume the template is a type template. Either our assumption is
1964 // correct, or the code is ill-formed and will be diagnosed when the
1965 // dependent name is substituted.
1966 return Context.getDependentTemplateSpecializationType(ETK_None,
1967 DTN->getQualifier(),
1968 DTN->getIdentifier(),
1969 TemplateArgs);
1970
Douglas Gregor7532dc62009-03-30 22:58:21 +00001971 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001972 if (!Template || isa<FunctionTemplateDecl>(Template)) {
1973 // We might have a substituted template template parameter pack. If so,
1974 // build a template specialization type for it.
1975 if (Name.getAsSubstTemplateTemplateParmPack())
1976 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3e4c6c42011-05-05 21:57:07 +00001977
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001978 Diag(TemplateLoc, diag::err_template_id_not_a_type)
1979 << Name;
1980 NoteAllFoundTemplates(Name);
1981 return QualType();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001982 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001983
Douglas Gregor40808ce2009-03-09 23:48:35 +00001984 // Check that the template argument list is well-formed for this
1985 // template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001986 SmallVector<TemplateArgument, 4> Converted;
Douglas Gregorb70126a2012-02-03 17:16:23 +00001987 bool ExpansionIntoFixedList = false;
John McCalld5532b62009-11-23 01:53:49 +00001988 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregorb70126a2012-02-03 17:16:23 +00001989 false, Converted, &ExpansionIntoFixedList))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001990 return QualType();
1991
Douglas Gregor40808ce2009-03-09 23:48:35 +00001992 QualType CanonType;
1993
Douglas Gregor561f8122011-07-01 01:22:09 +00001994 bool InstantiationDependent = false;
Douglas Gregorb70126a2012-02-03 17:16:23 +00001995 TypeAliasTemplateDecl *AliasTemplate = 0;
1996 if (!ExpansionIntoFixedList &&
1997 (AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Template))) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00001998 // Find the canonical type for this type alias template specialization.
1999 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2000 if (Pattern->isInvalidDecl())
2001 return QualType();
2002
2003 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2004 Converted.data(), Converted.size());
2005
2006 // Only substitute for the innermost template argument list.
2007 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith18041742011-05-14 15:04:18 +00002008 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smithaff37b42011-05-12 00:06:17 +00002009 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2010 for (unsigned I = 0; I < Depth; ++I)
2011 TemplateArgLists.addOuterTemplateArguments(0, 0);
Richard Smith3e4c6c42011-05-05 21:57:07 +00002012
Richard Smitha8eaf002012-08-23 06:16:52 +00002013 LocalInstantiationScope Scope(*this);
Richard Smith3e4c6c42011-05-05 21:57:07 +00002014 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Richard Smithab91ef12012-07-08 02:38:24 +00002015 if (Inst)
2016 return QualType();
Richard Smitha8eaf002012-08-23 06:16:52 +00002017
Richard Smith3e4c6c42011-05-05 21:57:07 +00002018 CanonType = SubstType(Pattern->getUnderlyingType(),
2019 TemplateArgLists, AliasTemplate->getLocation(),
2020 AliasTemplate->getDeclName());
2021 if (CanonType.isNull())
2022 return QualType();
2023 } else if (Name.isDependent() ||
2024 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor561f8122011-07-01 01:22:09 +00002025 TemplateArgs, InstantiationDependent)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002026 // This class template specialization is a dependent
2027 // type. Therefore, its canonical type is another class template
2028 // specialization type that contains all of the converted
2029 // arguments in canonical form. This ensures that, e.g., A<T> and
2030 // A<T, T> have identical types when A is declared as:
2031 //
2032 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002033 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00002034 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor910f8002010-11-07 23:05:16 +00002035 Converted.data(),
2036 Converted.size());
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Douglas Gregor1275ae02009-07-28 23:00:59 +00002038 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00002039 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00002040 // In the future, we need to teach getTemplateSpecializationType to only
2041 // build the canonical type and return that to us.
2042 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00002043
2044 // This might work out to be a current instantiation, in which
2045 // case the canonical type needs to be the InjectedClassNameType.
2046 //
2047 // TODO: in theory this could be a simple hashtable lookup; most
2048 // changes to CurContext don't change the set of current
2049 // instantiations.
2050 if (isa<ClassTemplateDecl>(Template)) {
2051 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2052 // If we get out to a namespace, we're done.
2053 if (Ctx->isFileContext()) break;
2054
2055 // If this isn't a record, keep looking.
2056 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2057 if (!Record) continue;
2058
2059 // Look for one of the two cases with InjectedClassNameTypes
2060 // and check whether it's the same template.
2061 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2062 !Record->getDescribedClassTemplate())
2063 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002064
John McCall31f17ec2010-04-27 00:57:59 +00002065 // Fetch the injected class name type and check whether its
2066 // injected type is equal to the type we just built.
2067 QualType ICNT = Context.getTypeDeclType(Record);
2068 QualType Injected = cast<InjectedClassNameType>(ICNT)
2069 ->getInjectedSpecializationType();
2070
2071 if (CanonType != Injected->getCanonicalTypeInternal())
2072 continue;
2073
2074 // If so, the canonical type of this TST is the injected
2075 // class name type of the record we just found.
2076 assert(ICNT.isCanonical());
2077 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00002078 break;
2079 }
2080 }
Mike Stump1eb44332009-09-09 15:08:12 +00002081 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002082 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002083 // Find the class template specialization declaration that
2084 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00002085 void *InsertPos = 0;
2086 ClassTemplateSpecializationDecl *Decl
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002087 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002088 InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002089 if (!Decl) {
2090 // This is the first time we have referenced this class template
2091 // specialization. Create the canonical declaration and add it to
2092 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002093 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002094 ClassTemplate->getTemplatedDecl()->getTagKind(),
2095 ClassTemplate->getDeclContext(),
Abramo Bagnara09d82122011-10-03 20:34:03 +00002096 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002097 ClassTemplate->getLocation(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002098 ClassTemplate,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002099 Converted.data(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002100 Converted.size(), 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002101 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara4f216d382012-09-05 09:05:18 +00002102 if (ClassTemplate->isOutOfLine())
2103 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregor40808ce2009-03-09 23:48:35 +00002104 }
2105
2106 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00002107 assert(isa<RecordType>(CanonType) &&
2108 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00002109 }
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Douglas Gregor40808ce2009-03-09 23:48:35 +00002111 // Build the fully-sugared type for this class template
2112 // specialization, which refers back to the class template
2113 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00002114 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002115}
2116
John McCallf312b1e2010-08-26 23:41:50 +00002117TypeResult
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002118Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00002119 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002120 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002121 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002122 SourceLocation RAngleLoc,
2123 bool IsCtorOrDtorName) {
Douglas Gregor059101f2011-03-02 00:47:37 +00002124 if (SS.isInvalid())
2125 return true;
2126
Douglas Gregor7532dc62009-03-30 22:58:21 +00002127 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00002128
Douglas Gregor40808ce2009-03-09 23:48:35 +00002129 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00002130 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00002131 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002132
Douglas Gregora88f09f2011-02-28 17:23:35 +00002133 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002134 QualType T
2135 = Context.getDependentTemplateSpecializationType(ETK_None,
2136 DTN->getQualifier(),
2137 DTN->getIdentifier(),
2138 TemplateArgs);
2139 // Build type-source information.
Douglas Gregora88f09f2011-02-28 17:23:35 +00002140 TypeLocBuilder TLB;
2141 DependentTemplateSpecializationTypeLoc SpecTL
2142 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002143 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2144 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara66581d42012-02-06 22:45:07 +00002145 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002146 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregora88f09f2011-02-28 17:23:35 +00002147 SpecTL.setLAngleLoc(LAngleLoc);
2148 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregora88f09f2011-02-28 17:23:35 +00002149 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2150 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2151 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2152 }
2153
John McCalld5532b62009-11-23 01:53:49 +00002154 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor31a19b62009-04-01 21:51:26 +00002155
2156 if (Result.isNull())
2157 return true;
2158
Douglas Gregor059101f2011-03-02 00:47:37 +00002159 // Build type-source information.
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002160 TypeLocBuilder TLB;
Douglas Gregor059101f2011-03-02 00:47:37 +00002161 TemplateSpecializationTypeLoc SpecTL
2162 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002163 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregor059101f2011-03-02 00:47:37 +00002164 SpecTL.setTemplateNameLoc(TemplateLoc);
2165 SpecTL.setLAngleLoc(LAngleLoc);
2166 SpecTL.setRAngleLoc(RAngleLoc);
2167 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2168 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall833ca992009-10-29 08:12:44 +00002169
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002170 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2171 // constructor or destructor name (in such a case, the scope specifier
2172 // will be attached to the enclosing Decl or Expr node).
2173 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor059101f2011-03-02 00:47:37 +00002174 // Create an elaborated-type-specifier containing the nested-name-specifier.
2175 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2176 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara38a42912012-02-06 19:09:27 +00002177 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor059101f2011-03-02 00:47:37 +00002178 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2179 }
2180
2181 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall6b2becf2009-09-08 17:47:29 +00002182}
John McCallf1bbbb42009-09-04 01:14:41 +00002183
Douglas Gregor059101f2011-03-02 00:47:37 +00002184TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallf312b1e2010-08-26 23:41:50 +00002185 TypeSpecifierType TagSpec,
Douglas Gregor059101f2011-03-02 00:47:37 +00002186 SourceLocation TagLoc,
2187 CXXScopeSpec &SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002188 SourceLocation TemplateKWLoc,
2189 TemplateTy TemplateD,
Douglas Gregor059101f2011-03-02 00:47:37 +00002190 SourceLocation TemplateLoc,
2191 SourceLocation LAngleLoc,
2192 ASTTemplateArgsPtr TemplateArgsIn,
2193 SourceLocation RAngleLoc) {
2194 TemplateName Template = TemplateD.getAsVal<TemplateName>();
2195
2196 // Translate the parser's template argument list in our AST format.
2197 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2198 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2199
2200 // Determine the tag kind
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002201 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregor059101f2011-03-02 00:47:37 +00002202 ElaboratedTypeKeyword Keyword
2203 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002204
Douglas Gregor059101f2011-03-02 00:47:37 +00002205 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2206 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2207 DTN->getQualifier(),
2208 DTN->getIdentifier(),
2209 TemplateArgs);
2210
2211 // Build type-source information.
2212 TypeLocBuilder TLB;
2213 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002214 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2215 SpecTL.setElaboratedKeywordLoc(TagLoc);
2216 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara66581d42012-02-06 22:45:07 +00002217 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002218 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor059101f2011-03-02 00:47:37 +00002219 SpecTL.setLAngleLoc(LAngleLoc);
2220 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor059101f2011-03-02 00:47:37 +00002221 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2222 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2223 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2224 }
Richard Smith3e4c6c42011-05-05 21:57:07 +00002225
2226 if (TypeAliasTemplateDecl *TAT =
2227 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2228 // C++0x [dcl.type.elab]p2:
2229 // If the identifier resolves to a typedef-name or the simple-template-id
2230 // resolves to an alias template specialization, the
2231 // elaborated-type-specifier is ill-formed.
2232 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2233 Diag(TAT->getLocation(), diag::note_declared_at);
2234 }
Douglas Gregor059101f2011-03-02 00:47:37 +00002235
2236 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2237 if (Result.isNull())
Matt Beaumont-Gay3a51d412011-08-25 23:22:24 +00002238 return TypeResult(true);
Douglas Gregor059101f2011-03-02 00:47:37 +00002239
2240 // Check the tag kind
2241 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00002242 RecordDecl *D = RT->getDecl();
Douglas Gregor059101f2011-03-02 00:47:37 +00002243
John McCall6b2becf2009-09-08 17:47:29 +00002244 IdentifierInfo *Id = D->getIdentifier();
2245 assert(Id && "templated class must have an identifier");
Douglas Gregor059101f2011-03-02 00:47:37 +00002246
Richard Trieubbf34c02011-06-10 03:11:26 +00002247 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2248 TagLoc, *Id)) {
John McCall6b2becf2009-09-08 17:47:29 +00002249 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregor059101f2011-03-02 00:47:37 +00002250 << Result
Douglas Gregor849b2432010-03-31 17:46:05 +00002251 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00002252 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00002253 }
2254 }
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002255
Douglas Gregor059101f2011-03-02 00:47:37 +00002256 // Provide source-location information for the template specialization.
2257 TypeLocBuilder TLB;
2258 TemplateSpecializationTypeLoc SpecTL
2259 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002260 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregor059101f2011-03-02 00:47:37 +00002261 SpecTL.setTemplateNameLoc(TemplateLoc);
2262 SpecTL.setLAngleLoc(LAngleLoc);
2263 SpecTL.setRAngleLoc(RAngleLoc);
2264 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2265 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCallf1bbbb42009-09-04 01:14:41 +00002266
Douglas Gregor059101f2011-03-02 00:47:37 +00002267 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002268 // and tag keyword.
Douglas Gregor059101f2011-03-02 00:47:37 +00002269 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2270 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara38a42912012-02-06 19:09:27 +00002271 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor059101f2011-03-02 00:47:37 +00002272 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2273 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor55f6b142009-02-09 18:46:07 +00002274}
2275
John McCall60d7b3a2010-08-24 06:29:42 +00002276ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002277 SourceLocation TemplateKWLoc,
Douglas Gregor4c9be892011-02-28 20:01:57 +00002278 LookupResult &R,
2279 bool RequiresADL,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00002280 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002281 // FIXME: Can we do any checking at this point? I guess we could check the
2282 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00002283 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002284 // though.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00002285 // foo<int> could identify a single function unambiguously
2286 // This approach does NOT work, since f<int>(1);
2287 // gets resolved prior to resorting to overload resolution
2288 // i.e., template<class T> void f(double);
2289 // vs template<class T, class U> void f(U);
John McCallf7a1a742009-11-24 19:00:30 +00002290
2291 // These should be filtered out by our callers.
2292 assert(!R.empty() && "empty lookup results when building templateid");
2293 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2294
John McCallc373d482010-01-27 01:50:18 +00002295 // We don't want lookup warnings at this point.
2296 R.suppressDiagnostics();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002297
John McCallf7a1a742009-11-24 19:00:30 +00002298 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002299 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002300 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002301 TemplateKWLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +00002302 R.getLookupNameInfo(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002303 RequiresADL, TemplateArgs,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002304 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00002305
2306 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002307}
2308
John McCallf7a1a742009-11-24 19:00:30 +00002309// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00002310ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002311Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002312 SourceLocation TemplateKWLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +00002313 const DeclarationNameInfo &NameInfo,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00002314 const TemplateArgumentListInfo *TemplateArgs) {
2315 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCallf7a1a742009-11-24 19:00:30 +00002316 DeclContext *DC;
2317 if (!(DC = computeDeclContext(SS, false)) ||
2318 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00002319 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00002320 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002321
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002322 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00002323 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002324 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
2325 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00002326
John McCallf7a1a742009-11-24 19:00:30 +00002327 if (R.isAmbiguous())
2328 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002329
John McCallf7a1a742009-11-24 19:00:30 +00002330 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002331 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2332 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002333 return ExprError();
2334 }
2335
2336 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002337 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2338 << (NestedNameSpecifier*) SS.getScopeRep()
2339 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002340 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2341 return ExprError();
2342 }
2343
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002344 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002345}
2346
Douglas Gregorc45c2322009-03-31 00:43:58 +00002347/// \brief Form a dependent template name.
2348///
2349/// This action forms a dependent template name given the template
2350/// name and its (presumably dependent) scope specifier. For
2351/// example, given "MetaFun::template apply", the scope specifier \p
2352/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2353/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002354TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002355 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002356 SourceLocation TemplateKWLoc,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002357 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00002358 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002359 bool EnteringContext,
2360 TemplateTy &Result) {
Richard Smithebaf0e62011-10-18 20:49:44 +00002361 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2362 Diag(TemplateKWLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00002363 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00002364 diag::warn_cxx98_compat_template_outside_of_template :
2365 diag::ext_template_outside_of_template)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002366 << FixItHint::CreateRemoval(TemplateKWLoc);
2367
Douglas Gregor0707bc52010-01-19 16:01:07 +00002368 DeclContext *LookupCtx = 0;
2369 if (SS.isSet())
2370 LookupCtx = computeDeclContext(SS, EnteringContext);
2371 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00002372 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00002373 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00002374 // C++0x [temp.names]p5:
2375 // If a name prefixed by the keyword template is not the name of
2376 // a template, the program is ill-formed. [Note: the keyword
2377 // template may not be applied to non-template members of class
2378 // templates. -end note ] [ Note: as is the case with the
2379 // typename prefix, the template prefix is allowed in cases
2380 // where it is not strictly necessary; i.e., when the
2381 // nested-name-specifier or the expression on the left of the ->
2382 // or . is not dependent on a template-parameter, or the use
2383 // does not appear in the scope of a template. -end note]
2384 //
2385 // Note: C++03 was more strict here, because it banned the use of
2386 // the "template" keyword prior to a template-name that was not a
2387 // dependent name. C++ DR468 relaxed this requirement (the
2388 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00002389 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002390 bool MemberOfUnknownSpecialization;
Richard Smithd6537012012-11-15 00:31:27 +00002391 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c153532010-08-06 12:11:11 +00002392 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002393 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00002394 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2395 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregord078bd22011-03-11 23:27:41 +00002396 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2397 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00002398 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00002399 } else if (TNK == TNK_Non_template) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002400 Diag(Name.getLocStart(),
Douglas Gregor014e88d2009-11-03 23:16:33 +00002401 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00002402 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00002403 << Name.getSourceRange()
2404 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00002405 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00002406 } else {
2407 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00002408 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00002409 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00002410 }
2411
Mike Stump1eb44332009-09-09 15:08:12 +00002412 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002413 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002414
Douglas Gregor014e88d2009-11-03 23:16:33 +00002415 switch (Name.getKind()) {
2416 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002417 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002418 Name.Identifier));
2419 return TNK_Dependent_template_name;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002420
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002421 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00002422 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002423 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00002424 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00002425
2426 case UnqualifiedId::IK_LiteralOperatorId:
David Blaikieb219cfc2011-09-23 05:06:16 +00002427 llvm_unreachable(
2428 "We don't support these; Parse shouldn't have allowed propagation");
Sean Hunte6252d12009-11-28 08:58:14 +00002429
Douglas Gregor014e88d2009-11-03 23:16:33 +00002430 default:
2431 break;
2432 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002433
Daniel Dunbar96a00142012-03-09 18:35:03 +00002434 Diag(Name.getLocStart(),
Douglas Gregor014e88d2009-11-03 23:16:33 +00002435 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00002436 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00002437 << Name.getSourceRange()
2438 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00002439 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00002440}
2441
Mike Stump1eb44332009-09-09 15:08:12 +00002442bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00002443 const TemplateArgumentLoc &AL,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002444 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall833ca992009-10-29 08:12:44 +00002445 const TemplateArgument &Arg = AL.getArgument();
2446
Anders Carlsson436b1562009-06-13 00:33:33 +00002447 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002448 switch(Arg.getKind()) {
2449 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00002450 // C++ [temp.arg.type]p1:
2451 // A template-argument for a template-parameter which is a
2452 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002453 break;
2454 case TemplateArgument::Template: {
2455 // We have a template type parameter but the template argument
2456 // is a template without any arguments.
2457 SourceRange SR = AL.getSourceRange();
2458 TemplateName Name = Arg.getAsTemplate();
2459 Diag(SR.getBegin(), diag::err_template_missing_args)
2460 << Name << SR;
2461 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
2462 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00002463
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002464 return true;
2465 }
Kaelyn Uhrainab7ad722012-05-18 23:42:49 +00002466 case TemplateArgument::Expression: {
2467 // We have a template type parameter but the template argument is an
2468 // expression; see if maybe it is missing the "typename" keyword.
2469 CXXScopeSpec SS;
2470 DeclarationNameInfo NameInfo;
2471
2472 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
2473 SS.Adopt(ArgExpr->getQualifierLoc());
2474 NameInfo = ArgExpr->getNameInfo();
2475 } else if (DependentScopeDeclRefExpr *ArgExpr =
2476 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
2477 SS.Adopt(ArgExpr->getQualifierLoc());
2478 NameInfo = ArgExpr->getNameInfo();
2479 } else if (CXXDependentScopeMemberExpr *ArgExpr =
2480 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain8c14de82012-06-08 01:07:26 +00002481 if (ArgExpr->isImplicitAccess()) {
2482 SS.Adopt(ArgExpr->getQualifierLoc());
2483 NameInfo = ArgExpr->getMemberNameInfo();
2484 }
Kaelyn Uhrainab7ad722012-05-18 23:42:49 +00002485 }
2486
Kaelyn Uhrain8c14de82012-06-08 01:07:26 +00002487 if (NameInfo.getName().isIdentifier()) {
Kaelyn Uhrainab7ad722012-05-18 23:42:49 +00002488 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
2489 LookupParsedName(Result, CurScope, &SS);
2490
Kaelyn Uhrain8c14de82012-06-08 01:07:26 +00002491 if (Result.getAsSingle<TypeDecl>() ||
2492 Result.getResultKind() ==
2493 LookupResult::NotFoundInCurrentInstantiation) {
2494 // FIXME: Add a FixIt and fix up the template argument for recovery.
Kaelyn Uhrainab7ad722012-05-18 23:42:49 +00002495 SourceLocation Loc = AL.getSourceRange().getBegin();
2496 Diag(Loc, diag::err_template_arg_must_be_type_suggest);
2497 Diag(Param->getLocation(), diag::note_template_param_here);
2498 return true;
2499 }
2500 }
2501 // fallthrough
2502 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002503 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00002504 // We have a template type parameter but the template argument
2505 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00002506 SourceRange SR = AL.getSourceRange();
2507 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00002508 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002509
Anders Carlsson436b1562009-06-13 00:33:33 +00002510 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002511 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002512 }
Anders Carlsson436b1562009-06-13 00:33:33 +00002513
John McCalla93c9342009-12-07 02:54:59 +00002514 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00002515 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002516
Anders Carlsson436b1562009-06-13 00:33:33 +00002517 // Add the converted template type argument.
Douglas Gregore559ca12011-06-17 22:11:49 +00002518 QualType ArgType = Context.getCanonicalType(Arg.getAsType());
2519
2520 // Objective-C ARC:
2521 // If an explicitly-specified template argument type is a lifetime type
2522 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikie4e4d0842012-03-11 07:00:24 +00002523 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore559ca12011-06-17 22:11:49 +00002524 ArgType->isObjCLifetimeType() &&
2525 !ArgType.getObjCLifetime()) {
2526 Qualifiers Qs;
2527 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
2528 ArgType = Context.getQualifiedType(ArgType, Qs);
2529 }
2530
2531 Converted.push_back(TemplateArgument(ArgType));
Anders Carlsson436b1562009-06-13 00:33:33 +00002532 return false;
2533}
2534
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002535/// \brief Substitute template arguments into the default template argument for
2536/// the given template type parameter.
2537///
2538/// \param SemaRef the semantic analysis object for which we are performing
2539/// the substitution.
2540///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002541/// \param Template the template that we are synthesizing template arguments
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002542/// for.
2543///
2544/// \param TemplateLoc the location of the template name that started the
2545/// template-id we are checking.
2546///
2547/// \param RAngleLoc the location of the right angle bracket ('>') that
2548/// terminates the template-id.
2549///
2550/// \param Param the template template parameter whose default we are
2551/// substituting into.
2552///
2553/// \param Converted the list of template arguments provided for template
2554/// parameters that precede \p Param in the template parameter list.
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002555/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00002556static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002557SubstDefaultTemplateArgument(Sema &SemaRef,
2558 TemplateDecl *Template,
2559 SourceLocation TemplateLoc,
2560 SourceLocation RAngleLoc,
2561 TemplateTypeParmDecl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002562 SmallVectorImpl<TemplateArgument> &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00002563 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002564
2565 // If the argument type is dependent, instantiate it now based
2566 // on the previously-computed template arguments.
2567 if (ArgType->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002568 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002569 Converted.data(), Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002570
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002571 MultiLevelTemplateArgumentList AllTemplateArgs
2572 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2573
2574 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith7e54fb52012-07-16 01:09:10 +00002575 Template, Converted,
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002576 SourceRange(TemplateLoc, RAngleLoc));
Richard Smithab91ef12012-07-08 02:38:24 +00002577 if (Inst)
2578 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002579
Argyrios Kyrtzidisad579912012-04-25 18:39:17 +00002580 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002581 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2582 Param->getDefaultArgumentLoc(),
2583 Param->getDeclName());
2584 }
2585
2586 return ArgType;
2587}
2588
2589/// \brief Substitute template arguments into the default template argument for
2590/// the given non-type template parameter.
2591///
2592/// \param SemaRef the semantic analysis object for which we are performing
2593/// the substitution.
2594///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002595/// \param Template the template that we are synthesizing template arguments
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002596/// for.
2597///
2598/// \param TemplateLoc the location of the template name that started the
2599/// template-id we are checking.
2600///
2601/// \param RAngleLoc the location of the right angle bracket ('>') that
2602/// terminates the template-id.
2603///
Douglas Gregor788cd062009-11-11 01:00:40 +00002604/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002605/// substituting into.
2606///
2607/// \param Converted the list of template arguments provided for template
2608/// parameters that precede \p Param in the template parameter list.
2609///
2610/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00002611static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002612SubstDefaultTemplateArgument(Sema &SemaRef,
2613 TemplateDecl *Template,
2614 SourceLocation TemplateLoc,
2615 SourceLocation RAngleLoc,
2616 NonTypeTemplateParmDecl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002617 SmallVectorImpl<TemplateArgument> &Converted) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002618 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002619 Converted.data(), Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002620
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002621 MultiLevelTemplateArgumentList AllTemplateArgs
2622 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002623
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002624 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith7e54fb52012-07-16 01:09:10 +00002625 Template, Converted,
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002626 SourceRange(TemplateLoc, RAngleLoc));
Richard Smithab91ef12012-07-08 02:38:24 +00002627 if (Inst)
2628 return ExprError();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002629
Argyrios Kyrtzidisad579912012-04-25 18:39:17 +00002630 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
Eli Friedman9b94cd12012-04-26 22:43:24 +00002631 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002632 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2633}
2634
Douglas Gregor788cd062009-11-11 01:00:40 +00002635/// \brief Substitute template arguments into the default template argument for
2636/// the given template template parameter.
2637///
2638/// \param SemaRef the semantic analysis object for which we are performing
2639/// the substitution.
2640///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002641/// \param Template the template that we are synthesizing template arguments
Douglas Gregor788cd062009-11-11 01:00:40 +00002642/// for.
2643///
2644/// \param TemplateLoc the location of the template name that started the
2645/// template-id we are checking.
2646///
2647/// \param RAngleLoc the location of the right angle bracket ('>') that
2648/// terminates the template-id.
2649///
2650/// \param Param the template template parameter whose default we are
2651/// substituting into.
2652///
2653/// \param Converted the list of template arguments provided for template
2654/// parameters that precede \p Param in the template parameter list.
2655///
Douglas Gregor1d752d72011-03-02 18:46:51 +00002656/// \param QualifierLoc Will be set to the nested-name-specifier (with
2657/// source-location information) that precedes the template name.
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002658///
Douglas Gregor788cd062009-11-11 01:00:40 +00002659/// \returns the substituted template argument, or NULL if an error occurred.
2660static TemplateName
2661SubstDefaultTemplateArgument(Sema &SemaRef,
2662 TemplateDecl *Template,
2663 SourceLocation TemplateLoc,
2664 SourceLocation RAngleLoc,
2665 TemplateTemplateParmDecl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002666 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002667 NestedNameSpecifierLoc &QualifierLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002668 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002669 Converted.data(), Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002670
Douglas Gregor788cd062009-11-11 01:00:40 +00002671 MultiLevelTemplateArgumentList AllTemplateArgs
2672 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002673
Douglas Gregor788cd062009-11-11 01:00:40 +00002674 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith7e54fb52012-07-16 01:09:10 +00002675 Template, Converted,
Douglas Gregor788cd062009-11-11 01:00:40 +00002676 SourceRange(TemplateLoc, RAngleLoc));
Richard Smithab91ef12012-07-08 02:38:24 +00002677 if (Inst)
2678 return TemplateName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002679
Argyrios Kyrtzidisad579912012-04-25 18:39:17 +00002680 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002681 // Substitute into the nested-name-specifier first,
Douglas Gregor1d752d72011-03-02 18:46:51 +00002682 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002683 if (QualifierLoc) {
2684 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2685 AllTemplateArgs);
2686 if (!QualifierLoc)
2687 return TemplateName();
2688 }
2689
Douglas Gregor1d752d72011-03-02 18:46:51 +00002690 return SemaRef.SubstTemplateName(QualifierLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +00002691 Param->getDefaultArgument().getArgument().getAsTemplate(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002692 Param->getDefaultArgument().getTemplateNameLoc(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002693 AllTemplateArgs);
2694}
2695
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002696/// \brief If the given template parameter has a default template
2697/// argument, substitute into that default template argument and
2698/// return the corresponding template argument.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002699TemplateArgumentLoc
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002700Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2701 SourceLocation TemplateLoc,
2702 SourceLocation RAngleLoc,
2703 Decl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002704 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002705 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002706 if (!TypeParm->hasDefaultArgument())
2707 return TemplateArgumentLoc();
2708
John McCalla93c9342009-12-07 02:54:59 +00002709 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002710 TemplateLoc,
2711 RAngleLoc,
2712 TypeParm,
2713 Converted);
2714 if (DI)
2715 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2716
2717 return TemplateArgumentLoc();
2718 }
2719
2720 if (NonTypeTemplateParmDecl *NonTypeParm
2721 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2722 if (!NonTypeParm->hasDefaultArgument())
2723 return TemplateArgumentLoc();
2724
John McCall60d7b3a2010-08-24 06:29:42 +00002725 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002726 TemplateLoc,
2727 RAngleLoc,
2728 NonTypeParm,
2729 Converted);
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002730 if (Arg.isInvalid())
2731 return TemplateArgumentLoc();
2732
2733 Expr *ArgE = Arg.takeAs<Expr>();
2734 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2735 }
2736
2737 TemplateTemplateParmDecl *TempTempParm
2738 = cast<TemplateTemplateParmDecl>(Param);
2739 if (!TempTempParm->hasDefaultArgument())
2740 return TemplateArgumentLoc();
2741
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002742
Douglas Gregor1d752d72011-03-02 18:46:51 +00002743 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002744 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002745 TemplateLoc,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002746 RAngleLoc,
2747 TempTempParm,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002748 Converted,
2749 QualifierLoc);
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002750 if (TName.isNull())
2751 return TemplateArgumentLoc();
2752
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002753 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002754 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002755 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2756}
2757
Douglas Gregore7526412009-11-11 19:31:23 +00002758/// \brief Check that the given template argument corresponds to the given
2759/// template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002760///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002761/// \param Param The template parameter against which the argument will be
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002762/// checked.
2763///
2764/// \param Arg The template argument.
2765///
2766/// \param Template The template in which the template argument resides.
2767///
2768/// \param TemplateLoc The location of the template name for the template
2769/// whose argument list we're matching.
2770///
2771/// \param RAngleLoc The location of the right angle bracket ('>') that closes
2772/// the template argument list.
2773///
2774/// \param ArgumentPackIndex The index into the argument pack where this
2775/// argument will be placed. Only valid if the parameter is a parameter pack.
2776///
2777/// \param Converted The checked, converted argument will be added to the
2778/// end of this small vector.
2779///
2780/// \param CTAK Describes how we arrived at this particular template argument:
2781/// explicitly written, deduced, etc.
2782///
2783/// \returns true on error, false otherwise.
Douglas Gregore7526412009-11-11 19:31:23 +00002784bool Sema::CheckTemplateArgument(NamedDecl *Param,
2785 const TemplateArgumentLoc &Arg,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002786 NamedDecl *Template,
Douglas Gregore7526412009-11-11 19:31:23 +00002787 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002788 SourceLocation RAngleLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002789 unsigned ArgumentPackIndex,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002790 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor02024a92010-03-28 02:42:43 +00002791 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002792 // Check template type parameters.
2793 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002794 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002795
Douglas Gregord9e15302009-11-11 19:41:09 +00002796 // Check non-type template parameters.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002797 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002798 // Do substitution on the type of the non-type template parameter
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002799 // with the template arguments we've seen thus far. But if the
2800 // template has a dependent context then we cannot substitute yet.
Douglas Gregore7526412009-11-11 19:31:23 +00002801 QualType NTTPType = NTTP->getType();
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002802 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
2803 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002804
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002805 if (NTTPType->isDependentType() &&
2806 !isa<TemplateTemplateParmDecl>(Template) &&
2807 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002808 // Do substitution on the type of the non-type template parameter.
2809 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith7e54fb52012-07-16 01:09:10 +00002810 NTTP, Converted,
Douglas Gregore7526412009-11-11 19:31:23 +00002811 SourceRange(TemplateLoc, RAngleLoc));
Richard Smithab91ef12012-07-08 02:38:24 +00002812 if (Inst)
2813 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002814
2815 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002816 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002817 NTTPType = SubstType(NTTPType,
2818 MultiLevelTemplateArgumentList(TemplateArgs),
2819 NTTP->getLocation(),
2820 NTTP->getDeclName());
2821 // If that worked, check the non-type template parameter type
2822 // for validity.
2823 if (!NTTPType.isNull())
2824 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2825 NTTP->getLocation());
2826 if (NTTPType.isNull())
2827 return true;
2828 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002829
Douglas Gregore7526412009-11-11 19:31:23 +00002830 switch (Arg.getArgument().getKind()) {
2831 case TemplateArgument::Null:
David Blaikieb219cfc2011-09-23 05:06:16 +00002832 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002833
Douglas Gregore7526412009-11-11 19:31:23 +00002834 case TemplateArgument::Expression: {
Douglas Gregore7526412009-11-11 19:31:23 +00002835 TemplateArgument Result;
John Wiegley429bb272011-04-08 18:41:53 +00002836 ExprResult Res =
2837 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
2838 Result, CTAK);
2839 if (Res.isInvalid())
Douglas Gregore7526412009-11-11 19:31:23 +00002840 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002841
Douglas Gregor910f8002010-11-07 23:05:16 +00002842 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002843 break;
2844 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002845
Douglas Gregore7526412009-11-11 19:31:23 +00002846 case TemplateArgument::Declaration:
2847 case TemplateArgument::Integral:
Eli Friedmand7a6b162012-09-26 02:36:12 +00002848 case TemplateArgument::NullPtr:
Douglas Gregore7526412009-11-11 19:31:23 +00002849 // We've already checked this template argument, so just copy
2850 // it to the list of converted arguments.
Douglas Gregor910f8002010-11-07 23:05:16 +00002851 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002852 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002853
Douglas Gregore7526412009-11-11 19:31:23 +00002854 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00002855 case TemplateArgument::TemplateExpansion:
Douglas Gregore7526412009-11-11 19:31:23 +00002856 // We were given a template template argument. It may not be ill-formed;
2857 // see below.
2858 if (DependentTemplateName *DTN
Douglas Gregora7fc9012011-01-05 18:58:31 +00002859 = Arg.getArgument().getAsTemplateOrTemplatePattern()
2860 .getAsDependentTemplateName()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002861 // We have a template argument such as \c T::template X, which we
2862 // parsed as a template template argument. However, since we now
2863 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002864 // template name into an expression.
2865
2866 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2867 Arg.getTemplateNameLoc());
2868
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00002869 CXXScopeSpec SS;
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002870 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002871 // FIXME: the template-template arg was a DependentTemplateName,
2872 // so it was provided with a template keyword. However, its source
2873 // location is not stored in the template argument structure.
2874 SourceLocation TemplateKWLoc;
John Wiegley429bb272011-04-08 18:41:53 +00002875 ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context,
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00002876 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002877 TemplateKWLoc,
2878 NameInfo, 0));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002879
Douglas Gregora7fc9012011-01-05 18:58:31 +00002880 // If we parsed the template argument as a pack expansion, create a
2881 // pack expansion expression.
2882 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
John Wiegley429bb272011-04-08 18:41:53 +00002883 E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc());
2884 if (E.isInvalid())
Douglas Gregora7fc9012011-01-05 18:58:31 +00002885 return true;
Douglas Gregora7fc9012011-01-05 18:58:31 +00002886 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002887
Douglas Gregore7526412009-11-11 19:31:23 +00002888 TemplateArgument Result;
John Wiegley429bb272011-04-08 18:41:53 +00002889 E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result);
2890 if (E.isInvalid())
Douglas Gregore7526412009-11-11 19:31:23 +00002891 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002892
Douglas Gregor910f8002010-11-07 23:05:16 +00002893 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002894 break;
2895 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002896
Douglas Gregore7526412009-11-11 19:31:23 +00002897 // We have a template argument that actually does refer to a class
Richard Smith3e4c6c42011-05-05 21:57:07 +00002898 // template, alias template, or template template parameter, and
Douglas Gregore7526412009-11-11 19:31:23 +00002899 // therefore cannot be a non-type template argument.
2900 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2901 << Arg.getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002902
Douglas Gregore7526412009-11-11 19:31:23 +00002903 Diag(Param->getLocation(), diag::note_template_param_here);
2904 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002905
Douglas Gregore7526412009-11-11 19:31:23 +00002906 case TemplateArgument::Type: {
2907 // We have a non-type template parameter but the template
2908 // argument is a type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002909
Douglas Gregore7526412009-11-11 19:31:23 +00002910 // C++ [temp.arg]p2:
2911 // In a template-argument, an ambiguity between a type-id and
2912 // an expression is resolved to a type-id, regardless of the
2913 // form of the corresponding template-parameter.
2914 //
2915 // We warn specifically about this case, since it can be rather
2916 // confusing for users.
2917 QualType T = Arg.getArgument().getAsType();
2918 SourceRange SR = Arg.getSourceRange();
2919 if (T->isFunctionType())
2920 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2921 else
2922 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2923 Diag(Param->getLocation(), diag::note_template_param_here);
2924 return true;
2925 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002926
Douglas Gregore7526412009-11-11 19:31:23 +00002927 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002928 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002929 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002930
Douglas Gregore7526412009-11-11 19:31:23 +00002931 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002932 }
2933
2934
Douglas Gregore7526412009-11-11 19:31:23 +00002935 // Check template template parameters.
2936 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002937
Douglas Gregore7526412009-11-11 19:31:23 +00002938 // Substitute into the template parameter list of the template
2939 // template parameter, since previously-supplied template arguments
2940 // may appear within the template template parameter.
2941 {
2942 // Set up a template instantiation context.
2943 LocalInstantiationScope Scope(*this);
2944 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith7e54fb52012-07-16 01:09:10 +00002945 TempParm, Converted,
Douglas Gregore7526412009-11-11 19:31:23 +00002946 SourceRange(TemplateLoc, RAngleLoc));
Richard Smithab91ef12012-07-08 02:38:24 +00002947 if (Inst)
2948 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002949
2950 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002951 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002952 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002953 SubstDecl(TempParm, CurContext,
Douglas Gregore7526412009-11-11 19:31:23 +00002954 MultiLevelTemplateArgumentList(TemplateArgs)));
2955 if (!TempParm)
2956 return true;
Douglas Gregore7526412009-11-11 19:31:23 +00002957 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002958
Douglas Gregore7526412009-11-11 19:31:23 +00002959 switch (Arg.getArgument().getKind()) {
2960 case TemplateArgument::Null:
David Blaikieb219cfc2011-09-23 05:06:16 +00002961 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002962
Douglas Gregore7526412009-11-11 19:31:23 +00002963 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00002964 case TemplateArgument::TemplateExpansion:
Richard Smith6964b3f2012-09-07 02:06:42 +00002965 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregore7526412009-11-11 19:31:23 +00002966 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002967
Douglas Gregor910f8002010-11-07 23:05:16 +00002968 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002969 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002970
Douglas Gregore7526412009-11-11 19:31:23 +00002971 case TemplateArgument::Expression:
2972 case TemplateArgument::Type:
2973 // We have a template template parameter but the template
2974 // argument does not refer to a template.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002975 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
David Blaikie4e4d0842012-03-11 07:00:24 +00002976 << getLangOpts().CPlusPlus0x;
Douglas Gregore7526412009-11-11 19:31:23 +00002977 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002978
Douglas Gregore7526412009-11-11 19:31:23 +00002979 case TemplateArgument::Declaration:
David Blaikie7530c032012-01-17 06:56:22 +00002980 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregore7526412009-11-11 19:31:23 +00002981 case TemplateArgument::Integral:
David Blaikie7530c032012-01-17 06:56:22 +00002982 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmand7a6b162012-09-26 02:36:12 +00002983 case TemplateArgument::NullPtr:
2984 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002985
Douglas Gregore7526412009-11-11 19:31:23 +00002986 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002987 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002988 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002989
Douglas Gregore7526412009-11-11 19:31:23 +00002990 return false;
2991}
2992
Douglas Gregor8fbbae52012-02-03 07:34:46 +00002993/// \brief Diagnose an arity mismatch in the
2994static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
2995 SourceLocation TemplateLoc,
2996 TemplateArgumentListInfo &TemplateArgs) {
2997 TemplateParameterList *Params = Template->getTemplateParameters();
2998 unsigned NumParams = Params->size();
2999 unsigned NumArgs = TemplateArgs.size();
3000
3001 SourceRange Range;
3002 if (NumArgs > NumParams)
3003 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3004 TemplateArgs.getRAngleLoc());
3005 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3006 << (NumArgs > NumParams)
3007 << (isa<ClassTemplateDecl>(Template)? 0 :
3008 isa<FunctionTemplateDecl>(Template)? 1 :
3009 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3010 << Template << Range;
3011 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3012 << Params->getSourceRange();
3013 return true;
3014}
3015
Richard Smith6964b3f2012-09-07 02:06:42 +00003016/// \brief Check whether the template parameter is a pack expansion, and if so,
3017/// determine the number of parameters produced by that expansion. For instance:
3018///
3019/// \code
3020/// template<typename ...Ts> struct A {
3021/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3022/// };
3023/// \endcode
3024///
3025/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3026/// is not a pack expansion, so returns an empty Optional.
3027static llvm::Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3028 if (NonTypeTemplateParmDecl *NTTP
3029 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3030 if (NTTP->isExpandedParameterPack())
3031 return NTTP->getNumExpansionTypes();
3032 }
3033
3034 if (TemplateTemplateParmDecl *TTP
3035 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3036 if (TTP->isExpandedParameterPack())
3037 return TTP->getNumExpansionTemplateParameters();
3038 }
3039
3040 return llvm::Optional<unsigned>();
3041}
3042
Douglas Gregorc15cb382009-02-09 23:23:08 +00003043/// \brief Check that the given template argument list is well-formed
3044/// for specializing the given template.
3045bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3046 SourceLocation TemplateLoc,
Douglas Gregor67714232011-03-03 02:41:12 +00003047 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00003048 bool PartialTemplateArgs,
Douglas Gregorb70126a2012-02-03 17:16:23 +00003049 SmallVectorImpl<TemplateArgument> &Converted,
3050 bool *ExpansionIntoFixedList) {
3051 if (ExpansionIntoFixedList)
3052 *ExpansionIntoFixedList = false;
3053
Douglas Gregorc15cb382009-02-09 23:23:08 +00003054 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregorc15cb382009-02-09 23:23:08 +00003055
John McCalld5532b62009-11-23 01:53:49 +00003056 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
3057
Mike Stump1eb44332009-09-09 15:08:12 +00003058 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00003059 // [...] The type and form of each template-argument specified in
3060 // a template-id shall match the type and form specified for the
3061 // corresponding parameter declared by the template in its
3062 // template-parameter-list.
Douglas Gregor67714232011-03-03 02:41:12 +00003063 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003064 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Smith6964b3f2012-09-07 02:06:42 +00003065 unsigned ArgIdx = 0, NumArgs = TemplateArgs.size();
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003066 LocalInstantiationScope InstScope(*this, true);
Richard Smith6964b3f2012-09-07 02:06:42 +00003067 for (TemplateParameterList::iterator Param = Params->begin(),
3068 ParamEnd = Params->end();
3069 Param != ParamEnd; /* increment in loop */) {
3070 // If we have an expanded parameter pack, make sure we don't have too
3071 // many arguments.
3072 if (llvm::Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3073 if (*Expansions == ArgumentPack.size()) {
3074 // We're done with this parameter pack. Pack up its arguments and add
3075 // them to the list.
Eli Friedmand7a6b162012-09-26 02:36:12 +00003076 Converted.push_back(
3077 TemplateArgument::CreatePackCopy(Context,
3078 ArgumentPack.data(),
3079 ArgumentPack.size()));
3080 ArgumentPack.clear();
3081
Richard Smith6964b3f2012-09-07 02:06:42 +00003082 // This argument is assigned to the next parameter.
3083 ++Param;
3084 continue;
3085 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3086 // Not enough arguments for this parameter pack.
3087 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3088 << false
3089 << (isa<ClassTemplateDecl>(Template)? 0 :
3090 isa<FunctionTemplateDecl>(Template)? 1 :
3091 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3092 << Template;
3093 Diag(Template->getLocation(), diag::note_template_decl_here)
3094 << Params->getSourceRange();
3095 return true;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00003096 }
Richard Smith6964b3f2012-09-07 02:06:42 +00003097 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003098
Richard Smith6964b3f2012-09-07 02:06:42 +00003099 if (ArgIdx < NumArgs) {
Douglas Gregorf35f8282009-11-11 21:54:23 +00003100 // Check the template argument we were given.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003101 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
3102 TemplateLoc, RAngleLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00003103 ArgumentPack.size(), Converted))
Douglas Gregorf35f8282009-11-11 21:54:23 +00003104 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003105
Richard Smith6964b3f2012-09-07 02:06:42 +00003106 // We're now done with this argument.
3107 ++ArgIdx;
3108
Douglas Gregor14be16b2010-12-20 16:57:52 +00003109 if ((*Param)->isTemplateParameterPack()) {
3110 // The template parameter was a template parameter pack, so take the
3111 // deduced argument and place it on the argument pack. Note that we
3112 // stay on the same template parameter so that we can deduce more
3113 // arguments.
3114 ArgumentPack.push_back(Converted.back());
3115 Converted.pop_back();
3116 } else {
3117 // Move to the next template parameter.
3118 ++Param;
3119 }
Richard Smith6964b3f2012-09-07 02:06:42 +00003120
3121 // If we just saw a pack expansion, then directly convert the remaining
3122 // arguments, because we don't know what parameters they'll match up
3123 // with.
3124 if (TemplateArgs[ArgIdx-1].getArgument().isPackExpansion()) {
3125 bool InFinalParameterPack = Param != ParamEnd &&
3126 Param + 1 == ParamEnd &&
3127 (*Param)->isTemplateParameterPack() &&
3128 !getExpandedPackSize(*Param);
3129
3130 if (!InFinalParameterPack && !ArgumentPack.empty()) {
3131 // If we were part way through filling in an expanded parameter pack,
3132 // fall back to just producing individual arguments.
3133 Converted.insert(Converted.end(),
3134 ArgumentPack.begin(), ArgumentPack.end());
3135 ArgumentPack.clear();
3136 }
3137
3138 while (ArgIdx < NumArgs) {
3139 if (InFinalParameterPack)
3140 ArgumentPack.push_back(TemplateArgs[ArgIdx].getArgument());
3141 else
3142 Converted.push_back(TemplateArgs[ArgIdx].getArgument());
3143 ++ArgIdx;
3144 }
3145
3146 // Push the argument pack onto the list of converted arguments.
3147 if (InFinalParameterPack) {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003148 Converted.push_back(
3149 TemplateArgument::CreatePackCopy(Context,
3150 ArgumentPack.data(),
3151 ArgumentPack.size()));
3152 ArgumentPack.clear();
Richard Smith6964b3f2012-09-07 02:06:42 +00003153 } else if (ExpansionIntoFixedList) {
3154 // We have expanded a pack into a fixed list.
3155 *ExpansionIntoFixedList = true;
3156 }
3157
3158 return false;
Douglas Gregor8fbbae52012-02-03 07:34:46 +00003159 }
Richard Smith6964b3f2012-09-07 02:06:42 +00003160
Douglas Gregorf35f8282009-11-11 21:54:23 +00003161 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003162 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003163
Douglas Gregor8735b292011-06-03 02:59:40 +00003164 // If we're checking a partial template argument list, we're done.
3165 if (PartialTemplateArgs) {
3166 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3167 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3168 ArgumentPack.data(),
3169 ArgumentPack.size()));
3170
Richard Smith6964b3f2012-09-07 02:06:42 +00003171 return false;
Douglas Gregor8735b292011-06-03 02:59:40 +00003172 }
3173
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003174 // If we have a template parameter pack with no more corresponding
Douglas Gregor14be16b2010-12-20 16:57:52 +00003175 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith6964b3f2012-09-07 02:06:42 +00003176 if ((*Param)->isTemplateParameterPack()) {
3177 assert(!getExpandedPackSize(*Param) &&
3178 "Should have dealt with this already");
3179
3180 // A non-expanded parameter pack before the end of the parameter list
3181 // only occurs for an ill-formed template parameter list, unless we've
3182 // got a partial argument list for a function template, so just bail out.
3183 if (Param + 1 != ParamEnd)
3184 return true;
3185
Eli Friedmand7a6b162012-09-26 02:36:12 +00003186 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3187 ArgumentPack.data(),
3188 ArgumentPack.size()));
3189 ArgumentPack.clear();
Richard Smith6964b3f2012-09-07 02:06:42 +00003190
3191 ++Param;
3192 continue;
3193 }
3194
Douglas Gregor8fbbae52012-02-03 07:34:46 +00003195 // Check whether we have a default argument.
Douglas Gregorf35f8282009-11-11 21:54:23 +00003196 TemplateArgumentLoc Arg;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003197
Douglas Gregorf35f8282009-11-11 21:54:23 +00003198 // Retrieve the default template argument from the template
3199 // parameter. For each kind of template parameter, we substitute the
3200 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003201 // (when the template parameter was part of a nested template) into
Douglas Gregorf35f8282009-11-11 21:54:23 +00003202 // the default argument.
3203 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Douglas Gregor8fbbae52012-02-03 07:34:46 +00003204 if (!TTP->hasDefaultArgument())
3205 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3206 TemplateArgs);
Douglas Gregorf35f8282009-11-11 21:54:23 +00003207
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003208 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00003209 Template,
3210 TemplateLoc,
3211 RAngleLoc,
3212 TTP,
3213 Converted);
3214 if (!ArgType)
3215 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003216
Douglas Gregorf35f8282009-11-11 21:54:23 +00003217 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3218 ArgType);
3219 } else if (NonTypeTemplateParmDecl *NTTP
3220 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Douglas Gregor8fbbae52012-02-03 07:34:46 +00003221 if (!NTTP->hasDefaultArgument())
3222 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3223 TemplateArgs);
Douglas Gregorf35f8282009-11-11 21:54:23 +00003224
John McCall60d7b3a2010-08-24 06:29:42 +00003225 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003226 TemplateLoc,
3227 RAngleLoc,
3228 NTTP,
Douglas Gregorf35f8282009-11-11 21:54:23 +00003229 Converted);
3230 if (E.isInvalid())
3231 return true;
3232
3233 Expr *Ex = E.takeAs<Expr>();
3234 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3235 } else {
3236 TemplateTemplateParmDecl *TempParm
3237 = cast<TemplateTemplateParmDecl>(*Param);
3238
Douglas Gregor8fbbae52012-02-03 07:34:46 +00003239 if (!TempParm->hasDefaultArgument())
3240 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3241 TemplateArgs);
Douglas Gregorf35f8282009-11-11 21:54:23 +00003242
Douglas Gregor1d752d72011-03-02 18:46:51 +00003243 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregorf35f8282009-11-11 21:54:23 +00003244 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003245 TemplateLoc,
3246 RAngleLoc,
Douglas Gregorf35f8282009-11-11 21:54:23 +00003247 TempParm,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00003248 Converted,
3249 QualifierLoc);
Douglas Gregorf35f8282009-11-11 21:54:23 +00003250 if (Name.isNull())
3251 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003252
Douglas Gregorb6744ef2011-03-02 17:09:35 +00003253 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3254 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregorf35f8282009-11-11 21:54:23 +00003255 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003256
Douglas Gregorf35f8282009-11-11 21:54:23 +00003257 // Introduce an instantiation record that describes where we are using
3258 // the default template argument.
Richard Smith7e54fb52012-07-16 01:09:10 +00003259 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template,
3260 *Param, Converted,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003261 SourceRange(TemplateLoc, RAngleLoc));
Richard Smithab91ef12012-07-08 02:38:24 +00003262 if (Instantiating)
3263 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003264
Douglas Gregorf35f8282009-11-11 21:54:23 +00003265 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00003266 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00003267 RAngleLoc, 0, Converted))
Douglas Gregore7526412009-11-11 19:31:23 +00003268 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003269
Douglas Gregor67714232011-03-03 02:41:12 +00003270 // Core issue 150 (assumed resolution): if this is a template template
3271 // parameter, keep track of the default template arguments from the
3272 // template definition.
3273 if (isTemplateTemplateParameter)
3274 TemplateArgs.addArgument(Arg);
3275
Douglas Gregor14be16b2010-12-20 16:57:52 +00003276 // Move to the next template parameter and argument.
3277 ++Param;
3278 ++ArgIdx;
Douglas Gregorc15cb382009-02-09 23:23:08 +00003279 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003280
Douglas Gregor8fbbae52012-02-03 07:34:46 +00003281 // If we have any leftover arguments, then there were too many arguments.
3282 // Complain and fail.
3283 if (ArgIdx < NumArgs)
3284 return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003285
Richard Smith6964b3f2012-09-07 02:06:42 +00003286 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00003287}
3288
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003289namespace {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003290 class UnnamedLocalNoLinkageFinder
3291 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003292 {
3293 Sema &S;
3294 SourceRange SR;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003295
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003296 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003297
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003298 public:
3299 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3300
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003301 bool Visit(QualType T) {
3302 return inherited::Visit(T.getTypePtr());
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003303 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003304
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003305#define TYPE(Class, Parent) \
3306 bool Visit##Class##Type(const Class##Type *);
3307#define ABSTRACT_TYPE(Class, Parent) \
3308 bool Visit##Class##Type(const Class##Type *) { return false; }
3309#define NON_CANONICAL_TYPE(Class, Parent) \
3310 bool Visit##Class##Type(const Class##Type *) { return false; }
3311#include "clang/AST/TypeNodes.def"
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003312
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003313 bool VisitTagDecl(const TagDecl *Tag);
3314 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3315 };
3316}
3317
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003318bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003319 return false;
3320}
3321
3322bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3323 return Visit(T->getElementType());
3324}
3325
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003326bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003327 return Visit(T->getPointeeType());
3328}
3329
3330bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003331 const BlockPointerType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003332 return Visit(T->getPointeeType());
3333}
3334
3335bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003336 const LValueReferenceType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003337 return Visit(T->getPointeeType());
3338}
3339
3340bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003341 const RValueReferenceType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003342 return Visit(T->getPointeeType());
3343}
3344
3345bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003346 const MemberPointerType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003347 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3348}
3349
3350bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003351 const ConstantArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003352 return Visit(T->getElementType());
3353}
3354
3355bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003356 const IncompleteArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003357 return Visit(T->getElementType());
3358}
3359
3360bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003361 const VariableArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003362 return Visit(T->getElementType());
3363}
3364
3365bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003366 const DependentSizedArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003367 return Visit(T->getElementType());
3368}
3369
3370bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003371 const DependentSizedExtVectorType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003372 return Visit(T->getElementType());
3373}
3374
3375bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3376 return Visit(T->getElementType());
3377}
3378
3379bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3380 return Visit(T->getElementType());
3381}
3382
3383bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3384 const FunctionProtoType* T) {
3385 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003386 AEnd = T->arg_type_end();
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003387 A != AEnd; ++A) {
3388 if (Visit(*A))
3389 return true;
3390 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003391
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003392 return Visit(T->getResultType());
3393}
3394
3395bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3396 const FunctionNoProtoType* T) {
3397 return Visit(T->getResultType());
3398}
3399
3400bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3401 const UnresolvedUsingType*) {
3402 return false;
3403}
3404
3405bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3406 return false;
3407}
3408
3409bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
3410 return Visit(T->getUnderlyingType());
3411}
3412
3413bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
3414 return false;
3415}
3416
Sean Huntca63c202011-05-24 22:41:36 +00003417bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
3418 const UnaryTransformType*) {
3419 return false;
3420}
3421
Richard Smith34b41d92011-02-20 03:19:35 +00003422bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
3423 return Visit(T->getDeducedType());
3424}
3425
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003426bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
3427 return VisitTagDecl(T->getDecl());
3428}
3429
3430bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
3431 return VisitTagDecl(T->getDecl());
3432}
3433
3434bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
3435 const TemplateTypeParmType*) {
3436 return false;
3437}
3438
Douglas Gregorc3069d62011-01-14 02:55:32 +00003439bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
3440 const SubstTemplateTypeParmPackType *) {
3441 return false;
3442}
3443
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003444bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
3445 const TemplateSpecializationType*) {
3446 return false;
3447}
3448
3449bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
3450 const InjectedClassNameType* T) {
3451 return VisitTagDecl(T->getDecl());
3452}
3453
3454bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
3455 const DependentNameType* T) {
3456 return VisitNestedNameSpecifier(T->getQualifier());
3457}
3458
3459bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
3460 const DependentTemplateSpecializationType* T) {
3461 return VisitNestedNameSpecifier(T->getQualifier());
3462}
3463
Douglas Gregor7536dd52010-12-20 02:24:11 +00003464bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
3465 const PackExpansionType* T) {
3466 return Visit(T->getPattern());
3467}
3468
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003469bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
3470 return false;
3471}
3472
3473bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
3474 const ObjCInterfaceType *) {
3475 return false;
3476}
3477
3478bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
3479 const ObjCObjectPointerType *) {
3480 return false;
3481}
3482
Eli Friedmanb001de72011-10-06 23:00:33 +00003483bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
3484 return Visit(T->getValueType());
3485}
3486
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003487bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
3488 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003489 S.Diag(SR.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00003490 S.getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00003491 diag::warn_cxx98_compat_template_arg_local_type :
3492 diag::ext_template_arg_local_type)
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003493 << S.Context.getTypeDeclType(Tag) << SR;
3494 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003495 }
3496
Richard Smith162e1c12011-04-15 14:24:37 +00003497 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl()) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003498 S.Diag(SR.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00003499 S.getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00003500 diag::warn_cxx98_compat_template_arg_unnamed_type :
3501 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003502 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
3503 return true;
3504 }
3505
3506 return false;
3507}
3508
3509bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
3510 NestedNameSpecifier *NNS) {
3511 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
3512 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003513
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003514 switch (NNS->getKind()) {
3515 case NestedNameSpecifier::Identifier:
3516 case NestedNameSpecifier::Namespace:
Douglas Gregor14aba762011-02-24 02:36:08 +00003517 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003518 case NestedNameSpecifier::Global:
3519 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003520
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003521 case NestedNameSpecifier::TypeSpec:
3522 case NestedNameSpecifier::TypeSpecWithTemplate:
3523 return Visit(QualType(NNS->getAsType(), 0));
3524 }
David Blaikie7530c032012-01-17 06:56:22 +00003525 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003526}
3527
3528
Douglas Gregorc15cb382009-02-09 23:23:08 +00003529/// \brief Check a template argument against its corresponding
3530/// template type parameter.
3531///
3532/// This routine implements the semantics of C++ [temp.arg.type]. It
3533/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003534bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00003535 TypeSourceInfo *ArgInfo) {
3536 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00003537 QualType Arg = ArgInfo->getType();
Douglas Gregor0fddb972010-05-22 16:17:30 +00003538 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00003539
3540 if (Arg->isVariablyModifiedType()) {
3541 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00003542 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00003543 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00003544 }
3545
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003546 // C++03 [temp.arg.type]p2:
3547 // A local type, a type with no linkage, an unnamed type or a type
3548 // compounded from any of these types shall not be used as a
3549 // template-argument for a template type-parameter.
3550 //
Richard Smithebaf0e62011-10-18 20:49:44 +00003551 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003552 // a warning.
Richard Smithebaf0e62011-10-18 20:49:44 +00003553 if (LangOpts.CPlusPlus0x ?
3554 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_unnamed_type,
3555 SR.getBegin()) != DiagnosticsEngine::Ignored ||
3556 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_local_type,
3557 SR.getBegin()) != DiagnosticsEngine::Ignored :
3558 Arg->hasUnnamedOrLocalType()) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003559 UnnamedLocalNoLinkageFinder Finder(*this, SR);
3560 (void)Finder.Visit(Context.getCanonicalType(Arg));
3561 }
3562
Douglas Gregorc15cb382009-02-09 23:23:08 +00003563 return false;
3564}
3565
Douglas Gregor42963612012-04-10 17:08:25 +00003566enum NullPointerValueKind {
3567 NPV_NotNullPointer,
3568 NPV_NullPointer,
3569 NPV_Error
3570};
3571
3572/// \brief Determine whether the given template argument is a null pointer
3573/// value of the appropriate type.
3574static NullPointerValueKind
3575isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
3576 QualType ParamType, Expr *Arg) {
3577 if (Arg->isValueDependent() || Arg->isTypeDependent())
3578 return NPV_NotNullPointer;
3579
3580 if (!S.getLangOpts().CPlusPlus0x)
3581 return NPV_NotNullPointer;
3582
3583 // Determine whether we have a constant expression.
Douglas Gregor50fadd12012-04-10 19:03:30 +00003584 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
3585 if (ArgRV.isInvalid())
3586 return NPV_Error;
3587 Arg = ArgRV.take();
3588
Douglas Gregor42963612012-04-10 17:08:25 +00003589 Expr::EvalResult EvalResult;
Douglas Gregor50fadd12012-04-10 19:03:30 +00003590 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
3591 EvalResult.Diag = &Notes;
Douglas Gregor42963612012-04-10 17:08:25 +00003592 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor50fadd12012-04-10 19:03:30 +00003593 EvalResult.HasSideEffects) {
3594 SourceLocation DiagLoc = Arg->getExprLoc();
3595
3596 // If our only note is the usual "invalid subexpression" note, just point
3597 // the caret at its location rather than producing an essentially
3598 // redundant note.
3599 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
3600 diag::note_invalid_subexpr_in_const_expr) {
3601 DiagLoc = Notes[0].first;
3602 Notes.clear();
3603 }
3604
3605 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
3606 << Arg->getType() << Arg->getSourceRange();
3607 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
3608 S.Diag(Notes[I].first, Notes[I].second);
3609
3610 S.Diag(Param->getLocation(), diag::note_template_param_here);
3611 return NPV_Error;
3612 }
Douglas Gregor42963612012-04-10 17:08:25 +00003613
3614 // C++11 [temp.arg.nontype]p1:
3615 // - an address constant expression of type std::nullptr_t
3616 if (Arg->getType()->isNullPtrType())
3617 return NPV_NullPointer;
3618
3619 // - a constant expression that evaluates to a null pointer value (4.10); or
3620 // - a constant expression that evaluates to a null member pointer value
3621 // (4.11); or
3622 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
3623 (EvalResult.Val.isMemberPointer() &&
3624 !EvalResult.Val.getMemberPointerDecl())) {
3625 // If our expression has an appropriate type, we've succeeded.
3626 bool ObjCLifetimeConversion;
3627 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
3628 S.IsQualificationConversion(Arg->getType(), ParamType, false,
3629 ObjCLifetimeConversion))
3630 return NPV_NullPointer;
3631
3632 // The types didn't match, but we know we got a null pointer; complain,
3633 // then recover as if the types were correct.
3634 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
3635 << Arg->getType() << ParamType << Arg->getSourceRange();
3636 S.Diag(Param->getLocation(), diag::note_template_param_here);
3637 return NPV_NullPointer;
3638 }
3639
3640 // If we don't have a null pointer value, but we do have a NULL pointer
3641 // constant, suggest a cast to the appropriate type.
3642 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
3643 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
3644 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
3645 << ParamType
3646 << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
3647 << FixItHint::CreateInsertion(S.PP.getLocForEndOfToken(Arg->getLocEnd()),
3648 ")");
3649 S.Diag(Param->getLocation(), diag::note_template_param_here);
3650 return NPV_NullPointer;
3651 }
3652
3653 // FIXME: If we ever want to support general, address-constant expressions
3654 // as non-type template arguments, we should return the ExprResult here to
3655 // be interpreted by the caller.
3656 return NPV_NotNullPointer;
3657}
3658
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003659/// \brief Checks whether the given template argument is the address
3660/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003661static bool
Douglas Gregorb7a09262010-04-01 18:32:35 +00003662CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
3663 NonTypeTemplateParmDecl *Param,
3664 QualType ParamType,
3665 Expr *ArgIn,
3666 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003667 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00003668 Expr *Arg = ArgIn;
3669 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003670
Douglas Gregor42963612012-04-10 17:08:25 +00003671 // If our parameter has pointer type, check for a null template value.
3672 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
3673 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
3674 case NPV_NullPointer:
Richard Smith86e6fdc2012-04-26 01:51:03 +00003675 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Eli Friedmand7a6b162012-09-26 02:36:12 +00003676 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
Douglas Gregor42963612012-04-10 17:08:25 +00003677 return false;
3678
3679 case NPV_Error:
3680 return true;
3681
3682 case NPV_NotNullPointer:
3683 break;
3684 }
3685 }
3686
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003687 // See through any implicit casts we added to fix the type.
John McCall91a57552011-07-15 05:09:51 +00003688 Arg = Arg->IgnoreImpCasts();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003689
3690 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003691 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003692 // A template-argument for a non-type, non-template
3693 // template-parameter shall be one of: [...]
3694 //
3695 // -- the address of an object or function with external
3696 // linkage, including function templates and function
3697 // template-ids but excluding non-static class members,
3698 // expressed as & id-expression where the & is optional if
3699 // the name refers to a function or array, or if the
3700 // corresponding template-parameter is a reference; or
Mike Stump1eb44332009-09-09 15:08:12 +00003701
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003702 // In C++98/03 mode, give an extension warning on any extra parentheses.
3703 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3704 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003705 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003706 if (!Invalid && !ExtraParens) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003707 S.Diag(Arg->getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00003708 S.getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00003709 diag::warn_cxx98_compat_template_arg_extra_parens :
3710 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003711 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003712 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003713 }
3714
3715 Arg = Parens->getSubExpr();
3716 }
3717
John McCall91a57552011-07-15 05:09:51 +00003718 while (SubstNonTypeTemplateParmExpr *subst =
3719 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3720 Arg = subst->getReplacement()->IgnoreImpCasts();
3721
Douglas Gregorb7a09262010-04-01 18:32:35 +00003722 bool AddressTaken = false;
3723 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003724 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003725 if (UnOp->getOpcode() == UO_AddrOf) {
John McCall91a57552011-07-15 05:09:51 +00003726 Arg = UnOp->getSubExpr();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003727 AddressTaken = true;
3728 AddrOpLoc = UnOp->getOperatorLoc();
3729 }
Francois Picheta343a412011-04-29 09:08:14 +00003730 }
John McCall91a57552011-07-15 05:09:51 +00003731
David Blaikie4e4d0842012-03-11 07:00:24 +00003732 if (S.getLangOpts().MicrosoftExt && isa<CXXUuidofExpr>(Arg)) {
John McCall91a57552011-07-15 05:09:51 +00003733 Converted = TemplateArgument(ArgIn);
3734 return false;
3735 }
3736
3737 while (SubstNonTypeTemplateParmExpr *subst =
3738 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3739 Arg = subst->getReplacement()->IgnoreImpCasts();
3740
Chandler Carruth038cc392010-01-31 10:01:20 +00003741 // Stop checking the precise nature of the argument if it is value dependent,
3742 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00003743 if (Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00003744 Converted = TemplateArgument(ArgIn);
Chandler Carruth038cc392010-01-31 10:01:20 +00003745 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00003746 }
Douglas Gregord2008e22012-04-06 22:40:38 +00003747
3748 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
3749 if (!DRE) {
3750 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
3751 << Arg->getSourceRange();
3752 S.Diag(Param->getLocation(), diag::note_template_param_here);
3753 return true;
3754 }
Chandler Carruth038cc392010-01-31 10:01:20 +00003755
Douglas Gregorb7a09262010-04-01 18:32:35 +00003756 if (!isa<ValueDecl>(DRE->getDecl())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003757 S.Diag(Arg->getLocStart(),
Douglas Gregorb7a09262010-04-01 18:32:35 +00003758 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003759 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003760 S.Diag(Param->getLocation(), diag::note_template_param_here);
3761 return true;
3762 }
3763
Eli Friedmand7a6b162012-09-26 02:36:12 +00003764 ValueDecl *Entity = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003765
3766 // Cannot refer to non-static data members
Richard Smithb4051e72012-04-04 21:11:30 +00003767 if (FieldDecl *Field = dyn_cast<FieldDecl>(Entity)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003768 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003769 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003770 S.Diag(Param->getLocation(), diag::note_template_param_here);
3771 return true;
3772 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003773
3774 // Cannot refer to non-static member functions
Richard Smithb4051e72012-04-04 21:11:30 +00003775 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003776 if (!Method->isStatic()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003777 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003778 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003779 S.Diag(Param->getLocation(), diag::note_template_param_here);
3780 return true;
3781 }
Richard Smithb4051e72012-04-04 21:11:30 +00003782 }
Mike Stump1eb44332009-09-09 15:08:12 +00003783
Richard Smithb4051e72012-04-04 21:11:30 +00003784 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
3785 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003786
Richard Smithb4051e72012-04-04 21:11:30 +00003787 // A non-type template argument must refer to an object or function.
3788 if (!Func && !Var) {
3789 // We found something, but we don't know specifically what it is.
3790 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
3791 << Arg->getSourceRange();
3792 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
3793 return true;
3794 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003795
Richard Smithb4051e72012-04-04 21:11:30 +00003796 // Address / reference template args must have external linkage in C++98.
3797 if (Entity->getLinkage() == InternalLinkage) {
3798 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus0x ?
3799 diag::warn_cxx98_compat_template_arg_object_internal :
3800 diag::ext_template_arg_object_internal)
3801 << !Func << Entity << Arg->getSourceRange();
3802 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
3803 << !Func;
3804 } else if (Entity->getLinkage() == NoLinkage) {
3805 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
3806 << !Func << Entity << Arg->getSourceRange();
3807 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
3808 << !Func;
3809 return true;
3810 }
3811
3812 if (Func) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003813 // If the template parameter has pointer type, the function decays.
3814 if (ParamType->isPointerType() && !AddressTaken)
3815 ArgType = S.Context.getPointerType(Func->getType());
3816 else if (AddressTaken && ParamType->isReferenceType()) {
3817 // If we originally had an address-of operator, but the
3818 // parameter has reference type, complain and (if things look
3819 // like they will work) drop the address-of operator.
3820 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
3821 ParamType.getNonReferenceType())) {
3822 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3823 << ParamType;
3824 S.Diag(Param->getLocation(), diag::note_template_param_here);
3825 return true;
3826 }
3827
3828 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3829 << ParamType
3830 << FixItHint::CreateRemoval(AddrOpLoc);
3831 S.Diag(Param->getLocation(), diag::note_template_param_here);
3832
3833 ArgType = Func->getType();
3834 }
Richard Smithb4051e72012-04-04 21:11:30 +00003835 } else {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003836 // A value of reference type is not an object.
3837 if (Var->getType()->isReferenceType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003838 S.Diag(Arg->getLocStart(),
Douglas Gregorb7a09262010-04-01 18:32:35 +00003839 diag::err_template_arg_reference_var)
3840 << Var->getType() << Arg->getSourceRange();
3841 S.Diag(Param->getLocation(), diag::note_template_param_here);
3842 return true;
3843 }
3844
Richard Smithb4051e72012-04-04 21:11:30 +00003845 // A template argument must have static storage duration.
3846 // FIXME: Ensure this works for thread_local as well as __thread.
3847 if (Var->isThreadSpecified()) {
3848 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
3849 << Arg->getSourceRange();
3850 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
3851 return true;
3852 }
Douglas Gregorb7a09262010-04-01 18:32:35 +00003853
3854 // If the template parameter has pointer type, we must have taken
3855 // the address of this object.
3856 if (ParamType->isReferenceType()) {
3857 if (AddressTaken) {
3858 // If we originally had an address-of operator, but the
3859 // parameter has reference type, complain and (if things look
3860 // like they will work) drop the address-of operator.
3861 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
3862 ParamType.getNonReferenceType())) {
3863 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3864 << ParamType;
3865 S.Diag(Param->getLocation(), diag::note_template_param_here);
3866 return true;
3867 }
3868
3869 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3870 << ParamType
3871 << FixItHint::CreateRemoval(AddrOpLoc);
3872 S.Diag(Param->getLocation(), diag::note_template_param_here);
3873
3874 ArgType = Var->getType();
3875 }
3876 } else if (!AddressTaken && ParamType->isPointerType()) {
3877 if (Var->getType()->isArrayType()) {
3878 // Array-to-pointer decay.
3879 ArgType = S.Context.getArrayDecayedType(Var->getType());
3880 } else {
3881 // If the template parameter has pointer type but the address of
3882 // this object was not taken, complain and (possibly) recover by
3883 // taking the address of the entity.
3884 ArgType = S.Context.getPointerType(Var->getType());
3885 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
3886 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3887 << ParamType;
3888 S.Diag(Param->getLocation(), diag::note_template_param_here);
3889 return true;
3890 }
3891
3892 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3893 << ParamType
3894 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
3895
3896 S.Diag(Param->getLocation(), diag::note_template_param_here);
3897 }
3898 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003899 }
Mike Stump1eb44332009-09-09 15:08:12 +00003900
John McCallf85e1932011-06-15 23:02:42 +00003901 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003902 if (ParamType->isPointerType() &&
Douglas Gregorb7a09262010-04-01 18:32:35 +00003903 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
John McCallf85e1932011-06-15 23:02:42 +00003904 S.IsQualificationConversion(ArgType, ParamType, false,
3905 ObjCLifetimeConversion)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003906 // For pointer-to-object types, qualification conversions are
3907 // permitted.
3908 } else {
3909 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
3910 if (!ParamRef->getPointeeType()->isFunctionType()) {
3911 // C++ [temp.arg.nontype]p5b3:
3912 // For a non-type template-parameter of type reference to
3913 // object, no conversions apply. The type referred to by the
3914 // reference may be more cv-qualified than the (otherwise
3915 // identical) type of the template- argument. The
3916 // template-parameter is bound directly to the
3917 // template-argument, which shall be an lvalue.
3918
3919 // FIXME: Other qualifiers?
3920 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
3921 unsigned ArgQuals = ArgType.getCVRQualifiers();
3922
3923 if ((ParamQuals | ArgQuals) != ParamQuals) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003924 S.Diag(Arg->getLocStart(),
Douglas Gregorb7a09262010-04-01 18:32:35 +00003925 diag::err_template_arg_ref_bind_ignores_quals)
3926 << ParamType << Arg->getType()
3927 << Arg->getSourceRange();
3928 S.Diag(Param->getLocation(), diag::note_template_param_here);
3929 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003930 }
Douglas Gregorb7a09262010-04-01 18:32:35 +00003931 }
3932 }
3933
3934 // At this point, the template argument refers to an object or
3935 // function with external linkage. We now need to check whether the
3936 // argument and parameter types are compatible.
3937 if (!S.Context.hasSameUnqualifiedType(ArgType,
3938 ParamType.getNonReferenceType())) {
3939 // We can't perform this conversion or binding.
3940 if (ParamType->isReferenceType())
3941 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
John McCall91a57552011-07-15 05:09:51 +00003942 << ParamType << ArgIn->getType() << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003943 else
3944 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
John McCall91a57552011-07-15 05:09:51 +00003945 << ArgIn->getType() << ParamType << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003946 S.Diag(Param->getLocation(), diag::note_template_param_here);
3947 return true;
3948 }
3949 }
3950
3951 // Create the template argument.
Eli Friedmand7a6b162012-09-26 02:36:12 +00003952 Converted = TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
3953 ParamType->isReferenceType());
Eli Friedman5f2987c2012-02-02 03:46:19 +00003954 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00003955 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003956}
3957
3958/// \brief Checks whether the given template argument is a pointer to
3959/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor42963612012-04-10 17:08:25 +00003960static bool CheckTemplateArgumentPointerToMember(Sema &S,
3961 NonTypeTemplateParmDecl *Param,
3962 QualType ParamType,
3963 Expr *&ResultArg,
3964 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003965 bool Invalid = false;
3966
Douglas Gregor42963612012-04-10 17:08:25 +00003967 // Check for a null pointer value.
3968 Expr *Arg = ResultArg;
3969 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
3970 case NPV_Error:
3971 return true;
3972 case NPV_NullPointer:
Richard Smith86e6fdc2012-04-26 01:51:03 +00003973 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Eli Friedmand7a6b162012-09-26 02:36:12 +00003974 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
Douglas Gregor42963612012-04-10 17:08:25 +00003975 return false;
3976 case NPV_NotNullPointer:
3977 break;
3978 }
3979
3980 bool ObjCLifetimeConversion;
3981 if (S.IsQualificationConversion(Arg->getType(),
3982 ParamType.getNonReferenceType(),
3983 false, ObjCLifetimeConversion)) {
3984 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
3985 Arg->getValueKind()).take();
3986 ResultArg = Arg;
3987 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
3988 ParamType.getNonReferenceType())) {
3989 // We can't perform this conversion.
3990 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
3991 << Arg->getType() << ParamType << Arg->getSourceRange();
3992 S.Diag(Param->getLocation(), diag::note_template_param_here);
3993 return true;
3994 }
3995
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003996 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003997 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003998 Arg = Cast->getSubExpr();
3999
4000 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004001 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00004002 // A template-argument for a non-type, non-template
4003 // template-parameter shall be one of: [...]
4004 //
4005 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00004006 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00004007
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00004008 // In C++98/03 mode, give an extension warning on any extra parentheses.
4009 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4010 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00004011 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smithebaf0e62011-10-18 20:49:44 +00004012 if (!Invalid && !ExtraParens) {
Douglas Gregor42963612012-04-10 17:08:25 +00004013 S.Diag(Arg->getLocStart(),
4014 S.getLangOpts().CPlusPlus0x ?
4015 diag::warn_cxx98_compat_template_arg_extra_parens :
4016 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00004017 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00004018 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00004019 }
4020
4021 Arg = Parens->getSubExpr();
4022 }
4023
John McCall91a57552011-07-15 05:09:51 +00004024 while (SubstNonTypeTemplateParmExpr *subst =
4025 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4026 Arg = subst->getReplacement()->IgnoreImpCasts();
4027
Douglas Gregorcaddba02009-11-12 18:38:13 +00004028 // A pointer-to-member constant written &Class::member.
4029 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00004030 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00004031 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4032 if (DRE && !DRE->getQualifier())
4033 DRE = 0;
4034 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004035 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00004036 // A constant of pointer-to-member type.
4037 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4038 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4039 if (VD->getType()->isMemberPointerType()) {
4040 if (isa<NonTypeTemplateParmDecl>(VD) ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004041 (isa<VarDecl>(VD) &&
Douglas Gregor42963612012-04-10 17:08:25 +00004042 S.Context.getCanonicalType(VD->getType()).isConstQualified())) {
Eli Friedmand7a6b162012-09-26 02:36:12 +00004043 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00004044 Converted = TemplateArgument(Arg);
Eli Friedmand7a6b162012-09-26 02:36:12 +00004045 } else {
4046 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4047 Converted = TemplateArgument(VD, /*isReferenceParam*/false);
4048 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00004049 return Invalid;
4050 }
4051 }
4052 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004053
Douglas Gregorcaddba02009-11-12 18:38:13 +00004054 DRE = 0;
4055 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004056
Douglas Gregorcc45cb32009-02-11 19:52:55 +00004057 if (!DRE)
Douglas Gregor42963612012-04-10 17:08:25 +00004058 return S.Diag(Arg->getLocStart(),
4059 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00004060 << Arg->getSourceRange();
4061
4062 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
4063 assert((isa<FieldDecl>(DRE->getDecl()) ||
4064 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4065 "Only non-static member pointers can make it here");
4066
4067 // Okay: this is the address of a non-static member, and therefore
4068 // a member pointer constant.
Eli Friedmand7a6b162012-09-26 02:36:12 +00004069 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00004070 Converted = TemplateArgument(Arg);
Eli Friedmand7a6b162012-09-26 02:36:12 +00004071 } else {
4072 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4073 Converted = TemplateArgument(D, /*isReferenceParam*/false);
4074 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00004075 return Invalid;
4076 }
4077
4078 // We found something else, but we don't know specifically what it is.
Douglas Gregor42963612012-04-10 17:08:25 +00004079 S.Diag(Arg->getLocStart(),
4080 diag::err_template_arg_not_pointer_to_member_form)
4081 << Arg->getSourceRange();
4082 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorcc45cb32009-02-11 19:52:55 +00004083 return true;
4084}
4085
Douglas Gregorc15cb382009-02-09 23:23:08 +00004086/// \brief Check a template argument against its corresponding
4087/// non-type template parameter.
4088///
Douglas Gregor2943aed2009-03-03 04:44:36 +00004089/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley429bb272011-04-08 18:41:53 +00004090/// If an error occurred, it returns ExprError(); otherwise, it
4091/// returns the converted template argument. \p
Douglas Gregor2943aed2009-03-03 04:44:36 +00004092/// InstantiatedParamType is the type of the non-type template
4093/// parameter after it has been instantiated.
John Wiegley429bb272011-04-08 18:41:53 +00004094ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4095 QualType InstantiatedParamType, Expr *Arg,
4096 TemplateArgument &Converted,
4097 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004098 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregor40808ce2009-03-09 23:48:35 +00004099
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004100 // If either the parameter has a dependent type or the argument is
4101 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00004102 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
4103 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00004104 Converted = TemplateArgument(Arg);
John Wiegley429bb272011-04-08 18:41:53 +00004105 return Owned(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00004106 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004107
4108 // C++ [temp.arg.nontype]p5:
4109 // The following conversions are performed on each expression used
4110 // as a non-type template-argument. If a non-type
4111 // template-argument cannot be converted to the type of the
4112 // corresponding template-parameter then the program is
4113 // ill-formed.
Douglas Gregor2943aed2009-03-03 04:44:36 +00004114 QualType ParamType = InstantiatedParamType;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004115 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004116 // C++11:
4117 // -- for a non-type template-parameter of integral or
4118 // enumeration type, conversions permitted in a converted
4119 // constant expression are applied.
4120 //
4121 // C++98:
4122 // -- for a non-type template-parameter of integral or
4123 // enumeration type, integral promotions (4.5) and integral
4124 // conversions (4.7) are applied.
4125
4126 if (CTAK == CTAK_Deduced &&
4127 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4128 // C++ [temp.deduct.type]p17:
4129 // If, in the declaration of a function template with a non-type
4130 // template-parameter, the non-type template-parameter is used
4131 // in an expression in the function parameter-list and, if the
4132 // corresponding template-argument is deduced, the
4133 // template-argument type shall match the type of the
4134 // template-parameter exactly, except that a template-argument
4135 // deduced from an array bound may be of any integral type.
4136 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4137 << Arg->getType().getUnqualifiedType()
4138 << ParamType.getUnqualifiedType();
4139 Diag(Param->getLocation(), diag::note_template_param_here);
4140 return ExprError();
4141 }
4142
David Blaikie4e4d0842012-03-11 07:00:24 +00004143 if (getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004144 // We can't check arbitrary value-dependent arguments.
4145 // FIXME: If there's no viable conversion to the template parameter type,
4146 // we should be able to diagnose that prior to instantiation.
4147 if (Arg->isValueDependent()) {
4148 Converted = TemplateArgument(Arg);
4149 return Owned(Arg);
4150 }
4151
4152 // C++ [temp.arg.nontype]p1:
4153 // A template-argument for a non-type, non-template template-parameter
4154 // shall be one of:
4155 //
4156 // -- for a non-type template-parameter of integral or enumeration
4157 // type, a converted constant expression of the type of the
4158 // template-parameter; or
4159 llvm::APSInt Value;
4160 ExprResult ArgResult =
4161 CheckConvertedConstantExpression(Arg, ParamType, Value,
4162 CCEK_TemplateArg);
4163 if (ArgResult.isInvalid())
4164 return ExprError();
4165
4166 // Widen the argument value to sizeof(parameter type). This is almost
4167 // always a no-op, except when the parameter type is bool. In
4168 // that case, this may extend the argument from 1 bit to 8 bits.
4169 QualType IntegerType = ParamType;
4170 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4171 IntegerType = Enum->getDecl()->getIntegerType();
4172 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4173
Benjamin Kramer85524372012-06-07 15:09:51 +00004174 Converted = TemplateArgument(Context, Value,
4175 Context.getCanonicalType(ParamType));
Richard Smith8ef7b202012-01-18 23:55:52 +00004176 return ArgResult;
4177 }
4178
Richard Smith4f870622011-10-27 22:11:44 +00004179 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4180 if (ArgResult.isInvalid())
4181 return ExprError();
4182 Arg = ArgResult.take();
4183
4184 QualType ArgType = Arg->getType();
4185
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004186 // C++ [temp.arg.nontype]p1:
4187 // A template-argument for a non-type, non-template
4188 // template-parameter shall be one of:
4189 //
4190 // -- an integral constant-expression of integral or enumeration
4191 // type; or
4192 // -- the name of a non-type template-parameter; or
4193 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00004194 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004195 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004196 Diag(Arg->getLocStart(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004197 diag::err_template_arg_not_integral_or_enumeral)
4198 << ArgType << Arg->getSourceRange();
4199 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00004200 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00004201 } else if (!Arg->isValueDependent()) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00004202 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4203 QualType T;
4204
4205 public:
4206 TmplArgICEDiagnoser(QualType T) : T(T) { }
4207
4208 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc,
4209 SourceRange SR) {
4210 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
4211 }
4212 } Diagnoser(ArgType);
4213
4214 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
4215 false).take();
Richard Smith282e7e62012-02-04 09:53:13 +00004216 if (!Arg)
4217 return ExprError();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004218 }
4219
Douglas Gregor02024a92010-03-28 02:42:43 +00004220 // From here on out, all we care about are the unqualified forms
4221 // of the parameter and argument types.
4222 ParamType = ParamType.getUnqualifiedType();
4223 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004224
4225 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00004226 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004227 // Okay: no conversion necessary
John McCalldaa8e4e2010-11-15 09:13:47 +00004228 } else if (ParamType->isBooleanType()) {
4229 // This is an integral-to-boolean conversion.
John Wiegley429bb272011-04-08 18:41:53 +00004230 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004231 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
4232 !ParamType->isEnumeralType()) {
4233 // This is an integral promotion or conversion.
John Wiegley429bb272011-04-08 18:41:53 +00004234 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004235 } else {
4236 // We can't perform this conversion.
Daniel Dunbar96a00142012-03-09 18:35:03 +00004237 Diag(Arg->getLocStart(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004238 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00004239 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004240 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00004241 return ExprError();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004242 }
4243
Douglas Gregorc7469372011-05-04 21:55:00 +00004244 // Add the value of this argument to the list of converted
4245 // arguments. We use the bitwidth and signedness of the template
4246 // parameter.
4247 if (Arg->isValueDependent()) {
4248 // The argument is value-dependent. Create a new
4249 // TemplateArgument with the converted expression.
4250 Converted = TemplateArgument(Arg);
4251 return Owned(Arg);
4252 }
4253
Douglas Gregorf80a9d52009-03-14 00:20:21 +00004254 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00004255 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00004256 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00004257
Douglas Gregorc7469372011-05-04 21:55:00 +00004258 if (ParamType->isBooleanType()) {
4259 // Value must be zero or one.
4260 Value = Value != 0;
4261 unsigned AllowedBits = Context.getTypeSize(IntegerType);
4262 if (Value.getBitWidth() != AllowedBits)
4263 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor575a1c92011-05-20 16:38:50 +00004264 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorc7469372011-05-04 21:55:00 +00004265 } else {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00004266 llvm::APSInt OldValue = Value;
Douglas Gregorc7469372011-05-04 21:55:00 +00004267
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004268 // Coerce the template argument's value to the value it will have
Douglas Gregor1a6e0342010-03-26 02:38:37 +00004269 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00004270 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00004271 if (Value.getBitWidth() != AllowedBits)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004272 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor575a1c92011-05-20 16:38:50 +00004273 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorc7469372011-05-04 21:55:00 +00004274
Douglas Gregor1a6e0342010-03-26 02:38:37 +00004275 // Complain if an unsigned parameter received a negative value.
Douglas Gregor575a1c92011-05-20 16:38:50 +00004276 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorc7469372011-05-04 21:55:00 +00004277 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004278 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregor1a6e0342010-03-26 02:38:37 +00004279 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4280 << Arg->getSourceRange();
4281 Diag(Param->getLocation(), diag::note_template_param_here);
4282 }
Douglas Gregorc7469372011-05-04 21:55:00 +00004283
Douglas Gregor1a6e0342010-03-26 02:38:37 +00004284 // Complain if we overflowed the template parameter's type.
4285 unsigned RequiredBits;
Douglas Gregor575a1c92011-05-20 16:38:50 +00004286 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregor1a6e0342010-03-26 02:38:37 +00004287 RequiredBits = OldValue.getActiveBits();
4288 else if (OldValue.isUnsigned())
4289 RequiredBits = OldValue.getActiveBits() + 1;
4290 else
4291 RequiredBits = OldValue.getMinSignedBits();
4292 if (RequiredBits > AllowedBits) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004293 Diag(Arg->getLocStart(),
Douglas Gregor1a6e0342010-03-26 02:38:37 +00004294 diag::warn_template_arg_too_large)
4295 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4296 << Arg->getSourceRange();
4297 Diag(Param->getLocation(), diag::note_template_param_here);
4298 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00004299 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00004300
Benjamin Kramer85524372012-06-07 15:09:51 +00004301 Converted = TemplateArgument(Context, Value,
Douglas Gregor6b63f552011-08-09 01:55:14 +00004302 ParamType->isEnumeralType()
4303 ? Context.getCanonicalType(ParamType)
4304 : IntegerType);
John Wiegley429bb272011-04-08 18:41:53 +00004305 return Owned(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004306 }
Douglas Gregora35284b2009-02-11 00:19:33 +00004307
Richard Smith4f870622011-10-27 22:11:44 +00004308 QualType ArgType = Arg->getType();
John McCall6bb80172010-03-30 21:47:33 +00004309 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
4310
Douglas Gregorb86b0572009-02-11 01:18:59 +00004311 // Handle pointer-to-function, reference-to-function, and
4312 // pointer-to-member-function all in (roughly) the same way.
4313 if (// -- For a non-type template-parameter of type pointer to
4314 // function, only the function-to-pointer conversion (4.3) is
4315 // applied. If the template-argument represents a set of
4316 // overloaded functions (or a pointer to such), the matching
4317 // function is selected from the set (13.4).
4318 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004319 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00004320 // -- For a non-type template-parameter of type reference to
4321 // function, no conversions apply. If the template-argument
4322 // represents a set of overloaded functions, the matching
4323 // function is selected from the set (13.4).
4324 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004325 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00004326 // -- For a non-type template-parameter of type pointer to
4327 // member function, no conversions apply. If the
4328 // template-argument represents a set of overloaded member
4329 // functions, the matching member function is selected from
4330 // the set (13.4).
4331 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004332 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00004333 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00004334
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004335 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004336 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004337 true,
4338 FoundResult)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004339 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley429bb272011-04-08 18:41:53 +00004340 return ExprError();
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004341
4342 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4343 ArgType = Arg->getType();
4344 } else
John Wiegley429bb272011-04-08 18:41:53 +00004345 return ExprError();
Douglas Gregora35284b2009-02-11 00:19:33 +00004346 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004347
John Wiegley429bb272011-04-08 18:41:53 +00004348 if (!ParamType->isMemberPointerType()) {
4349 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4350 ParamType,
4351 Arg, Converted))
4352 return ExprError();
4353 return Owned(Arg);
4354 }
Douglas Gregorb7a09262010-04-01 18:32:35 +00004355
Douglas Gregor42963612012-04-10 17:08:25 +00004356 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
4357 Converted))
John Wiegley429bb272011-04-08 18:41:53 +00004358 return ExprError();
4359 return Owned(Arg);
Douglas Gregora35284b2009-02-11 00:19:33 +00004360 }
4361
Chris Lattnerfe90de72009-02-20 21:37:53 +00004362 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00004363 // -- for a non-type template-parameter of type pointer to
4364 // object, qualification conversions (4.4) and the
4365 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004366 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00004367 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00004368 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00004369
John Wiegley429bb272011-04-08 18:41:53 +00004370 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4371 ParamType,
4372 Arg, Converted))
4373 return ExprError();
4374 return Owned(Arg);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00004375 }
Mike Stump1eb44332009-09-09 15:08:12 +00004376
Ted Kremenek6217b802009-07-29 21:53:49 +00004377 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00004378 // -- For a non-type template-parameter of type reference to
4379 // object, no conversions apply. The type referred to by the
4380 // reference may be more cv-qualified than the (otherwise
4381 // identical) type of the template-argument. The
4382 // template-parameter is bound directly to the
4383 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00004384 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00004385 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00004386
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004387 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004388 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
4389 ParamRefType->getPointeeType(),
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004390 true,
4391 FoundResult)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004392 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley429bb272011-04-08 18:41:53 +00004393 return ExprError();
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004394
4395 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4396 ArgType = Arg->getType();
4397 } else
John Wiegley429bb272011-04-08 18:41:53 +00004398 return ExprError();
Douglas Gregorb86b0572009-02-11 01:18:59 +00004399 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004400
John Wiegley429bb272011-04-08 18:41:53 +00004401 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4402 ParamType,
4403 Arg, Converted))
4404 return ExprError();
4405 return Owned(Arg);
Douglas Gregorb86b0572009-02-11 01:18:59 +00004406 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00004407
Douglas Gregor42963612012-04-10 17:08:25 +00004408 // Deal with parameters of type std::nullptr_t.
4409 if (ParamType->isNullPtrType()) {
4410 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4411 Converted = TemplateArgument(Arg);
4412 return Owned(Arg);
4413 }
4414
4415 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
4416 case NPV_NotNullPointer:
4417 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
4418 << Arg->getType() << ParamType;
4419 Diag(Param->getLocation(), diag::note_template_param_here);
4420 return ExprError();
4421
4422 case NPV_Error:
4423 return ExprError();
4424
4425 case NPV_NullPointer:
Richard Smith86e6fdc2012-04-26 01:51:03 +00004426 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Eli Friedmand7a6b162012-09-26 02:36:12 +00004427 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004428 return Owned(Arg);
Douglas Gregor42963612012-04-10 17:08:25 +00004429 }
4430 }
4431
Douglas Gregor658bbb52009-02-11 16:16:59 +00004432 // -- For a non-type template-parameter of type pointer to data
4433 // member, qualification conversions (4.4) are applied.
4434 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
4435
Douglas Gregor42963612012-04-10 17:08:25 +00004436 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
4437 Converted))
John Wiegley429bb272011-04-08 18:41:53 +00004438 return ExprError();
4439 return Owned(Arg);
Douglas Gregorc15cb382009-02-09 23:23:08 +00004440}
4441
4442/// \brief Check a template argument against its corresponding
4443/// template template parameter.
4444///
4445/// This routine implements the semantics of C++ [temp.arg.template].
4446/// It returns true if an error occurred, and false otherwise.
4447bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Richard Smith6964b3f2012-09-07 02:06:42 +00004448 const TemplateArgumentLoc &Arg,
4449 unsigned ArgumentPackIndex) {
Eli Friedmand7a6b162012-09-26 02:36:12 +00004450 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor788cd062009-11-11 01:00:40 +00004451 TemplateDecl *Template = Name.getAsTemplateDecl();
4452 if (!Template) {
4453 // Any dependent template name is fine.
4454 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
4455 return false;
4456 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00004457
Richard Smith3e4c6c42011-05-05 21:57:07 +00004458 // C++0x [temp.arg.template]p1:
Douglas Gregordd0574e2009-02-10 00:24:35 +00004459 // A template-argument for a template template-parameter shall be
Richard Smith3e4c6c42011-05-05 21:57:07 +00004460 // the name of a class template or an alias template, expressed as an
4461 // id-expression. When the template-argument names a class template, only
Douglas Gregordd0574e2009-02-10 00:24:35 +00004462 // primary class templates are considered when matching the
4463 // template template argument with the corresponding parameter;
4464 // partial specializations are not considered even if their
4465 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004466 //
4467 // Note that we also allow template template parameters here, which
4468 // will happen when we are dealing with, e.g., class template
4469 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00004470 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3e4c6c42011-05-05 21:57:07 +00004471 !isa<TemplateTemplateParmDecl>(Template) &&
4472 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004473 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00004474 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00004475 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00004476 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00004477 << Template;
4478 }
4479
Richard Smith6964b3f2012-09-07 02:06:42 +00004480 TemplateParameterList *Params = Param->getTemplateParameters();
4481 if (Param->isExpandedParameterPack())
4482 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
4483
Douglas Gregordd0574e2009-02-10 00:24:35 +00004484 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith6964b3f2012-09-07 02:06:42 +00004485 Params,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004486 true,
Douglas Gregorfb898e12009-11-12 16:20:59 +00004487 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00004488 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00004489}
4490
Douglas Gregor02024a92010-03-28 02:42:43 +00004491/// \brief Given a non-type template argument that refers to a
4492/// declaration and the type of its corresponding non-type template
4493/// parameter, produce an expression that properly refers to that
4494/// declaration.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004495ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00004496Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
4497 QualType ParamType,
4498 SourceLocation Loc) {
Douglas Gregord2008e22012-04-06 22:40:38 +00004499 // For a NULL non-type template argument, return nullptr casted to the
4500 // parameter's type.
Eli Friedmand7a6b162012-09-26 02:36:12 +00004501 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregord2008e22012-04-06 22:40:38 +00004502 return ImpCastExprToType(
4503 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
4504 ParamType,
4505 ParamType->getAs<MemberPointerType>()
4506 ? CK_NullToMemberPointer
4507 : CK_NullToPointer);
4508 }
Eli Friedmand7a6b162012-09-26 02:36:12 +00004509 assert(Arg.getKind() == TemplateArgument::Declaration &&
4510 "Only declaration template arguments permitted here");
4511
Douglas Gregor02024a92010-03-28 02:42:43 +00004512 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
4513
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004514 if (VD->getDeclContext()->isRecord() &&
Douglas Gregor02024a92010-03-28 02:42:43 +00004515 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
4516 // If the value is a class member, we might have a pointer-to-member.
4517 // Determine whether the non-type template template parameter is of
4518 // pointer-to-member type. If so, we need to build an appropriate
4519 // expression for a pointer-to-member, since a "normal" DeclRefExpr
4520 // would refer to the member itself.
4521 if (ParamType->isMemberPointerType()) {
4522 QualType ClassType
4523 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
4524 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00004525 = NestedNameSpecifier::Create(Context, 0, false,
4526 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00004527 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00004528 SS.MakeTrivial(Context, Qualifier, Loc);
John McCalldfa1edb2010-11-23 20:48:44 +00004529
4530 // The actual value-ness of this is unimportant, but for
4531 // internal consistency's sake, references to instance methods
4532 // are r-values.
4533 ExprValueKind VK = VK_LValue;
4534 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
4535 VK = VK_RValue;
4536
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004537 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCallf89e55a2010-11-18 06:31:45 +00004538 VD->getType().getNonReferenceType(),
John McCalldfa1edb2010-11-23 20:48:44 +00004539 VK,
John McCallf89e55a2010-11-18 06:31:45 +00004540 Loc,
4541 &SS);
Douglas Gregor02024a92010-03-28 02:42:43 +00004542 if (RefExpr.isInvalid())
4543 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004544
John McCall2de56d12010-08-25 11:45:40 +00004545 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004546
Douglas Gregorc0c83002010-04-30 21:46:38 +00004547 // We might need to perform a trailing qualification conversion, since
4548 // the element type on the parameter could be more qualified than the
4549 // element type in the expression we constructed.
John McCallf85e1932011-06-15 23:02:42 +00004550 bool ObjCLifetimeConversion;
Douglas Gregorc0c83002010-04-30 21:46:38 +00004551 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCallf85e1932011-06-15 23:02:42 +00004552 ParamType.getUnqualifiedType(), false,
4553 ObjCLifetimeConversion))
John Wiegley429bb272011-04-08 18:41:53 +00004554 RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004555
Douglas Gregor02024a92010-03-28 02:42:43 +00004556 assert(!RefExpr.isInvalid() &&
4557 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00004558 ParamType.getUnqualifiedType()));
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004559 return RefExpr;
Douglas Gregor02024a92010-03-28 02:42:43 +00004560 }
4561 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004562
Douglas Gregor02024a92010-03-28 02:42:43 +00004563 QualType T = VD->getType().getNonReferenceType();
4564 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00004565 // When the non-type template parameter is a pointer, take the
4566 // address of the declaration.
John McCallf89e55a2010-11-18 06:31:45 +00004567 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00004568 if (RefExpr.isInvalid())
4569 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00004570
4571 if (T->isFunctionType() || T->isArrayType()) {
4572 // Decay functions and arrays.
John Wiegley429bb272011-04-08 18:41:53 +00004573 RefExpr = DefaultFunctionArrayConversion(RefExpr.take());
4574 if (RefExpr.isInvalid())
4575 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00004576
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004577 return RefExpr;
Douglas Gregor02024a92010-03-28 02:42:43 +00004578 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004579
Douglas Gregorb7a09262010-04-01 18:32:35 +00004580 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00004581 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00004582 }
4583
John McCallf89e55a2010-11-18 06:31:45 +00004584 ExprValueKind VK = VK_RValue;
4585
Douglas Gregor02024a92010-03-28 02:42:43 +00004586 // If the non-type template parameter has reference type, qualify the
4587 // resulting declaration reference with the extra qualifiers on the
4588 // type that the reference refers to.
John McCallf89e55a2010-11-18 06:31:45 +00004589 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
4590 VK = VK_LValue;
4591 T = Context.getQualifiedType(T,
4592 TargetRef->getPointeeType().getQualifiers());
4593 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004594
John McCallf89e55a2010-11-18 06:31:45 +00004595 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00004596}
4597
4598/// \brief Construct a new expression that refers to the given
4599/// integral template argument with the given source-location
4600/// information.
4601///
4602/// This routine takes care of the mapping from an integral template
4603/// argument (which may have any integral type) to the appropriate
4604/// literal value.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004605ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00004606Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
4607 SourceLocation Loc) {
4608 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregord3731192011-01-10 07:32:04 +00004609 "Operation is only valid for integral template arguments");
Benjamin Kramer39ad0f02012-11-21 17:42:47 +00004610 QualType OrigT = Arg.getIntegralType();
4611
4612 // If this is an enum type that we're instantiating, we need to use an integer
4613 // type the same size as the enumerator. We don't want to build an
4614 // IntegerLiteral with enum type. The integer type of an enum type can be of
4615 // any integral type with C++11 enum classes, make sure we create the right
4616 // type of literal for it.
4617 QualType T = OrigT;
4618 if (const EnumType *ET = OrigT->getAs<EnumType>())
4619 T = ET->getDecl()->getIntegerType();
4620
4621 Expr *E;
Douglas Gregor5cee1192011-07-27 05:40:30 +00004622 if (T->isAnyCharacterType()) {
4623 CharacterLiteral::CharacterKind Kind;
4624 if (T->isWideCharType())
4625 Kind = CharacterLiteral::Wide;
4626 else if (T->isChar16Type())
4627 Kind = CharacterLiteral::UTF16;
4628 else if (T->isChar32Type())
4629 Kind = CharacterLiteral::UTF32;
4630 else
4631 Kind = CharacterLiteral::Ascii;
4632
Benjamin Kramer39ad0f02012-11-21 17:42:47 +00004633 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
4634 Kind, T, Loc);
4635 } else if (T->isBooleanType()) {
4636 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
4637 T, Loc);
4638 } else if (T->isNullPtrType()) {
4639 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
4640 } else {
4641 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregor5cee1192011-07-27 05:40:30 +00004642 }
4643
Benjamin Kramer39ad0f02012-11-21 17:42:47 +00004644 if (OrigT->isEnumeralType()) {
John McCall4e9272d2011-07-15 07:47:58 +00004645 // FIXME: This is a hack. We need a better way to handle substituted
4646 // non-type template parameters.
Benjamin Kramer39ad0f02012-11-21 17:42:47 +00004647 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E, 0,
4648 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall4e9272d2011-07-15 07:47:58 +00004649 Loc, Loc);
4650 }
4651
4652 return Owned(E);
Douglas Gregor02024a92010-03-28 02:42:43 +00004653}
4654
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004655/// \brief Match two template parameters within template parameter lists.
4656static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
4657 bool Complain,
4658 Sema::TemplateParameterListEqualKind Kind,
4659 SourceLocation TemplateArgLoc) {
4660 // Check the actual kind (type, non-type, template).
4661 if (Old->getKind() != New->getKind()) {
4662 if (Complain) {
4663 unsigned NextDiag = diag::err_template_param_different_kind;
4664 if (TemplateArgLoc.isValid()) {
4665 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4666 NextDiag = diag::note_template_param_different_kind;
4667 }
4668 S.Diag(New->getLocation(), NextDiag)
4669 << (Kind != Sema::TPL_TemplateMatch);
4670 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
4671 << (Kind != Sema::TPL_TemplateMatch);
4672 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004673
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004674 return false;
4675 }
4676
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004677 // Check that both are parameter packs are neither are parameter packs.
4678 // However, if we are matching a template template argument to a
Douglas Gregora0347822011-01-13 00:08:50 +00004679 // template template parameter, the template template parameter can have
4680 // a parameter pack where the template template argument does not.
4681 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
4682 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4683 Old->isTemplateParameterPack())) {
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004684 if (Complain) {
4685 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
4686 if (TemplateArgLoc.isValid()) {
4687 S.Diag(TemplateArgLoc,
4688 diag::err_template_arg_template_params_mismatch);
4689 NextDiag = diag::note_template_parameter_pack_non_pack;
4690 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004691
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004692 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
4693 : isa<NonTypeTemplateParmDecl>(New)? 1
4694 : 2;
4695 S.Diag(New->getLocation(), NextDiag)
4696 << ParamKind << New->isParameterPack();
4697 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
4698 << ParamKind << Old->isParameterPack();
4699 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004700
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004701 return false;
4702 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004703
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004704 // For non-type template parameters, check the type of the parameter.
4705 if (NonTypeTemplateParmDecl *OldNTTP
4706 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
4707 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004708
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004709 // If we are matching a template template argument to a template
4710 // template parameter and one of the non-type template parameter types
4711 // is dependent, then we must wait until template instantiation time
4712 // to actually compare the arguments.
4713 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4714 (OldNTTP->getType()->isDependentType() ||
4715 NewNTTP->getType()->isDependentType()))
4716 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004717
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004718 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
4719 if (Complain) {
4720 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
4721 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004722 S.Diag(TemplateArgLoc,
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004723 diag::err_template_arg_template_params_mismatch);
4724 NextDiag = diag::note_template_nontype_parm_different_type;
4725 }
4726 S.Diag(NewNTTP->getLocation(), NextDiag)
4727 << NewNTTP->getType()
4728 << (Kind != Sema::TPL_TemplateMatch);
4729 S.Diag(OldNTTP->getLocation(),
4730 diag::note_template_nontype_parm_prev_declaration)
4731 << OldNTTP->getType();
4732 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004733
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004734 return false;
4735 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004736
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004737 return true;
4738 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004739
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004740 // For template template parameters, check the template parameter types.
4741 // The template parameter lists of template template
4742 // parameters must agree.
4743 if (TemplateTemplateParmDecl *OldTTP
4744 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004745 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004746 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
4747 OldTTP->getTemplateParameters(),
4748 Complain,
4749 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004750 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004751 : Kind),
4752 TemplateArgLoc);
4753 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004754
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004755 return true;
4756}
Douglas Gregor02024a92010-03-28 02:42:43 +00004757
Douglas Gregora0347822011-01-13 00:08:50 +00004758/// \brief Diagnose a known arity mismatch when comparing template argument
4759/// lists.
4760static
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004761void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregora0347822011-01-13 00:08:50 +00004762 TemplateParameterList *New,
4763 TemplateParameterList *Old,
4764 Sema::TemplateParameterListEqualKind Kind,
4765 SourceLocation TemplateArgLoc) {
4766 unsigned NextDiag = diag::err_template_param_list_different_arity;
4767 if (TemplateArgLoc.isValid()) {
4768 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4769 NextDiag = diag::note_template_param_list_different_arity;
4770 }
4771 S.Diag(New->getTemplateLoc(), NextDiag)
4772 << (New->size() > Old->size())
4773 << (Kind != Sema::TPL_TemplateMatch)
4774 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
4775 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
4776 << (Kind != Sema::TPL_TemplateMatch)
4777 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
4778}
4779
Douglas Gregorddc29e12009-02-06 22:42:48 +00004780/// \brief Determine whether the given template parameter lists are
4781/// equivalent.
4782///
Mike Stump1eb44332009-09-09 15:08:12 +00004783/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00004784/// source code as part of a new template declaration.
4785///
4786/// \param Old The old template parameter list, typically found via
4787/// name lookup of the template declared with this template parameter
4788/// list.
4789///
4790/// \param Complain If true, this routine will produce a diagnostic if
4791/// the template parameter lists are not equivalent.
4792///
Douglas Gregorfb898e12009-11-12 16:20:59 +00004793/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00004794///
4795/// \param TemplateArgLoc If this source location is valid, then we
4796/// are actually checking the template parameter list of a template
4797/// argument (New) against the template parameter list of its
4798/// corresponding template template parameter (Old). We produce
4799/// slightly different diagnostics in this scenario.
4800///
Douglas Gregorddc29e12009-02-06 22:42:48 +00004801/// \returns True if the template parameter lists are equal, false
4802/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00004803bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00004804Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
4805 TemplateParameterList *Old,
4806 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00004807 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00004808 SourceLocation TemplateArgLoc) {
Douglas Gregora0347822011-01-13 00:08:50 +00004809 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
4810 if (Complain)
4811 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4812 TemplateArgLoc);
Douglas Gregorddc29e12009-02-06 22:42:48 +00004813
4814 return false;
4815 }
4816
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004817 // C++0x [temp.arg.template]p3:
4818 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004819 // when each of the template parameters in the template-parameter-list of
Richard Smith3e4c6c42011-05-05 21:57:07 +00004820 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004821 // (call it A) matches the corresponding template parameter in the
Douglas Gregora0347822011-01-13 00:08:50 +00004822 // template-parameter-list of P. [...]
4823 TemplateParameterList::iterator NewParm = New->begin();
4824 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorddc29e12009-02-06 22:42:48 +00004825 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregora0347822011-01-13 00:08:50 +00004826 OldParmEnd = Old->end();
4827 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregorc421f542011-01-13 18:47:47 +00004828 if (Kind != TPL_TemplateTemplateArgumentMatch ||
4829 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregora0347822011-01-13 00:08:50 +00004830 if (NewParm == NewParmEnd) {
4831 if (Complain)
4832 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4833 TemplateArgLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004834
Douglas Gregora0347822011-01-13 00:08:50 +00004835 return false;
4836 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004837
Douglas Gregora0347822011-01-13 00:08:50 +00004838 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4839 Kind, TemplateArgLoc))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004840 return false;
4841
Douglas Gregora0347822011-01-13 00:08:50 +00004842 ++NewParm;
4843 continue;
4844 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004845
Douglas Gregora0347822011-01-13 00:08:50 +00004846 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004847 // [...] When P's template- parameter-list contains a template parameter
4848 // pack (14.5.3), the template parameter pack will match zero or more
4849 // template parameters or template parameter packs in the
Douglas Gregora0347822011-01-13 00:08:50 +00004850 // template-parameter-list of A with the same type and form as the
4851 // template parameter pack in P (ignoring whether those template
4852 // parameters are template parameter packs).
4853 for (; NewParm != NewParmEnd; ++NewParm) {
4854 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4855 Kind, TemplateArgLoc))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004856 return false;
Douglas Gregora0347822011-01-13 00:08:50 +00004857 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00004858 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004859
Douglas Gregora0347822011-01-13 00:08:50 +00004860 // Make sure we exhausted all of the arguments.
4861 if (NewParm != NewParmEnd) {
4862 if (Complain)
4863 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4864 TemplateArgLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004865
Douglas Gregora0347822011-01-13 00:08:50 +00004866 return false;
4867 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004868
Douglas Gregorddc29e12009-02-06 22:42:48 +00004869 return true;
4870}
4871
4872/// \brief Check whether a template can be declared within this scope.
4873///
4874/// If the template declaration is valid in this scope, returns
4875/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00004876bool
Douglas Gregor05396e22009-08-25 17:23:04 +00004877Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorfb35e8f2011-11-03 16:37:14 +00004878 if (!S)
4879 return false;
4880
Douglas Gregorddc29e12009-02-06 22:42:48 +00004881 // Find the nearest enclosing declaration scope.
4882 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4883 (S->getFlags() & Scope::TemplateParamScope) != 0)
4884 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004885
Douglas Gregorddc29e12009-02-06 22:42:48 +00004886 // C++ [temp]p2:
4887 // A template-declaration can appear only as a namespace scope or
4888 // class scope declaration.
4889 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00004890 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
4891 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00004892 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00004893 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004894
Eli Friedman1503f772009-07-31 01:43:05 +00004895 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00004896 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00004897
4898 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
4899 return false;
4900
Mike Stump1eb44332009-09-09 15:08:12 +00004901 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004902 diag::err_template_outside_namespace_or_class_scope)
4903 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00004904}
Douglas Gregorcc636682009-02-17 23:15:12 +00004905
Douglas Gregord5cb8762009-10-07 00:13:32 +00004906/// \brief Determine what kind of template specialization the given declaration
4907/// is.
Douglas Gregorf785a7d2012-01-14 15:55:47 +00004908static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004909 if (!D)
4910 return TSK_Undeclared;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004911
Douglas Gregorf6b11852009-10-08 15:14:33 +00004912 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
4913 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00004914 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
4915 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004916 if (VarDecl *Var = dyn_cast<VarDecl>(D))
4917 return Var->getTemplateSpecializationKind();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004918
Douglas Gregord5cb8762009-10-07 00:13:32 +00004919 return TSK_Undeclared;
4920}
4921
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004922/// \brief Check whether a specialization is well-formed in the current
Douglas Gregor9302da62009-10-14 23:50:59 +00004923/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00004924///
Douglas Gregor9302da62009-10-14 23:50:59 +00004925/// This routine determines whether a template specialization can be declared
4926/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00004927///
4928/// \param S the semantic analysis object for which this check is being
4929/// performed.
4930///
4931/// \param Specialized the entity being specialized or instantiated, which
4932/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004933/// a member of a class template (member function, static data member,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004934/// member class).
4935///
4936/// \param PrevDecl the previous declaration of this entity, if any.
4937///
4938/// \param Loc the location of the explicit specialization or instantiation of
4939/// this entity.
4940///
4941/// \param IsPartialSpecialization whether this is a partial specialization of
4942/// a class template.
4943///
Douglas Gregord5cb8762009-10-07 00:13:32 +00004944/// \returns true if there was an error that we cannot recover from, false
4945/// otherwise.
4946static bool CheckTemplateSpecializationScope(Sema &S,
4947 NamedDecl *Specialized,
4948 NamedDecl *PrevDecl,
4949 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00004950 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004951 // Keep these "kind" numbers in sync with the %select statements in the
4952 // various diagnostics emitted by this routine.
4953 int EntityKind = 0;
Ted Kremenekfe62b062011-01-14 22:31:36 +00004954 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004955 EntityKind = IsPartialSpecialization? 1 : 0;
Ted Kremenekfe62b062011-01-14 22:31:36 +00004956 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004957 EntityKind = 2;
Ted Kremenekfe62b062011-01-14 22:31:36 +00004958 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004959 EntityKind = 3;
4960 else if (isa<VarDecl>(Specialized))
4961 EntityKind = 4;
4962 else if (isa<RecordDecl>(Specialized))
4963 EntityKind = 5;
Richard Smith1af83c42012-03-23 03:33:32 +00004964 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus0x)
4965 EntityKind = 6;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004966 else {
Richard Smith1af83c42012-03-23 03:33:32 +00004967 S.Diag(Loc, diag::err_template_spec_unknown_kind)
4968 << S.getLangOpts().CPlusPlus0x;
Douglas Gregor9302da62009-10-14 23:50:59 +00004969 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00004970 return true;
4971 }
4972
Douglas Gregor88b70942009-02-25 22:02:03 +00004973 // C++ [temp.expl.spec]p2:
4974 // An explicit specialization shall be declared in the namespace
4975 // of which the template is a member, or, for member templates, in
4976 // the namespace of which the enclosing class or enclosing class
4977 // template is a member. An explicit specialization of a member
4978 // function, member class or static data member of a class
4979 // template shall be declared in the namespace of which the class
4980 // template is a member. Such a declaration may also be a
4981 // definition. If the declaration is not a definition, the
4982 // specialization may be defined later in the name- space in which
4983 // the explicit specialization was declared, or in a namespace
4984 // that encloses the one in which the explicit specialization was
4985 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004986 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004987 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00004988 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00004989 return true;
4990 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004991
Douglas Gregor0a407472009-10-07 17:30:37 +00004992 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004993 if (S.getLangOpts().MicrosoftExt) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004994 // Do not warn for class scope explicit specialization during
4995 // instantiation, warning was already emitted during pattern
4996 // semantic analysis.
4997 if (!S.ActiveTemplateInstantiations.size())
4998 S.Diag(Loc, diag::ext_function_specialization_in_class)
4999 << Specialized;
5000 } else {
5001 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5002 << Specialized;
5003 return true;
5004 }
Douglas Gregor0a407472009-10-07 17:30:37 +00005005 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005006
Douglas Gregor8e0c1182011-10-20 16:41:18 +00005007 if (S.CurContext->isRecord() &&
5008 !S.CurContext->Equals(Specialized->getDeclContext())) {
5009 // Make sure that we're specializing in the right record context.
5010 // Otherwise, things can go horribly wrong.
5011 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5012 << Specialized;
5013 return true;
5014 }
5015
Douglas Gregor7974c3b2009-10-07 17:21:34 +00005016 // C++ [temp.class.spec]p6:
5017 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005018 // in any namespace scope in which its definition may be defined (14.5.1
5019 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00005020 bool ComplainedAboutScope = false;
Douglas Gregor8e0c1182011-10-20 16:41:18 +00005021 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00005022 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00005023 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005024 if ((!PrevDecl ||
Douglas Gregor9302da62009-10-14 23:50:59 +00005025 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5026 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00005027 // C++ [temp.exp.spec]p2:
5028 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005029 // the template is a member, or, for member templates, in the namespace
Douglas Gregor121dc9a2010-09-12 05:08:28 +00005030 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005031 // An explicit specialization of a member function, member class or
5032 // static data member of a class template shall be declared in the
Douglas Gregor121dc9a2010-09-12 05:08:28 +00005033 // namespace of which the class template is a member.
5034 //
5035 // C++0x [temp.expl.spec]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005036 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregor121dc9a2010-09-12 05:08:28 +00005037 // the specialized template.
Richard Smithebaf0e62011-10-18 20:49:44 +00005038 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5039 bool IsCPlusPlus0xExtension = DC->Encloses(SpecializedContext);
5040 if (isa<TranslationUnitDecl>(SpecializedContext)) {
5041 assert(!IsCPlusPlus0xExtension &&
5042 "DC encloses TU but isn't in enclosing namespace set");
5043 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregora4d5de52010-09-12 05:24:55 +00005044 << EntityKind << Specialized;
Richard Smithebaf0e62011-10-18 20:49:44 +00005045 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5046 int Diag;
5047 if (!IsCPlusPlus0xExtension)
5048 Diag = diag::err_template_spec_decl_out_of_scope;
David Blaikie4e4d0842012-03-11 07:00:24 +00005049 else if (!S.getLangOpts().CPlusPlus0x)
Richard Smithebaf0e62011-10-18 20:49:44 +00005050 Diag = diag::ext_template_spec_decl_out_of_scope;
5051 else
5052 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5053 S.Diag(Loc, Diag)
5054 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5055 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005056
Douglas Gregor9302da62009-10-14 23:50:59 +00005057 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Richard Smithebaf0e62011-10-18 20:49:44 +00005058 ComplainedAboutScope =
David Blaikie4e4d0842012-03-11 07:00:24 +00005059 !(IsCPlusPlus0xExtension && S.getLangOpts().CPlusPlus0x);
Douglas Gregor88b70942009-02-25 22:02:03 +00005060 }
Douglas Gregor88b70942009-02-25 22:02:03 +00005061 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005062
5063 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00005064 // namespace.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005065 // Note that HandleDeclarator() performs this check for explicit
Douglas Gregord5cb8762009-10-07 00:13:32 +00005066 // specializations of function templates, static data members, and member
5067 // functions, so we skip the check here for those kinds of entities.
5068 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00005069 // Should we refactor that check, so that it occurs later?
5070 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00005071 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
5072 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00005073 if (isa<TranslationUnitDecl>(SpecializedContext))
5074 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5075 << EntityKind << Specialized;
5076 else if (isa<NamespaceDecl>(SpecializedContext))
5077 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
5078 << EntityKind << Specialized
5079 << cast<NamedDecl>(SpecializedContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005080
Douglas Gregor9302da62009-10-14 23:50:59 +00005081 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00005082 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005083
Douglas Gregord5cb8762009-10-07 00:13:32 +00005084 // FIXME: check for specialization-after-instantiation errors and such.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005085
Douglas Gregor88b70942009-02-25 22:02:03 +00005086 return false;
5087}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005088
Douglas Gregorbacb9492011-01-03 21:13:47 +00005089/// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
5090/// that checks non-type template partial specialization arguments.
5091static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
5092 NonTypeTemplateParmDecl *Param,
5093 const TemplateArgument *Args,
5094 unsigned NumArgs) {
5095 for (unsigned I = 0; I != NumArgs; ++I) {
5096 if (Args[I].getKind() == TemplateArgument::Pack) {
5097 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005098 Args[I].pack_begin(),
Douglas Gregorbacb9492011-01-03 21:13:47 +00005099 Args[I].pack_size()))
5100 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005101
Douglas Gregore94866f2009-06-12 21:21:02 +00005102 continue;
Douglas Gregorbacb9492011-01-03 21:13:47 +00005103 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005104
Eli Friedmand7a6b162012-09-26 02:36:12 +00005105 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregore94866f2009-06-12 21:21:02 +00005106 continue;
Eli Friedmand7a6b162012-09-26 02:36:12 +00005107
5108 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregore94866f2009-06-12 21:21:02 +00005109
Douglas Gregor7a21fd42011-01-03 21:37:45 +00005110 // We can have a pack expansion of any of the bullets below.
Douglas Gregorbacb9492011-01-03 21:13:47 +00005111 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5112 ArgExpr = Expansion->getPattern();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00005113
5114 // Strip off any implicit casts we added as part of type checking.
5115 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5116 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005117
Douglas Gregore94866f2009-06-12 21:21:02 +00005118 // C++ [temp.class.spec]p8:
5119 // A non-type argument is non-specialized if it is the name of a
5120 // non-type parameter. All other non-type arguments are
5121 // specialized.
5122 //
5123 // Below, we check the two conditions that only apply to
5124 // specialized non-type arguments, so skip any non-specialized
5125 // arguments.
5126 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00005127 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregore94866f2009-06-12 21:21:02 +00005128 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005129
Douglas Gregore94866f2009-06-12 21:21:02 +00005130 // C++ [temp.class.spec]p9:
5131 // Within the argument list of a class template partial
5132 // specialization, the following restrictions apply:
5133 // -- A partially specialized non-type argument expression
5134 // shall not involve a template parameter of the partial
5135 // specialization except when the argument expression is a
5136 // simple identifier.
5137 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00005138 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00005139 diag::err_dependent_non_type_arg_in_partial_spec)
5140 << ArgExpr->getSourceRange();
5141 return true;
5142 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005143
Douglas Gregore94866f2009-06-12 21:21:02 +00005144 // -- The type of a template parameter corresponding to a
5145 // specialized non-type argument shall not be dependent on a
5146 // parameter of the specialization.
5147 if (Param->getType()->isDependentType()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00005148 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00005149 diag::err_dependent_typed_non_type_arg_in_partial_spec)
5150 << Param->getType()
5151 << ArgExpr->getSourceRange();
Douglas Gregorbacb9492011-01-03 21:13:47 +00005152 S.Diag(Param->getLocation(), diag::note_template_param_here);
Douglas Gregore94866f2009-06-12 21:21:02 +00005153 return true;
5154 }
5155 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005156
Douglas Gregorbacb9492011-01-03 21:13:47 +00005157 return false;
5158}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005159
Douglas Gregorbacb9492011-01-03 21:13:47 +00005160/// \brief Check the non-type template arguments of a class template
5161/// partial specialization according to C++ [temp.class.spec]p9.
5162///
5163/// \param TemplateParams the template parameters of the primary class
5164/// template.
5165///
James Dennett1dfbd922012-06-14 21:40:34 +00005166/// \param TemplateArgs the template arguments of the class template
Douglas Gregorbacb9492011-01-03 21:13:47 +00005167/// partial specialization.
5168///
5169/// \returns true if there was an error, false otherwise.
5170static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
5171 TemplateParameterList *TemplateParams,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005172 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00005173 const TemplateArgument *ArgList = TemplateArgs.data();
5174
5175 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5176 NonTypeTemplateParmDecl *Param
5177 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
5178 if (!Param)
5179 continue;
5180
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005181 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
Douglas Gregorbacb9492011-01-03 21:13:47 +00005182 &ArgList[I], 1))
5183 return true;
5184 }
Douglas Gregore94866f2009-06-12 21:21:02 +00005185
5186 return false;
5187}
5188
John McCalld226f652010-08-21 09:40:31 +00005189DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00005190Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
5191 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00005192 SourceLocation KWLoc,
Douglas Gregord023aec2011-09-09 20:53:38 +00005193 SourceLocation ModulePrivateLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005194 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00005195 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00005196 SourceLocation TemplateNameLoc,
5197 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00005198 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00005199 SourceLocation RAngleLoc,
5200 AttributeList *Attr,
5201 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005202 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00005203
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005204 // NOTE: KWLoc is the location of the tag keyword. This will instead
5205 // store the location of the outermost template keyword in the declaration.
5206 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005207 ? TemplateParameterLists[0]->getTemplateLoc() : SourceLocation();
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005208
Douglas Gregorcc636682009-02-17 23:15:12 +00005209 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00005210 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00005211 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00005212 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
5213
5214 if (!ClassTemplate) {
5215 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005216 << (Name.getAsTemplateDecl() &&
Douglas Gregor8b13c082009-11-12 00:46:20 +00005217 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
5218 return true;
5219 }
Douglas Gregorcc636682009-02-17 23:15:12 +00005220
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005221 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005222 bool isPartialSpecialization = false;
5223
Douglas Gregor88b70942009-02-25 22:02:03 +00005224 // Check the validity of the template headers that introduce this
5225 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005226 // FIXME: We probably shouldn't complain about these headers for
5227 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005228 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00005229 TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00005230 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc,
5231 TemplateNameLoc,
5232 SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +00005233 TemplateParameterLists.data(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005234 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00005235 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005236 isExplicitSpecialization,
5237 Invalid);
5238 if (Invalid)
5239 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005240
Douglas Gregor05396e22009-08-25 17:23:04 +00005241 if (TemplateParams && TemplateParams->size() > 0) {
5242 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00005243
Douglas Gregorb0ee93c2010-12-21 08:14:57 +00005244 if (TUK == TUK_Friend) {
5245 Diag(KWLoc, diag::err_partial_specialization_friend)
5246 << SourceRange(LAngleLoc, RAngleLoc);
5247 return true;
5248 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005249
Douglas Gregor05396e22009-08-25 17:23:04 +00005250 // C++ [temp.class.spec]p10:
5251 // The template parameter list of a specialization shall not
5252 // contain default template argument values.
5253 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5254 Decl *Param = TemplateParams->getParam(I);
5255 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5256 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005257 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00005258 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00005259 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00005260 }
5261 } else if (NonTypeTemplateParmDecl *NTTP
5262 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5263 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005264 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00005265 diag::err_default_arg_in_partial_spec)
5266 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00005267 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00005268 }
5269 } else {
5270 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00005271 if (TTP->hasDefaultArgument()) {
5272 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00005273 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00005274 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00005275 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00005276 }
5277 }
5278 }
Douglas Gregora735b202009-10-13 14:39:41 +00005279 } else if (TemplateParams) {
5280 if (TUK == TUK_Friend)
5281 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00005282 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00005283 SourceRange(TemplateParams->getTemplateLoc(),
5284 TemplateParams->getRAngleLoc()))
5285 << SourceRange(LAngleLoc, RAngleLoc);
5286 else
5287 isExplicitSpecialization = true;
5288 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00005289 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00005290 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005291 isExplicitSpecialization = true;
5292 }
Douglas Gregor88b70942009-02-25 22:02:03 +00005293
Douglas Gregorcc636682009-02-17 23:15:12 +00005294 // Check that the specialization uses the same tag kind as the
5295 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005296 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5297 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005298 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieubbf34c02011-06-10 03:11:26 +00005299 Kind, TUK == TUK_Definition, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005300 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005301 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00005302 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00005303 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00005304 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00005305 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00005306 diag::note_previous_use);
5307 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5308 }
5309
Douglas Gregor40808ce2009-03-09 23:48:35 +00005310 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00005311 TemplateArgumentListInfo TemplateArgs;
5312 TemplateArgs.setLAngleLoc(LAngleLoc);
5313 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00005314 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00005315
Douglas Gregor925910d2011-01-03 20:35:03 +00005316 // Check for unexpanded parameter packs in any of the template arguments.
5317 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005318 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor925910d2011-01-03 20:35:03 +00005319 UPPC_PartialSpecialization))
5320 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005321
Douglas Gregorcc636682009-02-17 23:15:12 +00005322 // Check that the template argument list is well-formed for this
5323 // template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005324 SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00005325 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5326 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00005327 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00005328
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005329 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00005330 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00005331 if (isPartialSpecialization) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00005332 if (CheckClassTemplatePartialSpecializationArgs(*this,
Douglas Gregore94866f2009-06-12 21:21:02 +00005333 ClassTemplate->getTemplateParameters(),
Douglas Gregorb9c66312010-12-23 17:13:55 +00005334 Converted))
Douglas Gregore94866f2009-06-12 21:21:02 +00005335 return true;
5336
Douglas Gregor561f8122011-07-01 01:22:09 +00005337 bool InstantiationDependent;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005338 if (!Name.isDependent() &&
Douglas Gregorde090962010-02-09 00:37:32 +00005339 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005340 TemplateArgs.getArgumentArray(),
Douglas Gregor561f8122011-07-01 01:22:09 +00005341 TemplateArgs.size(),
5342 InstantiationDependent)) {
Douglas Gregorde090962010-02-09 00:37:32 +00005343 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
5344 << ClassTemplate->getDeclName();
5345 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00005346 }
5347 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005348
Douglas Gregorcc636682009-02-17 23:15:12 +00005349 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005350 ClassTemplateSpecializationDecl *PrevDecl = 0;
5351
5352 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005353 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005354 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005355 = ClassTemplate->findPartialSpecialization(Converted.data(),
5356 Converted.size(),
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005357 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005358 else
5359 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005360 = ClassTemplate->findSpecialization(Converted.data(),
5361 Converted.size(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00005362
5363 ClassTemplateSpecializationDecl *Specialization = 0;
5364
Douglas Gregor88b70942009-02-25 22:02:03 +00005365 // Check whether we can declare a class template specialization in
5366 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005367 if (TUK != TUK_Friend &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005368 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
5369 TemplateNameLoc,
Douglas Gregor9302da62009-10-14 23:50:59 +00005370 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00005371 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005372
Douglas Gregorb88e8882009-07-30 17:40:51 +00005373 // The canonical type
5374 QualType CanonType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005375 if (PrevDecl &&
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005376 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00005377 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00005378 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005379 // arguments was referenced but not declared, or we're only
5380 // referencing this specialization as a friend, reuse that
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005381 // declaration node as our own, updating its source location and
5382 // the list of outer template parameters to reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00005383 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00005384 Specialization->setLocation(TemplateNameLoc);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005385 if (TemplateParameterLists.size() > 0) {
5386 Specialization->setTemplateParameterListsInfo(Context,
5387 TemplateParameterLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00005388 TemplateParameterLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005389 }
Douglas Gregorcc636682009-02-17 23:15:12 +00005390 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00005391 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005392 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00005393 // Build the canonical type that describes the converted template
5394 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00005395 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5396 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb9c66312010-12-23 17:13:55 +00005397 Converted.data(),
5398 Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005399
5400 if (Context.hasSameType(CanonType,
Douglas Gregorb9c66312010-12-23 17:13:55 +00005401 ClassTemplate->getInjectedClassNameSpecialization())) {
5402 // C++ [temp.class.spec]p9b3:
5403 //
5404 // -- The argument list of the specialization shall not be identical
5405 // to the implicit argument list of the primary template.
5406 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Douglas Gregor8d267c52011-09-09 02:06:17 +00005407 << (TUK == TUK_Definition)
5408 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregorb9c66312010-12-23 17:13:55 +00005409 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
5410 ClassTemplate->getIdentifier(),
5411 TemplateNameLoc,
5412 Attr,
5413 TemplateParams,
Douglas Gregore7612302011-09-09 19:05:14 +00005414 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005415 TemplateParameterLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +00005416 TemplateParameterLists.data());
Douglas Gregorb9c66312010-12-23 17:13:55 +00005417 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00005418
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005419 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005420 ClassTemplatePartialSpecializationDecl *PrevPartial
5421 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00005422 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005423 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00005424 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00005425 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005426 ClassTemplate->getDeclContext(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005427 KWLoc, TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00005428 TemplateParams,
5429 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005430 Converted.data(),
5431 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00005432 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00005433 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00005434 PrevPartial,
5435 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00005436 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005437 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00005438 Partial->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005439 TemplateParameterLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +00005440 TemplateParameterLists.data());
Abramo Bagnara9b934882010-06-12 08:15:14 +00005441 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005442
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005443 if (!PrevPartial)
5444 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005445 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00005446
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005447 // If we are providing an explicit specialization of a member class
Douglas Gregored9c0f92009-10-29 00:04:11 +00005448 // template specialization, make a note of that.
5449 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
5450 PrevPartial->setMemberSpecialization();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005451
Douglas Gregor031a5882009-06-13 00:26:55 +00005452 // Check that all of the template parameters of the class template
5453 // partial specialization are deducible from the template
5454 // arguments. If not, this class template partial specialization
5455 // will never be used.
Benjamin Kramer013b3662012-01-30 16:17:39 +00005456 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005457 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00005458 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00005459 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00005460
Benjamin Kramer013b3662012-01-30 16:17:39 +00005461 if (!DeducibleParams.all()) {
5462 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor031a5882009-06-13 00:26:55 +00005463 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
5464 << (NumNonDeducible > 1)
5465 << SourceRange(TemplateNameLoc, RAngleLoc);
5466 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
5467 if (!DeducibleParams[I]) {
5468 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
5469 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00005470 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00005471 diag::note_partial_spec_unused_parameter)
5472 << Param->getDeclName();
5473 else
Mike Stump1eb44332009-09-09 15:08:12 +00005474 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00005475 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00005476 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00005477 }
5478 }
5479 }
Douglas Gregorcc636682009-02-17 23:15:12 +00005480 } else {
5481 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005482 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00005483 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005484 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00005485 ClassTemplate->getDeclContext(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005486 KWLoc, TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005487 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005488 Converted.data(),
5489 Converted.size(),
Douglas Gregorcc636682009-02-17 23:15:12 +00005490 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005491 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005492 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00005493 Specialization->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005494 TemplateParameterLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00005495 TemplateParameterLists.data());
Abramo Bagnara9b934882010-06-12 08:15:14 +00005496 }
Douglas Gregorcc636682009-02-17 23:15:12 +00005497
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005498 if (!PrevDecl)
5499 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00005500
5501 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00005502 }
5503
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005504 // C++ [temp.expl.spec]p6:
5505 // If a template, a member template or the member of a class template is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005506 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005507 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005508 // instantiation to take place, in every translation unit in which such a
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005509 // use occurs; no diagnostic is required.
5510 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005511 bool Okay = false;
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005512 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005513 // Is there any previous explicit specialization declaration?
5514 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5515 Okay = true;
5516 break;
5517 }
5518 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005519
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005520 if (!Okay) {
5521 SourceRange Range(TemplateNameLoc, RAngleLoc);
5522 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
5523 << Context.getTypeDeclType(Specialization) << Range;
5524
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005525 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005526 diag::note_instantiation_required_here)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005527 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005528 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005529 return true;
5530 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005531 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005532
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005533 // If this is not a friend, note that this is an explicit specialization.
5534 if (TUK != TUK_Friend)
5535 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00005536
5537 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00005538 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00005539 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00005540 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005541 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005542 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00005543 Diag(Def->getLocation(), diag::note_previous_definition);
5544 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00005545 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00005546 }
5547 }
5548
John McCall7f1b9872010-12-18 03:30:47 +00005549 if (Attr)
5550 ProcessDeclAttributeList(S, Specialization, Attr);
5551
Richard Smith0652c352012-08-17 03:20:55 +00005552 // Add alignment attributes if necessary; these attributes are checked when
5553 // the ASTContext lays out the structure.
5554 if (TUK == TUK_Definition) {
5555 AddAlignmentAttributesForRecord(Specialization);
5556 AddMsStructLayoutForRecord(Specialization);
5557 }
5558
Douglas Gregord023aec2011-09-09 20:53:38 +00005559 if (ModulePrivateLoc.isValid())
5560 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
5561 << (isPartialSpecialization? 1 : 0)
5562 << FixItHint::CreateRemoval(ModulePrivateLoc);
5563
Douglas Gregorfc705b82009-02-26 22:19:44 +00005564 // Build the fully-sugared type for this class template
5565 // specialization as the user wrote in the specialization
5566 // itself. This means that we'll pretty-print the type retrieved
5567 // from the specialization's declaration the way that the user
5568 // actually wrote the specialization, rather than formatting the
5569 // name based on the "canonical" representation used to store the
5570 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005571 TypeSourceInfo *WrittenTy
5572 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5573 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005574 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005575 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005576 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005577 }
Douglas Gregorcc636682009-02-17 23:15:12 +00005578
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00005579 // C++ [temp.expl.spec]p9:
5580 // A template explicit specialization is in the scope of the
5581 // namespace in which the template was defined.
5582 //
5583 // We actually implement this paragraph where we set the semantic
5584 // context (in the creation of the ClassTemplateSpecializationDecl),
5585 // but we also maintain the lexical context where the actual
5586 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00005587 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005588
Douglas Gregorcc636682009-02-17 23:15:12 +00005589 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00005590 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00005591 Specialization->startDefinition();
5592
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005593 if (TUK == TUK_Friend) {
5594 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
5595 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00005596 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005597 /*FIXME:*/KWLoc);
5598 Friend->setAccess(AS_public);
5599 CurContext->addDecl(Friend);
5600 } else {
5601 // Add the specialization into its lexical context, so that it can
5602 // be seen when iterating through the list of declarations in that
5603 // context. However, specializations are not found by name lookup.
5604 CurContext->addDecl(Specialization);
5605 }
John McCalld226f652010-08-21 09:40:31 +00005606 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00005607}
Douglas Gregord57959a2009-03-27 23:10:48 +00005608
John McCalld226f652010-08-21 09:40:31 +00005609Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00005610 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00005611 Declarator &D) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005612 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko96b09862012-07-31 22:37:06 +00005613 ActOnDocumentableDecl(NewDecl);
5614 return NewDecl;
Douglas Gregore542c862009-06-23 23:11:28 +00005615}
5616
John McCalld226f652010-08-21 09:40:31 +00005617Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00005618 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00005619 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00005620 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005621 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00005622
Douglas Gregor52591bf2009-06-24 00:54:41 +00005623 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00005624 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00005625 }
Mike Stump1eb44332009-09-09 15:08:12 +00005626
Douglas Gregor52591bf2009-06-24 00:54:41 +00005627 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00005628
Douglas Gregor45fa5602011-11-07 20:56:01 +00005629 D.setFunctionDefinitionKind(FDK_Definition);
John McCalld226f652010-08-21 09:40:31 +00005630 Decl *DP = HandleDeclarator(ParentScope, D,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005631 TemplateParameterLists);
Mike Stump1eb44332009-09-09 15:08:12 +00005632 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00005633 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00005634 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00005635 FunctionTemplate->getTemplatedDecl());
5636 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
5637 return ActOnStartOfFunctionDef(FnBodyScope, Function);
5638 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00005639}
5640
John McCall75042392010-02-11 01:33:53 +00005641/// \brief Strips various properties off an implicit instantiation
5642/// that has just been explicitly specialized.
5643static void StripImplicitInstantiation(NamedDecl *D) {
Rafael Espindola860097c2012-02-23 04:17:32 +00005644 // FIXME: "make check" is clean if the call to dropAttrs() is commented out.
Sean Huntcf807c42010-08-18 23:23:40 +00005645 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00005646
5647 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5648 FD->setInlineSpecified(false);
5649 }
5650}
5651
Nico Weberd1d512a2012-01-09 19:52:25 +00005652/// \brief Compute the diagnostic location for an explicit instantiation
5653// declaration or definition.
5654static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005655 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Weberd1d512a2012-01-09 19:52:25 +00005656 // Explicit instantiations following a specialization have no effect and
5657 // hence no PointOfInstantiation. In that case, walk decl backwards
5658 // until a valid name loc is found.
5659 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005660 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
5661 Prev = Prev->getPreviousDecl()) {
Nico Weberd1d512a2012-01-09 19:52:25 +00005662 PrevDiagLoc = Prev->getLocation();
5663 }
5664 assert(PrevDiagLoc.isValid() &&
5665 "Explicit instantiation without point of instantiation?");
5666 return PrevDiagLoc;
5667}
5668
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005669/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregor454885e2009-10-15 15:54:05 +00005670/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005671/// for those cases where they are required and determining whether the
Douglas Gregor454885e2009-10-15 15:54:05 +00005672/// new specialization/instantiation will have any effect.
5673///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005674/// \param NewLoc the location of the new explicit specialization or
Douglas Gregor454885e2009-10-15 15:54:05 +00005675/// instantiation.
5676///
5677/// \param NewTSK the kind of the new explicit specialization or instantiation.
5678///
5679/// \param PrevDecl the previous declaration of the entity.
5680///
5681/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
5682///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005683/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregor454885e2009-10-15 15:54:05 +00005684/// declaration was instantiated (either implicitly or explicitly).
5685///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005686/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00005687/// specialization or instantiation has no effect and should be ignored.
5688///
5689/// \returns true if there was an error that should prevent the introduction of
5690/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00005691bool
5692Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5693 TemplateSpecializationKind NewTSK,
5694 NamedDecl *PrevDecl,
5695 TemplateSpecializationKind PrevTSK,
5696 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005697 bool &HasNoEffect) {
5698 HasNoEffect = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005699
Douglas Gregor454885e2009-10-15 15:54:05 +00005700 switch (NewTSK) {
5701 case TSK_Undeclared:
5702 case TSK_ImplicitInstantiation:
David Blaikieb219cfc2011-09-23 05:06:16 +00005703 llvm_unreachable("Don't check implicit instantiations here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005704
Douglas Gregor454885e2009-10-15 15:54:05 +00005705 case TSK_ExplicitSpecialization:
5706 switch (PrevTSK) {
5707 case TSK_Undeclared:
5708 case TSK_ExplicitSpecialization:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005709 // Okay, we're just specializing something that is either already
Douglas Gregor454885e2009-10-15 15:54:05 +00005710 // explicitly specialized or has merely been mentioned without any
5711 // instantiation.
5712 return false;
5713
5714 case TSK_ImplicitInstantiation:
5715 if (PrevPointOfInstantiation.isInvalid()) {
5716 // The declaration itself has not actually been instantiated, so it is
5717 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00005718 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00005719 return false;
5720 }
5721 // Fall through
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005722
Douglas Gregor454885e2009-10-15 15:54:05 +00005723 case TSK_ExplicitInstantiationDeclaration:
5724 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005725 assert((PrevTSK == TSK_ImplicitInstantiation ||
5726 PrevPointOfInstantiation.isValid()) &&
Douglas Gregor454885e2009-10-15 15:54:05 +00005727 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005728
Douglas Gregor454885e2009-10-15 15:54:05 +00005729 // C++ [temp.expl.spec]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005730 // If a template, a member template or the member of a class template
Douglas Gregor454885e2009-10-15 15:54:05 +00005731 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005732 // before the first use of that specialization that would cause an
Douglas Gregor454885e2009-10-15 15:54:05 +00005733 // implicit instantiation to take place, in every translation unit in
5734 // which such a use occurs; no diagnostic is required.
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005735 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005736 // Is there any previous explicit specialization declaration?
5737 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
5738 return false;
5739 }
5740
Douglas Gregor0d035142009-10-27 18:42:08 +00005741 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00005742 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00005743 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00005744 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005745
Douglas Gregor454885e2009-10-15 15:54:05 +00005746 return true;
5747 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005748
Douglas Gregor454885e2009-10-15 15:54:05 +00005749 case TSK_ExplicitInstantiationDeclaration:
5750 switch (PrevTSK) {
5751 case TSK_ExplicitInstantiationDeclaration:
5752 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005753 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005754 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005755
Douglas Gregor454885e2009-10-15 15:54:05 +00005756 case TSK_Undeclared:
5757 case TSK_ImplicitInstantiation:
5758 // We're explicitly instantiating something that may have already been
5759 // implicitly instantiated; that's fine.
5760 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005761
Douglas Gregor454885e2009-10-15 15:54:05 +00005762 case TSK_ExplicitSpecialization:
5763 // C++0x [temp.explicit]p4:
5764 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005765 // of a template appears after a declaration of an explicit
Douglas Gregor454885e2009-10-15 15:54:05 +00005766 // specialization for that template, the explicit instantiation has no
5767 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005768 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005769 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005770
Douglas Gregor454885e2009-10-15 15:54:05 +00005771 case TSK_ExplicitInstantiationDefinition:
5772 // C++0x [temp.explicit]p10:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005773 // If an entity is the subject of both an explicit instantiation
5774 // declaration and an explicit instantiation definition in the same
Douglas Gregor454885e2009-10-15 15:54:05 +00005775 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005776 Diag(NewLoc,
Douglas Gregor0d035142009-10-27 18:42:08 +00005777 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberff91d242011-12-23 20:58:04 +00005778
5779 // Explicit instantiations following a specialization have no effect and
5780 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
5781 // until a valid name loc is found.
Nico Weberd1d512a2012-01-09 19:52:25 +00005782 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
5783 diag::note_explicit_instantiation_definition_here);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005784 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005785 return false;
5786 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005787
Douglas Gregor454885e2009-10-15 15:54:05 +00005788 case TSK_ExplicitInstantiationDefinition:
5789 switch (PrevTSK) {
5790 case TSK_Undeclared:
5791 case TSK_ImplicitInstantiation:
5792 // We're explicitly instantiating something that may have already been
5793 // implicitly instantiated; that's fine.
5794 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005795
Douglas Gregor454885e2009-10-15 15:54:05 +00005796 case TSK_ExplicitSpecialization:
5797 // C++ DR 259, C++0x [temp.explicit]p4:
5798 // For a given set of template parameters, if an explicit
5799 // instantiation of a template appears after a declaration of
5800 // an explicit specialization for that template, the explicit
5801 // instantiation has no effect.
5802 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005803 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00005804 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00005805 // has been explicitly specialized.
David Blaikie4e4d0842012-03-11 07:00:24 +00005806 Diag(NewLoc, getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005807 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
5808 diag::ext_explicit_instantiation_after_specialization)
5809 << PrevDecl;
5810 Diag(PrevDecl->getLocation(),
5811 diag::note_previous_template_specialization);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005812 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005813 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005814
Douglas Gregor454885e2009-10-15 15:54:05 +00005815 case TSK_ExplicitInstantiationDeclaration:
5816 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005817 // were previously asked to suppress instantiations. That's fine.
Nico Weberff91d242011-12-23 20:58:04 +00005818
5819 // C++0x [temp.explicit]p4:
5820 // For a given set of template parameters, if an explicit instantiation
5821 // of a template appears after a declaration of an explicit
5822 // specialization for that template, the explicit instantiation has no
5823 // effect.
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005824 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberff91d242011-12-23 20:58:04 +00005825 // Is there any previous explicit specialization declaration?
5826 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5827 HasNoEffect = true;
5828 break;
5829 }
5830 }
5831
Douglas Gregor454885e2009-10-15 15:54:05 +00005832 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005833
Douglas Gregor454885e2009-10-15 15:54:05 +00005834 case TSK_ExplicitInstantiationDefinition:
5835 // C++0x [temp.spec]p5:
5836 // For a given template and a given set of template-arguments,
5837 // - an explicit instantiation definition shall appear at most once
5838 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00005839 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00005840 << PrevDecl;
Nico Weberd1d512a2012-01-09 19:52:25 +00005841 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor0d035142009-10-27 18:42:08 +00005842 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005843 HasNoEffect = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005844 return false;
Douglas Gregor454885e2009-10-15 15:54:05 +00005845 }
Douglas Gregor454885e2009-10-15 15:54:05 +00005846 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005847
David Blaikieb219cfc2011-09-23 05:06:16 +00005848 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregor454885e2009-10-15 15:54:05 +00005849}
5850
John McCallaf2094e2010-04-08 09:05:18 +00005851/// \brief Perform semantic analysis for the given dependent function
James Dennettef2b5b32012-06-15 22:23:43 +00005852/// template specialization.
John McCallaf2094e2010-04-08 09:05:18 +00005853///
James Dennettef2b5b32012-06-15 22:23:43 +00005854/// The only possible way to get a dependent function template specialization
5855/// is with a friend declaration, like so:
5856///
5857/// \code
5858/// template \<class T> void foo(T);
5859/// template \<class T> class A {
John McCallaf2094e2010-04-08 09:05:18 +00005860/// friend void foo<>(T);
5861/// };
James Dennettef2b5b32012-06-15 22:23:43 +00005862/// \endcode
John McCallaf2094e2010-04-08 09:05:18 +00005863///
5864/// There really isn't any useful analysis we can do here, so we
5865/// just store the information.
5866bool
5867Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5868 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5869 LookupResult &Previous) {
5870 // Remove anything from Previous that isn't a function template in
5871 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005872 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00005873 LookupResult::Filter F = Previous.makeFilter();
5874 while (F.hasNext()) {
5875 NamedDecl *D = F.next()->getUnderlyingDecl();
5876 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00005877 !FDLookupContext->InEnclosingNamespaceSetOf(
5878 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00005879 F.erase();
5880 }
5881 F.done();
5882
5883 // Should this be diagnosed here?
5884 if (Previous.empty()) return true;
5885
5886 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
5887 ExplicitTemplateArgs);
5888 return false;
5889}
5890
Abramo Bagnarae03db982010-05-20 15:32:11 +00005891/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005892/// specialization.
5893///
Abramo Bagnarae03db982010-05-20 15:32:11 +00005894/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005895/// explicit function template specialization. On successful completion,
5896/// the function declaration \p FD will become a function template
5897/// specialization.
5898///
5899/// \param FD the function declaration, which will be updated to become a
5900/// function template specialization.
5901///
Abramo Bagnarae03db982010-05-20 15:32:11 +00005902/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
5903/// if any. Note that this may be valid info even when 0 arguments are
5904/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
5905/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005906///
Francois Pichet59e7c562011-07-08 06:21:47 +00005907/// \param Previous the set of declarations that may be specialized by
Abramo Bagnarae03db982010-05-20 15:32:11 +00005908/// this function specialization.
5909bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005910Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
Douglas Gregor67714232011-03-03 02:41:12 +00005911 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00005912 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005913 // The set of function template specializations that could match this
5914 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005915 UnresolvedSet<8> Candidates;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005916
Sebastian Redl7a126a42010-08-31 00:36:30 +00005917 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00005918 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5919 I != E; ++I) {
5920 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
5921 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005922 // Only consider templates found within the same semantic lookup scope as
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005923 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005924 if (!FDLookupContext->InEnclosingNamespaceSetOf(
5925 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005926 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005927
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005928 // C++ [temp.expl.spec]p11:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005929 // A trailing template-argument can be left unspecified in the
5930 // template-id naming an explicit function template specialization
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005931 // provided it can be deduced from the function argument type.
5932 // Perform template argument deduction to determine whether we may be
5933 // specializing this template.
5934 // FIXME: It is somewhat wasteful to build
Craig Topper93e45992012-09-19 02:26:47 +00005935 TemplateDeductionInfo Info(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005936 FunctionDecl *Specialization = 0;
5937 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00005938 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005939 FD->getType(),
5940 Specialization,
5941 Info)) {
5942 // FIXME: Template argument deduction failed; record why it failed, so
5943 // that we can provide nifty diagnostics.
5944 (void)TDK;
5945 continue;
5946 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005947
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005948 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00005949 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005950 }
5951 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005952
Douglas Gregorc5df30f2009-09-26 03:41:46 +00005953 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00005954 UnresolvedSetIterator Result
5955 = getMostSpecialized(Candidates.begin(), Candidates.end(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00005956 TPOC_Other, 0, FD->getLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005957 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00005958 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005959 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00005960 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005961 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00005962 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005963 return true;
John McCallc373d482010-01-27 01:50:18 +00005964
5965 // Ignore access information; it doesn't figure into redeclaration checking.
5966 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnaraabfb4052011-03-04 17:20:30 +00005967
5968 FunctionTemplateSpecializationInfo *SpecInfo
5969 = Specialization->getTemplateSpecializationInfo();
5970 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet59e7c562011-07-08 06:21:47 +00005971
5972 // Note: do not overwrite location info if previous template
5973 // specialization kind was explicit.
5974 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smithff234882012-02-20 23:28:05 +00005975 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet59e7c562011-07-08 06:21:47 +00005976 Specialization->setLocation(FD->getLocation());
Richard Smithff234882012-02-20 23:28:05 +00005977 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
5978 // function can differ from the template declaration with respect to
5979 // the constexpr specifier.
5980 Specialization->setConstexpr(FD->isConstexpr());
5981 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005982
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005983 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005984 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00005985
5986 // If this is a friend declaration, then we're not really declaring
5987 // an explicit specialization.
5988 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005989
Douglas Gregord5cb8762009-10-07 00:13:32 +00005990 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00005991 if (!isFriend &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005992 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00005993 Specialization->getPrimaryTemplate(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005994 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00005995 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00005996 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005997
5998 // C++ [temp.expl.spec]p6:
5999 // If a template, a member template or the member of a class template is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006000 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006001 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006002 // instantiation to take place, in every translation unit in which such a
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006003 // use occurs; no diagnostic is required.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006004 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00006005 if (!isFriend &&
6006 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00006007 TSK_ExplicitSpecialization,
6008 Specialization,
6009 SpecInfo->getTemplateSpecializationKind(),
6010 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006011 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006012 return true;
Douglas Gregore885e182011-05-21 18:53:30 +00006013
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006014 // Mark the prior declaration as an explicit specialization, so that later
6015 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00006016 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00006017 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00006018 MarkUnusedFileScopedDecl(Specialization);
6019 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006020
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006021 // Turn the given function declaration into a function template
6022 // specialization, with the template arguments from the previous
6023 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00006024 // Take copies of (semantic and syntactic) template argument lists.
6025 const TemplateArgumentList* TemplArgs = new (Context)
6026 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Douglas Gregor838db382010-02-11 01:19:42 +00006027 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00006028 TemplArgs, /*InsertPos=*/0,
6029 SpecInfo->getTemplateSpecializationKind(),
Argyrios Kyrtzidis71a76052011-09-22 20:07:09 +00006030 ExplicitTemplateArgs);
Douglas Gregore885e182011-05-21 18:53:30 +00006031 FD->setStorageClass(Specialization->getStorageClass());
6032
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006033 // The "previous declaration" for this function template specialization is
6034 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00006035 Previous.clear();
6036 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006037 return false;
6038}
6039
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006040/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00006041/// specialization.
6042///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006043/// This routine performs all of the semantic analysis required for an
Douglas Gregor1fef4e62009-10-07 22:35:40 +00006044/// explicit member function specialization. On successful completion,
6045/// the function declaration \p FD will become a member function
6046/// specialization.
6047///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006048/// \param Member the member declaration, which will be updated to become a
6049/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00006050///
John McCall68263142009-11-18 22:49:29 +00006051/// \param Previous the set of declarations, one of which may be specialized
6052/// by this function specialization; the set will be modified to contain the
6053/// redeclared member.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006054bool
John McCall68263142009-11-18 22:49:29 +00006055Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006056 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00006057
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006058 // Try to find the member we are instantiating.
6059 NamedDecl *Instantiation = 0;
6060 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006061 MemberSpecializationInfo *MSInfo = 0;
6062
John McCall68263142009-11-18 22:49:29 +00006063 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006064 // Nowhere to look anyway.
6065 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00006066 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6067 I != E; ++I) {
6068 NamedDecl *D = (*I)->getUnderlyingDecl();
6069 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006070 if (Context.hasSameType(Function->getType(), Method->getType())) {
6071 Instantiation = Method;
6072 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006073 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006074 break;
6075 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00006076 }
6077 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006078 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00006079 VarDecl *PrevVar;
6080 if (Previous.isSingleResult() &&
6081 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006082 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00006083 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006084 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006085 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006086 }
6087 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00006088 CXXRecordDecl *PrevRecord;
6089 if (Previous.isSingleResult() &&
6090 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6091 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006092 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006093 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006094 }
Richard Smith1af83c42012-03-23 03:33:32 +00006095 } else if (isa<EnumDecl>(Member)) {
6096 EnumDecl *PrevEnum;
6097 if (Previous.isSingleResult() &&
6098 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6099 Instantiation = PrevEnum;
6100 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6101 MSInfo = PrevEnum->getMemberSpecializationInfo();
6102 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00006103 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006104
Douglas Gregor1fef4e62009-10-07 22:35:40 +00006105 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006106 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00006107 // specializations are always out-of-line, the caller will complain about
6108 // this mismatch later.
6109 return false;
6110 }
John McCall77e8b112010-04-13 20:37:33 +00006111
6112 // If this is a friend, just bail out here before we start turning
6113 // things into explicit specializations.
6114 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6115 // Preserve instantiation information.
6116 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6117 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6118 cast<CXXMethodDecl>(InstantiatedFrom),
6119 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6120 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6121 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6122 cast<CXXRecordDecl>(InstantiatedFrom),
6123 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6124 }
6125
6126 Previous.clear();
6127 Previous.addDecl(Instantiation);
6128 return false;
6129 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006130
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006131 // Make sure that this is a specialization of a member.
6132 if (!InstantiatedFrom) {
6133 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6134 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00006135 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6136 return true;
6137 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006138
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006139 // C++ [temp.expl.spec]p6:
6140 // If a template, a member template or the member of a class template is
Nico Weberff91d242011-12-23 20:58:04 +00006141 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006142 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006143 // instantiation to take place, in every translation unit in which such a
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006144 // use occurs; no diagnostic is required.
6145 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00006146
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006147 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00006148 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
6149 TSK_ExplicitSpecialization,
6150 Instantiation,
6151 MSInfo->getTemplateSpecializationKind(),
6152 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006153 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006154 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006155
Douglas Gregor1fef4e62009-10-07 22:35:40 +00006156 // Check the scope of this explicit specialization.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006157 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006158 InstantiatedFrom,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006159 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00006160 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00006161 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00006162
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006163 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00006164 // the original declaration to note that it is an explicit specialization
6165 // (if it was previously an implicit instantiation). This latter step
6166 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006167 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00006168 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
6169 if (InstantiationFunction->getTemplateSpecializationKind() ==
6170 TSK_ImplicitInstantiation) {
6171 InstantiationFunction->setTemplateSpecializationKind(
6172 TSK_ExplicitSpecialization);
6173 InstantiationFunction->setLocation(Member->getLocation());
6174 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006175
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006176 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
6177 cast<CXXMethodDecl>(InstantiatedFrom),
6178 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00006179 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006180 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00006181 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
6182 if (InstantiationVar->getTemplateSpecializationKind() ==
6183 TSK_ImplicitInstantiation) {
6184 InstantiationVar->setTemplateSpecializationKind(
6185 TSK_ExplicitSpecialization);
6186 InstantiationVar->setLocation(Member->getLocation());
6187 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006188
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006189 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
6190 cast<VarDecl>(InstantiatedFrom),
6191 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00006192 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith1af83c42012-03-23 03:33:32 +00006193 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00006194 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
6195 if (InstantiationClass->getTemplateSpecializationKind() ==
6196 TSK_ImplicitInstantiation) {
6197 InstantiationClass->setTemplateSpecializationKind(
6198 TSK_ExplicitSpecialization);
6199 InstantiationClass->setLocation(Member->getLocation());
6200 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006201
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006202 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00006203 cast<CXXRecordDecl>(InstantiatedFrom),
6204 TSK_ExplicitSpecialization);
Richard Smith1af83c42012-03-23 03:33:32 +00006205 } else {
6206 assert(isa<EnumDecl>(Member) && "Only member enums remain");
6207 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
6208 if (InstantiationEnum->getTemplateSpecializationKind() ==
6209 TSK_ImplicitInstantiation) {
6210 InstantiationEnum->setTemplateSpecializationKind(
6211 TSK_ExplicitSpecialization);
6212 InstantiationEnum->setLocation(Member->getLocation());
6213 }
6214
6215 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
6216 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006217 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006218
Douglas Gregor1fef4e62009-10-07 22:35:40 +00006219 // Save the caller the trouble of having to figure out which declaration
6220 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00006221 Previous.clear();
6222 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00006223 return false;
6224}
6225
Douglas Gregor558c0322009-10-14 23:41:34 +00006226/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00006227///
6228/// \returns true if a serious error occurs, false otherwise.
6229static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00006230 SourceLocation InstLoc,
6231 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006232 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
6233 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006234
Douglas Gregor669eed82010-07-13 00:10:04 +00006235 if (CurContext->isRecord()) {
6236 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
6237 << D;
6238 return true;
6239 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006240
Richard Smith3e2e91e2011-10-18 02:28:33 +00006241 // C++11 [temp.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006242 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith3e2e91e2011-10-18 02:28:33 +00006243 // template. If the name declared in the explicit instantiation is an
6244 // unqualified name, the explicit instantiation shall appear in the
6245 // namespace where its template is declared or, if that namespace is inline
6246 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregor558c0322009-10-14 23:41:34 +00006247 //
6248 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith3e2e91e2011-10-18 02:28:33 +00006249 if (WasQualifiedName) {
6250 if (CurContext->Encloses(OrigContext))
6251 return false;
6252 } else {
6253 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
6254 return false;
6255 }
6256
6257 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
6258 if (WasQualifiedName)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006259 S.Diag(InstLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00006260 S.getLangOpts().CPlusPlus0x?
Richard Smith3e2e91e2011-10-18 02:28:33 +00006261 diag::err_explicit_instantiation_out_of_scope :
6262 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00006263 << D << NS;
6264 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006265 S.Diag(InstLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00006266 S.getLangOpts().CPlusPlus0x?
Richard Smith3e2e91e2011-10-18 02:28:33 +00006267 diag::err_explicit_instantiation_unqualified_wrong_namespace :
6268 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
6269 << D << NS;
6270 } else
6271 S.Diag(InstLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00006272 S.getLangOpts().CPlusPlus0x?
Richard Smith3e2e91e2011-10-18 02:28:33 +00006273 diag::err_explicit_instantiation_must_be_global :
6274 diag::warn_explicit_instantiation_must_be_global_0x)
6275 << D;
Douglas Gregor558c0322009-10-14 23:41:34 +00006276 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00006277 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00006278}
6279
6280/// \brief Determine whether the given scope specifier has a template-id in it.
6281static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
6282 if (!SS.isSet())
6283 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006284
Richard Smith3e2e91e2011-10-18 02:28:33 +00006285 // C++11 [temp.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006286 // If the explicit instantiation is for a member function, a member class
Douglas Gregor558c0322009-10-14 23:41:34 +00006287 // or a static data member of a class template specialization, the name of
6288 // the class template specialization in the qualified-id for the member
6289 // name shall be a simple-template-id.
6290 //
6291 // C++98 has the same restriction, just worded differently.
6292 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
6293 NNS; NNS = NNS->getPrefix())
John McCallf4c73712011-01-19 06:33:43 +00006294 if (const Type *T = NNS->getAsType())
Douglas Gregor558c0322009-10-14 23:41:34 +00006295 if (isa<TemplateSpecializationType>(T))
6296 return true;
6297
6298 return false;
6299}
6300
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006301// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00006302DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00006303Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00006304 SourceLocation ExternLoc,
6305 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006306 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006307 SourceLocation KWLoc,
6308 const CXXScopeSpec &SS,
6309 TemplateTy TemplateD,
6310 SourceLocation TemplateNameLoc,
6311 SourceLocation LAngleLoc,
6312 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006313 SourceLocation RAngleLoc,
6314 AttributeList *Attr) {
6315 // Find the class template we're specializing
6316 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00006317 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006318 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
6319
6320 // Check that the specialization uses the same tag kind as the
6321 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006322 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6323 assert(Kind != TTK_Enum &&
6324 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00006325 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieubbf34c02011-06-10 03:11:26 +00006326 Kind, /*isDefinition*/false, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00006327 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006328 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006329 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00006330 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006331 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00006332 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006333 diag::note_previous_use);
6334 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6335 }
6336
Douglas Gregor558c0322009-10-14 23:41:34 +00006337 // C++0x [temp.explicit]p2:
6338 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006339 // definition and an explicit instantiation declaration. An explicit
6340 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00006341 TemplateSpecializationKind TSK
6342 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6343 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006344
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006345 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00006346 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00006347 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006348
6349 // Check that the template argument list is well-formed for this
6350 // template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006351 SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00006352 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6353 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006354 return true;
6355
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006356 // Find the class template specialization declaration that
6357 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006358 void *InsertPos = 0;
6359 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00006360 = ClassTemplate->findSpecialization(Converted.data(),
6361 Converted.size(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006362
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006363 TemplateSpecializationKind PrevDecl_TSK
6364 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
6365
Douglas Gregord5cb8762009-10-07 00:13:32 +00006366 // C++0x [temp.explicit]p2:
6367 // [...] An explicit instantiation shall appear in an enclosing
6368 // namespace of its template. [...]
6369 //
6370 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00006371 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
6372 SS.isSet()))
6373 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006374
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006375 ClassTemplateSpecializationDecl *Specialization = 0;
6376
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006377 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006378 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00006379 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006380 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006381 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006382 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00006383 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006384
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006385 // Even though HasNoEffect == true means that this explicit instantiation
6386 // has no effect on semantics, we go on to put its syntax in the AST.
6387
6388 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
6389 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00006390 // Since the only prior class template specialization with these
6391 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006392 // declaration node as our own, updating the source location
6393 // for the template name to reflect our new declaration.
6394 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00006395 Specialization = PrevDecl;
6396 Specialization->setLocation(TemplateNameLoc);
6397 PrevDecl = 0;
6398 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006399 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006400
Douglas Gregor52604ab2009-09-11 21:19:12 +00006401 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006402 // Create a new class template specialization declaration node for
6403 // this explicit specialization.
6404 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00006405 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006406 ClassTemplate->getDeclContext(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00006407 KWLoc, TemplateNameLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006408 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00006409 Converted.data(),
6410 Converted.size(),
6411 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00006412 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006413
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00006414 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006415 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00006416 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006417 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006418 }
6419
6420 // Build the fully-sugared type for this explicit instantiation as
6421 // the user wrote in the explicit instantiation itself. This means
6422 // that we'll pretty-print the type retrieved from the
6423 // specialization's declaration the way that the user actually wrote
6424 // the explicit instantiation, rather than formatting the name based
6425 // on the "canonical" representation used to store the template
6426 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00006427 TypeSourceInfo *WrittenTy
6428 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6429 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006430 Context.getTypeDeclType(Specialization));
6431 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006432
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006433 // Set source locations for keywords.
6434 Specialization->setExternLoc(ExternLoc);
6435 Specialization->setTemplateKeywordLoc(TemplateLoc);
6436
Rafael Espindola0257b7f2012-01-03 06:04:21 +00006437 if (Attr)
6438 ProcessDeclAttributeList(S, Specialization, Attr);
6439
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006440 // Add the explicit instantiation into its lexical context. However,
6441 // since explicit instantiations are never found by name lookup, we
6442 // just put it into the declaration context directly.
6443 Specialization->setLexicalDeclContext(CurContext);
6444 CurContext->addDecl(Specialization);
6445
6446 // Syntax is now OK, so return if it has no other effect on semantics.
6447 if (HasNoEffect) {
6448 // Set the template specialization kind.
6449 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00006450 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00006451 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006452
6453 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006454 // A definition of a class template or class member template
6455 // shall be in scope at the point of the explicit instantiation of
6456 // the class template or class member template.
6457 //
6458 // This check comes when we actually try to perform the
6459 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006460 ClassTemplateSpecializationDecl *Def
6461 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00006462 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006463 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00006464 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006465 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006466 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006467 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
6468 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006469
Douglas Gregor0d035142009-10-27 18:42:08 +00006470 // Instantiate the members of this class template specialization.
6471 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00006472 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00006473 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00006474 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
6475
6476 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
6477 // TSK_ExplicitInstantiationDefinition
6478 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
6479 TSK == TSK_ExplicitInstantiationDefinition)
6480 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00006481
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006482 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00006483 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006484
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006485 // Set the template specialization kind.
6486 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00006487 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006488}
6489
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006490// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00006491DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00006492Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00006493 SourceLocation ExternLoc,
6494 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006495 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006496 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006497 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006498 IdentifierInfo *Name,
6499 SourceLocation NameLoc,
6500 AttributeList *Attr) {
6501
Douglas Gregor402abb52009-05-28 23:31:59 +00006502 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00006503 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00006504 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00006505 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregore7612302011-09-09 19:05:14 +00006506 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006507 MultiTemplateParamsArg(), Owned, IsDependent,
6508 SourceLocation(), false, TypeResult());
John McCallc4e70192009-09-11 04:59:25 +00006509 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
6510
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006511 if (!TagD)
6512 return true;
6513
John McCalld226f652010-08-21 09:40:31 +00006514 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith1af83c42012-03-23 03:33:32 +00006515 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006516
Douglas Gregord0c87372009-05-27 17:30:49 +00006517 if (Tag->isInvalidDecl())
6518 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006519
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006520 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
6521 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
6522 if (!Pattern) {
6523 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
6524 << Context.getTypeDeclType(Record);
6525 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
6526 return true;
6527 }
6528
Douglas Gregor558c0322009-10-14 23:41:34 +00006529 // C++0x [temp.explicit]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006530 // If the explicit instantiation is for a class or member class, the
6531 // elaborated-type-specifier in the declaration shall include a
Douglas Gregor558c0322009-10-14 23:41:34 +00006532 // simple-template-id.
6533 //
6534 // C++98 has the same restriction, just worded differently.
6535 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00006536 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00006537 << Record << SS.getRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006538
Douglas Gregor558c0322009-10-14 23:41:34 +00006539 // C++0x [temp.explicit]p2:
6540 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006541 // definition and an explicit instantiation declaration. An explicit
Douglas Gregor558c0322009-10-14 23:41:34 +00006542 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00006543 TemplateSpecializationKind TSK
6544 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6545 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006546
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006547 // C++0x [temp.explicit]p2:
6548 // [...] An explicit instantiation shall appear in an enclosing
6549 // namespace of its template. [...]
6550 //
6551 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00006552 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006553
Douglas Gregor454885e2009-10-15 15:54:05 +00006554 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006555 CXXRecordDecl *PrevDecl
Douglas Gregoref96ee02012-01-14 16:38:05 +00006556 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor952b0172010-02-11 01:04:33 +00006557 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00006558 PrevDecl = Record;
6559 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00006560 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006561 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00006562 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006563 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00006564 PrevDecl,
6565 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006566 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006567 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00006568 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006569 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00006570 return TagD;
6571 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006572
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006573 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00006574 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006575 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006576 // C++ [temp.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006577 // A definition of a member class of a class template shall be in scope
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006578 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006579 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00006580 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006581 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00006582 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
6583 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006584 Diag(Pattern->getLocation(), diag::note_forward_declaration)
6585 << Pattern;
6586 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00006587 } else {
6588 if (InstantiateClass(NameLoc, Record, Def,
6589 getTemplateInstantiationArgs(Record),
6590 TSK))
6591 return true;
6592
Douglas Gregor952b0172010-02-11 01:04:33 +00006593 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00006594 if (!RecordDef)
6595 return true;
6596 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006597 }
6598
Douglas Gregor0d035142009-10-27 18:42:08 +00006599 // Instantiate all of the members of the class.
6600 InstantiateClassMembers(NameLoc, RecordDef,
6601 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006602
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006603 if (TSK == TSK_ExplicitInstantiationDefinition)
6604 MarkVTableUsed(NameLoc, RecordDef, true);
6605
Mike Stump390b4cc2009-05-16 07:39:55 +00006606 // FIXME: We don't have any representation for explicit instantiations of
6607 // member classes. Such a representation is not needed for compilation, but it
6608 // should be available for clients that want to see all of the declarations in
6609 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006610 return TagD;
6611}
6612
John McCallf312b1e2010-08-26 23:41:50 +00006613DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
6614 SourceLocation ExternLoc,
6615 SourceLocation TemplateLoc,
6616 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00006617 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00006618 // TODO: check if/when DNInfo should replace Name.
6619 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6620 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006621 if (!Name) {
6622 if (!D.isInvalidType())
Daniel Dunbar96a00142012-03-09 18:35:03 +00006623 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006624 diag::err_explicit_instantiation_requires_name)
6625 << D.getDeclSpec().getSourceRange()
6626 << D.getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006627
Douglas Gregord5a423b2009-09-25 18:43:00 +00006628 return true;
6629 }
6630
6631 // The scope passed in may not be a decl scope. Zip up the scope tree until
6632 // we find one that is.
6633 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6634 (S->getFlags() & Scope::TemplateParamScope) != 0)
6635 S = S->getParent();
6636
6637 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00006638 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
6639 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006640 if (R.isNull())
6641 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006642
Douglas Gregore885e182011-05-21 18:53:30 +00006643 // C++ [dcl.stc]p1:
6644 // A storage-class-specifier shall not be specified in [...] an explicit
6645 // instantiation (14.7.2) directive.
Douglas Gregord5a423b2009-09-25 18:43:00 +00006646 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00006647 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
6648 << Name;
6649 return true;
Douglas Gregore885e182011-05-21 18:53:30 +00006650 } else if (D.getDeclSpec().getStorageClassSpec()
6651 != DeclSpec::SCS_unspecified) {
6652 // Complain about then remove the storage class specifier.
6653 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
6654 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6655
6656 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006657 }
6658
Douglas Gregor663b5a02009-10-14 20:14:33 +00006659 // C++0x [temp.explicit]p1:
6660 // [...] An explicit instantiation of a function template shall not use the
6661 // inline or constexpr specifiers.
6662 // Presumably, this also applies to member functions of class templates as
6663 // well.
Richard Smith2dc7ece2011-10-18 03:44:03 +00006664 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006665 Diag(D.getDeclSpec().getInlineSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006666 getLangOpts().CPlusPlus0x ?
Richard Smith2dc7ece2011-10-18 03:44:03 +00006667 diag::err_explicit_instantiation_inline :
6668 diag::warn_explicit_instantiation_inline_0x)
Richard Smithfe6f6482011-10-14 19:58:02 +00006669 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6670 if (D.getDeclSpec().isConstexprSpecified())
6671 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
6672 // not already specified.
6673 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6674 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006675
Douglas Gregor558c0322009-10-14 23:41:34 +00006676 // C++0x [temp.explicit]p2:
6677 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006678 // definition and an explicit instantiation declaration. An explicit
6679 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00006680 TemplateSpecializationKind TSK
6681 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6682 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006683
Abramo Bagnara25777432010-08-11 22:01:17 +00006684 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00006685 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006686
6687 if (!R->isFunctionType()) {
6688 // C++ [temp.explicit]p1:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006689 // A [...] static data member of a class template can be explicitly
6690 // instantiated from the member definition associated with its class
Douglas Gregord5a423b2009-09-25 18:43:00 +00006691 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00006692 if (Previous.isAmbiguous())
6693 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006694
John McCall1bcee0a2009-12-02 08:25:40 +00006695 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006696 if (!Prev || !Prev->isStaticDataMember()) {
6697 // We expect to see a data data member here.
6698 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
6699 << Name;
6700 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6701 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00006702 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00006703 return true;
6704 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006705
Douglas Gregord5a423b2009-09-25 18:43:00 +00006706 if (!Prev->getInstantiatedFromStaticDataMember()) {
6707 // FIXME: Check for explicit specialization?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006708 Diag(D.getIdentifierLoc(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006709 diag::err_explicit_instantiation_data_member_not_instantiated)
6710 << Prev;
6711 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
6712 // FIXME: Can we provide a note showing where this was declared?
6713 return true;
6714 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006715
Douglas Gregor558c0322009-10-14 23:41:34 +00006716 // C++0x [temp.explicit]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006717 // If the explicit instantiation is for a member function, a member class
Douglas Gregor558c0322009-10-14 23:41:34 +00006718 // or a static data member of a class template specialization, the name of
6719 // the class template specialization in the qualified-id for the member
6720 // name shall be a simple-template-id.
6721 //
6722 // C++98 has the same restriction, just worded differently.
6723 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006724 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00006725 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00006726 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006727
Douglas Gregor558c0322009-10-14 23:41:34 +00006728 // Check the scope of this explicit instantiation.
6729 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006730
Douglas Gregor454885e2009-10-15 15:54:05 +00006731 // Verify that it is okay to explicitly instantiate here.
6732 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
6733 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006734 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00006735 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00006736 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006737 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006738 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00006739 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006740 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00006741 return (Decl*) 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006742
Douglas Gregord5a423b2009-09-25 18:43:00 +00006743 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00006744 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006745 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00006746 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006747
Douglas Gregord5a423b2009-09-25 18:43:00 +00006748 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00006749 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00006750 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006751
6752 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00006753 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00006754 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00006755 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006756 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6757 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00006758 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
6759 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramer5354e772012-08-23 23:38:35 +00006760 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00006761 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00006762 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00006763 HasExplicitTemplateArgs = true;
6764 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006765
Douglas Gregord5a423b2009-09-25 18:43:00 +00006766 // C++ [temp.explicit]p1:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006767 // A [...] function [...] can be explicitly instantiated from its template.
6768 // A member function [...] of a class template can be explicitly
6769 // instantiated from the member definition associated with its class
Douglas Gregord5a423b2009-09-25 18:43:00 +00006770 // template.
John McCallc373d482010-01-27 01:50:18 +00006771 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00006772 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6773 P != PEnd; ++P) {
6774 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00006775 if (!HasExplicitTemplateArgs) {
6776 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
6777 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
6778 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00006779
John McCallc373d482010-01-27 01:50:18 +00006780 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00006781 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
6782 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00006783 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00006784 }
6785 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006786
Douglas Gregord5a423b2009-09-25 18:43:00 +00006787 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
6788 if (!FunTmpl)
6789 continue;
6790
Craig Topper93e45992012-09-19 02:26:47 +00006791 TemplateDeductionInfo Info(D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006792 FunctionDecl *Specialization = 0;
6793 if (TemplateDeductionResult TDK
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006794 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00006795 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006796 R, Specialization, Info)) {
6797 // FIXME: Keep track of almost-matches?
6798 (void)TDK;
6799 continue;
6800 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006801
John McCallc373d482010-01-27 01:50:18 +00006802 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006803 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006804
Douglas Gregord5a423b2009-09-25 18:43:00 +00006805 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00006806 UnresolvedSetIterator Result
Douglas Gregor5c7bf422011-01-11 17:34:58 +00006807 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006808 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006809 PDiag(diag::err_explicit_instantiation_not_known) << Name,
6810 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
6811 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00006812
John McCallc373d482010-01-27 01:50:18 +00006813 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00006814 return true;
John McCallc373d482010-01-27 01:50:18 +00006815
6816 // Ignore access control bits, we don't need them for redeclaration checking.
6817 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006818
Douglas Gregor0a897e32009-10-15 17:21:20 +00006819 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006820 Diag(D.getIdentifierLoc(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006821 diag::err_explicit_instantiation_member_function_not_instantiated)
6822 << Specialization
6823 << (Specialization->getTemplateSpecializationKind() ==
6824 TSK_ExplicitSpecialization);
6825 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
6826 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006827 }
6828
Douglas Gregoref96ee02012-01-14 16:38:05 +00006829 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor583f33b2009-10-15 18:07:02 +00006830 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
6831 PrevDecl = Specialization;
6832
Douglas Gregor0a897e32009-10-15 17:21:20 +00006833 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006834 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00006835 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006836 PrevDecl,
6837 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor0a897e32009-10-15 17:21:20 +00006838 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006839 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00006840 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006841
Douglas Gregor0a897e32009-10-15 17:21:20 +00006842 // FIXME: We may still want to build some representation of this
6843 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006844 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00006845 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00006846 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00006847
6848 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola256fc4d2012-01-04 05:40:59 +00006849 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
6850 if (Attr)
6851 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006852
Douglas Gregor0a897e32009-10-15 17:21:20 +00006853 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00006854 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006855
Douglas Gregor558c0322009-10-14 23:41:34 +00006856 // C++0x [temp.explicit]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006857 // If the explicit instantiation is for a member function, a member class
Douglas Gregor558c0322009-10-14 23:41:34 +00006858 // or a static data member of a class template specialization, the name of
6859 // the class template specialization in the qualified-id for the member
6860 // name shall be a simple-template-id.
6861 //
6862 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00006863 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006864 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006865 D.getCXXScopeSpec().isSet() &&
Douglas Gregor558c0322009-10-14 23:41:34 +00006866 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006867 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00006868 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00006869 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006870
Douglas Gregor558c0322009-10-14 23:41:34 +00006871 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006872 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregor558c0322009-10-14 23:41:34 +00006873 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006874 D.getIdentifierLoc(),
Douglas Gregor558c0322009-10-14 23:41:34 +00006875 D.getCXXScopeSpec().isSet());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006876
Douglas Gregord5a423b2009-09-25 18:43:00 +00006877 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00006878 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00006879}
6880
John McCallf312b1e2010-08-26 23:41:50 +00006881TypeResult
John McCallc4e70192009-09-11 04:59:25 +00006882Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
6883 const CXXScopeSpec &SS, IdentifierInfo *Name,
6884 SourceLocation TagLoc, SourceLocation NameLoc) {
6885 // This has to hold, because SS is expected to be defined.
6886 assert(Name && "Expected a name in a dependent tag");
6887
6888 NestedNameSpecifier *NNS
6889 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6890 if (!NNS)
6891 return true;
6892
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006893 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00006894
Douglas Gregor48c89f42010-04-24 16:38:41 +00006895 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
6896 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006897 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00006898 return true;
6899 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006900
Douglas Gregor059101f2011-03-02 00:47:37 +00006901 // Create the resulting type.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006902 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor059101f2011-03-02 00:47:37 +00006903 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
6904
6905 // Create type-source location information for this type.
6906 TypeLocBuilder TLB;
6907 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara38a42912012-02-06 19:09:27 +00006908 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor059101f2011-03-02 00:47:37 +00006909 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6910 TL.setNameLoc(NameLoc);
6911 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCallc4e70192009-09-11 04:59:25 +00006912}
6913
John McCallf312b1e2010-08-26 23:41:50 +00006914TypeResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006915Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6916 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregor1a15dae2010-06-16 22:31:08 +00006917 SourceLocation IdLoc) {
Douglas Gregore29425b2011-02-28 22:42:13 +00006918 if (SS.isInvalid())
Douglas Gregord57959a2009-03-27 23:10:48 +00006919 return true;
Douglas Gregore29425b2011-02-28 22:42:13 +00006920
Richard Smithebaf0e62011-10-18 20:49:44 +00006921 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
6922 Diag(TypenameLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00006923 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006924 diag::warn_cxx98_compat_typename_outside_of_template :
6925 diag::ext_typename_outside_of_template)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006926 << FixItHint::CreateRemoval(TypenameLoc);
6927
Douglas Gregor2494dd02011-03-01 01:34:45 +00006928 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor9e876872011-03-01 18:12:44 +00006929 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
6930 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00006931 if (T.isNull())
6932 return true;
John McCall63b43852010-04-29 23:50:39 +00006933
6934 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6935 if (isa<DependentNameType>(T)) {
6936 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00006937 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00006938 TL.setQualifierLoc(QualifierLoc);
John McCall4e449832010-05-28 23:32:21 +00006939 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00006940 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006941 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00006942 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00006943 TL.setQualifierLoc(QualifierLoc);
John McCall4e449832010-05-28 23:32:21 +00006944 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00006945 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006946
John McCallb3d87482010-08-24 05:47:05 +00006947 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00006948}
6949
John McCallf312b1e2010-08-26 23:41:50 +00006950TypeResult
Abramo Bagnara55d23c92012-02-06 14:41:24 +00006951Sema::ActOnTypenameType(Scope *S,
6952 SourceLocation TypenameLoc,
6953 const CXXScopeSpec &SS,
6954 SourceLocation TemplateKWLoc,
Douglas Gregora02411e2011-02-27 22:46:49 +00006955 TemplateTy TemplateIn,
6956 SourceLocation TemplateNameLoc,
6957 SourceLocation LAngleLoc,
6958 ASTTemplateArgsPtr TemplateArgsIn,
6959 SourceLocation RAngleLoc) {
Richard Smithebaf0e62011-10-18 20:49:44 +00006960 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
6961 Diag(TypenameLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00006962 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006963 diag::warn_cxx98_compat_typename_outside_of_template :
6964 diag::ext_typename_outside_of_template)
6965 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006966
6967 // Translate the parser's template argument list in our AST format.
6968 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
6969 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
6970
6971 TemplateName Template = TemplateIn.get();
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006972 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6973 // Construct a dependent template specialization type.
6974 assert(DTN && "dependent template has non-dependent name?");
6975 assert(DTN->getQualifier()
6976 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
6977 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
6978 DTN->getQualifier(),
6979 DTN->getIdentifier(),
6980 TemplateArgs);
Douglas Gregora02411e2011-02-27 22:46:49 +00006981
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006982 // Create source-location information for this type.
John McCall4e449832010-05-28 23:32:21 +00006983 TypeLocBuilder Builder;
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006984 DependentTemplateSpecializationTypeLoc SpecTL
6985 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00006986 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
6987 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara66581d42012-02-06 22:45:07 +00006988 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00006989 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006990 SpecTL.setLAngleLoc(LAngleLoc);
6991 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006992 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6993 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006994 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor6946baf2009-09-02 13:05:45 +00006995 }
Douglas Gregora02411e2011-02-27 22:46:49 +00006996
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006997 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
6998 if (T.isNull())
6999 return true;
Douglas Gregora02411e2011-02-27 22:46:49 +00007000
Abramo Bagnara55d23c92012-02-06 14:41:24 +00007001 // Provide source-location information for the template specialization type.
Douglas Gregora02411e2011-02-27 22:46:49 +00007002 TypeLocBuilder Builder;
Abramo Bagnara55d23c92012-02-06 14:41:24 +00007003 TemplateSpecializationTypeLoc SpecTL
Douglas Gregoref24c4b2011-03-01 16:44:30 +00007004 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00007005 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7006 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00007007 SpecTL.setLAngleLoc(LAngleLoc);
7008 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00007009 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7010 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7011
Douglas Gregoref24c4b2011-03-01 16:44:30 +00007012 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
7013 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara38a42912012-02-06 19:09:27 +00007014 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00007015 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7016
Douglas Gregoref24c4b2011-03-01 16:44:30 +00007017 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
7018 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00007019}
7020
Douglas Gregora02411e2011-02-27 22:46:49 +00007021
Richard Smith4493c0a2012-05-09 05:17:00 +00007022/// Determine whether this failed name lookup should be treated as being
7023/// disabled by a usage of std::enable_if.
7024static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
7025 SourceRange &CondRange) {
7026 // We must be looking for a ::type...
7027 if (!II.isStr("type"))
7028 return false;
7029
7030 // ... within an explicitly-written template specialization...
7031 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
7032 return false;
7033 TypeLoc EnableIfTy = NNS.getTypeLoc();
7034 TemplateSpecializationTypeLoc *EnableIfTSTLoc =
7035 dyn_cast<TemplateSpecializationTypeLoc>(&EnableIfTy);
7036 if (!EnableIfTSTLoc || EnableIfTSTLoc->getNumArgs() == 0)
7037 return false;
7038 const TemplateSpecializationType *EnableIfTST =
7039 cast<TemplateSpecializationType>(EnableIfTSTLoc->getTypePtr());
7040
7041 // ... which names a complete class template declaration...
7042 const TemplateDecl *EnableIfDecl =
7043 EnableIfTST->getTemplateName().getAsTemplateDecl();
7044 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
7045 return false;
7046
7047 // ... called "enable_if".
7048 const IdentifierInfo *EnableIfII =
7049 EnableIfDecl->getDeclName().getAsIdentifierInfo();
7050 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
7051 return false;
7052
7053 // Assume the first template argument is the condition.
7054 CondRange = EnableIfTSTLoc->getArgLoc(0).getSourceRange();
7055 return true;
7056}
7057
Douglas Gregord57959a2009-03-27 23:10:48 +00007058/// \brief Build the type that describes a C++ typename specifier,
7059/// e.g., "typename T::type".
7060QualType
Douglas Gregore29425b2011-02-28 22:42:13 +00007061Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
7062 SourceLocation KeywordLoc,
7063 NestedNameSpecifierLoc QualifierLoc,
7064 const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00007065 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00007066 CXXScopeSpec SS;
Douglas Gregore29425b2011-02-28 22:42:13 +00007067 SS.Adopt(QualifierLoc);
Douglas Gregord57959a2009-03-27 23:10:48 +00007068
John McCall77bb1aa2010-05-01 00:40:08 +00007069 DeclContext *Ctx = computeDeclContext(SS);
7070 if (!Ctx) {
7071 // If the nested-name-specifier is dependent and couldn't be
7072 // resolved to a type, build a typename type.
Douglas Gregore29425b2011-02-28 22:42:13 +00007073 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
7074 return Context.getDependentNameType(Keyword,
7075 QualifierLoc.getNestedNameSpecifier(),
7076 &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00007077 }
Douglas Gregord57959a2009-03-27 23:10:48 +00007078
John McCall77bb1aa2010-05-01 00:40:08 +00007079 // If the nested-name-specifier refers to the current instantiation,
7080 // the "typename" keyword itself is superfluous. In C++03, the
7081 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
7082 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00007083 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00007084
John McCall77bb1aa2010-05-01 00:40:08 +00007085 if (RequireCompleteDeclContext(SS, Ctx))
7086 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00007087
7088 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00007089 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00007090 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00007091 unsigned DiagID = 0;
7092 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00007093 switch (Result.getResultKind()) {
Richard Smith4493c0a2012-05-09 05:17:00 +00007094 case LookupResult::NotFound: {
7095 // If we're looking up 'type' within a template named 'enable_if', produce
7096 // a more specific diagnostic.
7097 SourceRange CondRange;
7098 if (isEnableIf(QualifierLoc, II, CondRange)) {
7099 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
7100 << Ctx << CondRange;
7101 return QualType();
7102 }
7103
Douglas Gregor3f093272009-10-13 21:16:44 +00007104 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00007105 break;
Richard Smith4493c0a2012-05-09 05:17:00 +00007106 }
Douglas Gregord9545042010-12-09 00:06:27 +00007107
7108 case LookupResult::FoundUnresolvedValue: {
7109 // We found a using declaration that is a value. Most likely, the using
7110 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregore29425b2011-02-28 22:42:13 +00007111 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregord9545042010-12-09 00:06:27 +00007112 IILoc);
7113 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
7114 << Name << Ctx << FullRange;
7115 if (UnresolvedUsingValueDecl *Using
7116 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregordc355712011-02-25 00:36:19 +00007117 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregord9545042010-12-09 00:06:27 +00007118 Diag(Loc, diag::note_using_value_decl_missing_typename)
7119 << FixItHint::CreateInsertion(Loc, "typename ");
7120 }
7121 }
7122 // Fall through to create a dependent typename type, from which we can recover
7123 // better.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007124
Douglas Gregor7d3f5762010-01-15 01:44:47 +00007125 case LookupResult::NotFoundInCurrentInstantiation:
7126 // Okay, it's a member of an unknown instantiation.
Douglas Gregore29425b2011-02-28 22:42:13 +00007127 return Context.getDependentNameType(Keyword,
7128 QualifierLoc.getNestedNameSpecifier(),
7129 &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00007130
7131 case LookupResult::Found:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007132 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00007133 // We found a type. Build an ElaboratedType, since the
7134 // typename-specifier was just sugar.
Douglas Gregore29425b2011-02-28 22:42:13 +00007135 return Context.getElaboratedType(ETK_Typename,
7136 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara465d41b2010-05-11 21:36:43 +00007137 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00007138 }
7139
7140 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00007141 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00007142 break;
7143
7144 case LookupResult::FoundOverloaded:
7145 DiagID = diag::err_typename_nested_not_type;
7146 Referenced = *Result.begin();
7147 break;
7148
John McCall6e247262009-10-10 05:48:19 +00007149 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00007150 return QualType();
7151 }
7152
7153 // If we get here, it's because name lookup did not find a
7154 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore29425b2011-02-28 22:42:13 +00007155 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00007156 IILoc);
7157 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00007158 if (Referenced)
7159 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
7160 << Name;
7161 return QualType();
7162}
Douglas Gregor4a959d82009-08-06 16:20:37 +00007163
7164namespace {
7165 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00007166 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00007167 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00007168 SourceLocation Loc;
7169 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00007170
Douglas Gregor4a959d82009-08-06 16:20:37 +00007171 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00007172 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007173
Mike Stump1eb44332009-09-09 15:08:12 +00007174 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00007175 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00007176 DeclarationName Entity)
7177 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00007178 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00007179
7180 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00007181 /// transformed.
7182 ///
7183 /// For the purposes of type reconstruction, a type has already been
7184 /// transformed if it is NULL or if it is not dependent.
7185 bool AlreadyTransformed(QualType T) {
7186 return T.isNull() || !T->isDependentType();
7187 }
Mike Stump1eb44332009-09-09 15:08:12 +00007188
7189 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00007190 /// rebuilt.
7191 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00007192
Douglas Gregor4a959d82009-08-06 16:20:37 +00007193 /// \brief Returns the name of the entity whose type is being rebuilt.
7194 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00007195
Douglas Gregor972e6ce2009-10-27 06:26:26 +00007196 /// \brief Sets the "base" location and entity when that
7197 /// information is known based on another transformation.
7198 void setBase(SourceLocation Loc, DeclarationName Entity) {
7199 this->Loc = Loc;
7200 this->Entity = Entity;
7201 }
Douglas Gregordfca6f52012-02-13 22:00:16 +00007202
7203 ExprResult TransformLambdaExpr(LambdaExpr *E) {
7204 // Lambdas never need to be transformed.
7205 return E;
7206 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00007207 };
7208}
7209
Douglas Gregor4a959d82009-08-06 16:20:37 +00007210/// \brief Rebuilds a type within the context of the current instantiation.
7211///
Mike Stump1eb44332009-09-09 15:08:12 +00007212/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00007213/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00007214/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00007215/// partial specialization thereof). This routine will rebuild that type now
7216/// that we have entered the declarator's scope, which may produce different
7217/// canonical types, e.g.,
7218///
7219/// \code
7220/// template<typename T>
7221/// struct X {
7222/// typedef T* pointer;
7223/// pointer data();
7224/// };
7225///
7226/// template<typename T>
7227/// typename X<T>::pointer X<T>::data() { ... }
7228/// \endcode
7229///
Douglas Gregor4714c122010-03-31 17:34:00 +00007230/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00007231/// since we do not know that we can look into X<T> when we parsed the type.
7232/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00007233/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00007234/// as the canonical type of T*, allowing the return types of the out-of-line
7235/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00007236TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7237 SourceLocation Loc,
7238 DeclarationName Name) {
7239 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00007240 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00007241
Douglas Gregor4a959d82009-08-06 16:20:37 +00007242 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
7243 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00007244}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00007245
John McCall60d7b3a2010-08-24 06:29:42 +00007246ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00007247 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
7248 DeclarationName());
7249 return Rebuilder.TransformExpr(E);
7250}
7251
John McCall63b43852010-04-29 23:50:39 +00007252bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor7e384942011-02-25 16:07:42 +00007253 if (SS.isInvalid())
7254 return true;
John McCall31f17ec2010-04-27 00:57:59 +00007255
Douglas Gregor7e384942011-02-25 16:07:42 +00007256 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall31f17ec2010-04-27 00:57:59 +00007257 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
7258 DeclarationName());
Douglas Gregor7e384942011-02-25 16:07:42 +00007259 NestedNameSpecifierLoc Rebuilt
7260 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
7261 if (!Rebuilt)
7262 return true;
John McCall63b43852010-04-29 23:50:39 +00007263
Douglas Gregor7e384942011-02-25 16:07:42 +00007264 SS.Adopt(Rebuilt);
John McCall63b43852010-04-29 23:50:39 +00007265 return false;
John McCall31f17ec2010-04-27 00:57:59 +00007266}
7267
Douglas Gregor20606502011-10-14 15:31:12 +00007268/// \brief Rebuild the template parameters now that we know we're in a current
7269/// instantiation.
7270bool Sema::RebuildTemplateParamsInCurrentInstantiation(
7271 TemplateParameterList *Params) {
7272 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
7273 Decl *Param = Params->getParam(I);
7274
7275 // There is nothing to rebuild in a type parameter.
7276 if (isa<TemplateTypeParmDecl>(Param))
7277 continue;
7278
7279 // Rebuild the template parameter list of a template template parameter.
7280 if (TemplateTemplateParmDecl *TTP
7281 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
7282 if (RebuildTemplateParamsInCurrentInstantiation(
7283 TTP->getTemplateParameters()))
7284 return true;
7285
7286 continue;
7287 }
7288
7289 // Rebuild the type of a non-type template parameter.
7290 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
7291 TypeSourceInfo *NewTSI
7292 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
7293 NTTP->getLocation(),
7294 NTTP->getDeclName());
7295 if (!NewTSI)
7296 return true;
7297
7298 if (NewTSI != NTTP->getTypeSourceInfo()) {
7299 NTTP->setTypeSourceInfo(NewTSI);
7300 NTTP->setType(NewTSI->getType());
7301 }
7302 }
7303
7304 return false;
7305}
7306
Douglas Gregorbf4ea562009-09-15 16:23:51 +00007307/// \brief Produces a formatted string that describes the binding of
7308/// template parameters to template arguments.
7309std::string
7310Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7311 const TemplateArgumentList &Args) {
Douglas Gregor910f8002010-11-07 23:05:16 +00007312 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregor9148c3f2009-11-11 19:13:48 +00007313}
7314
7315std::string
7316Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7317 const TemplateArgument *Args,
7318 unsigned NumArgs) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007319 SmallString<128> Str;
Douglas Gregor87dd6972010-12-20 16:52:59 +00007320 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00007321
Douglas Gregor9148c3f2009-11-11 19:13:48 +00007322 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00007323 return std::string();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007324
Douglas Gregorbf4ea562009-09-15 16:23:51 +00007325 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00007326 if (I >= NumArgs)
7327 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007328
Douglas Gregorbf4ea562009-09-15 16:23:51 +00007329 if (I == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00007330 Out << "[with ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00007331 else
Douglas Gregor87dd6972010-12-20 16:52:59 +00007332 Out << ", ";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007333
Douglas Gregorbf4ea562009-09-15 16:23:51 +00007334 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00007335 Out << Id->getName();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00007336 } else {
Douglas Gregor87dd6972010-12-20 16:52:59 +00007337 Out << '$' << I;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00007338 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007339
Douglas Gregor87dd6972010-12-20 16:52:59 +00007340 Out << " = ";
Douglas Gregor8987b232011-09-27 23:30:47 +00007341 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00007342 }
Douglas Gregor87dd6972010-12-20 16:52:59 +00007343
7344 Out << ']';
7345 return Out.str();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00007346}
Francois Pichet8387e2a2011-04-22 22:18:13 +00007347
7348void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag) {
7349 if (!FD)
7350 return;
7351 FD->setLateTemplateParsed(Flag);
7352}
7353
7354bool Sema::IsInsideALocalClassWithinATemplateFunction() {
7355 DeclContext *DC = CurContext;
7356
7357 while (DC) {
7358 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
7359 const FunctionDecl *FD = RD->isLocalClass();
7360 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
7361 } else if (DC->isTranslationUnit() || DC->isNamespace())
7362 return false;
7363
7364 DC = DC->getParent();
7365 }
7366 return false;
7367}