blob: 64c3263805135b1498a2821fec2d94030196b90c [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
Douglas Gregor15acfb92009-08-06 16:20:37 +000012#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000013#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000015#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000019#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000020#include "clang/AST/TypeVisitor.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/DeclSpec.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/ParsedTemplate.h"
27#include "clang/Sema/Scope.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000031#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000032#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000033#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000034using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000036
John McCall9b72f892010-11-10 02:40:36 +000037// Exported for use by Parser.
38SourceRange
39clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
40 unsigned N) {
41 if (!N) return SourceRange();
42 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
43}
44
Douglas Gregorb7bfe792009-09-02 22:59:36 +000045/// \brief Determine whether the declaration found is acceptable as the name
46/// of a template and, if so, return that template declaration. Otherwise,
47/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000048static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000049 NamedDecl *Orig,
50 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000051 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000052
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000053 if (isa<TemplateDecl>(D)) {
54 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
55 return 0;
56
John McCalle9cccd82010-06-16 08:42:20 +000057 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000058 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregorb7bfe792009-09-02 22:59:36 +000060 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
61 // C++ [temp.local]p1:
62 // Like normal (non-template) classes, class templates have an
63 // injected-class-name (Clause 9). The injected-class-name
64 // can be used with or without a template-argument-list. When
65 // it is used without a template-argument-list, it is
66 // equivalent to the injected-class-name followed by the
67 // template-parameters of the class template enclosed in
68 // <>. When it is used with a template-argument-list, it
69 // refers to the specified class template specialization,
70 // which could be the current specialization or another
71 // specialization.
72 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000073 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000074 if (Record->getDescribedClassTemplate())
75 return Record->getDescribedClassTemplate();
76
77 if (ClassTemplateSpecializationDecl *Spec
78 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
79 return Spec->getSpecializedTemplate();
80 }
Mike Stump11289f42009-09-09 15:08:12 +000081
Douglas Gregorb7bfe792009-09-02 22:59:36 +000082 return 0;
83 }
Mike Stump11289f42009-09-09 15:08:12 +000084
Douglas Gregorb7bfe792009-09-02 22:59:36 +000085 return 0;
86}
87
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000088void Sema::FilterAcceptableTemplateNames(LookupResult &R,
89 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +000090 // The set of class templates we've already seen.
91 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000092 LookupResult::Filter filter = R.makeFilter();
93 while (filter.hasNext()) {
94 NamedDecl *Orig = filter.next();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000095 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
96 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +000097 if (!Repl)
98 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000099 else if (Repl != Orig) {
100
101 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000102 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000103 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000104 // one base class). If all of the injected-class-names that are found
105 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000106 // is used as a template-name, the reference refers to the class
107 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000108 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000109 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
110 if (!ClassTemplates.insert(ClassTmpl)) {
111 filter.erase();
112 continue;
113 }
John McCallbd8062d2010-08-13 07:02:08 +0000114
115 // FIXME: we promote access to public here as a workaround to
116 // the fact that LookupResult doesn't let us remember that we
117 // found this template through a particular injected class name,
118 // which means we end up doing nasty things to the invariants.
119 // Pretending that access is public is *much* safer.
120 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000121 }
John McCalle66edc12009-11-24 19:00:30 +0000122 }
123 filter.done();
124}
125
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000126bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
127 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000128 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000129 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000130 return true;
131
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000132 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000133}
134
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000135TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000136 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000137 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000138 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000139 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000140 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000141 TemplateTy &TemplateResult,
142 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000143 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000144
Douglas Gregor3cf81312009-11-03 23:16:33 +0000145 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000146 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000147
Douglas Gregor3cf81312009-11-03 23:16:33 +0000148 switch (Name.getKind()) {
149 case UnqualifiedId::IK_Identifier:
150 TName = DeclarationName(Name.Identifier);
151 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000152
Douglas Gregor3cf81312009-11-03 23:16:33 +0000153 case UnqualifiedId::IK_OperatorFunctionId:
154 TName = Context.DeclarationNames.getCXXOperatorName(
155 Name.OperatorFunctionId.Operator);
156 break;
157
Alexis Hunted0530f2009-11-28 08:58:14 +0000158 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000159 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
160 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000161
Douglas Gregor3cf81312009-11-03 23:16:33 +0000162 default:
163 return TNK_Non_template;
164 }
Mike Stump11289f42009-09-09 15:08:12 +0000165
John McCallba7bf592010-08-24 05:47:05 +0000166 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000167
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000168 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000169 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
170 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000171 if (R.empty()) return TNK_Non_template;
172 if (R.isAmbiguous()) {
173 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000174 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000175
176 // FIXME: we might have ambiguous templates, in which case we
177 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000178 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000179 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000180
John McCalld28ae272009-12-02 08:04:21 +0000181 TemplateName Template;
182 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000183
John McCalld28ae272009-12-02 08:04:21 +0000184 unsigned ResultCount = R.end() - R.begin();
185 if (ResultCount > 1) {
186 // We assume that we'll preserve the qualifier from a function
187 // template name in other ways.
188 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
189 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000190
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000193 } else {
John McCalld28ae272009-12-02 08:04:21 +0000194 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
195
196 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000197 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000198 Template = Context.getQualifiedTemplateName(Qualifier,
199 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000200 } else {
201 Template = TemplateName(TD);
202 }
203
John McCalldcc71402010-08-13 02:23:42 +0000204 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000205 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000206
207 // We'll do this lookup again later.
208 R.suppressDiagnostics();
209 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000210 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
Larisse Voufo39a1e502013-08-06 01:03:05 +0000211 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD));
212 TemplateKind =
213 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000214 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
John McCalld28ae272009-12-02 08:04:21 +0000217 TemplateResult = TemplateTy::make(Template);
218 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000219}
220
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000221bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000222 SourceLocation IILoc,
223 Scope *S,
224 const CXXScopeSpec *SS,
225 TemplateTy &SuggestedTemplate,
226 TemplateNameKind &SuggestedKind) {
227 // We can't recover unless there's a dependent scope specifier preceding the
228 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000229 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000230 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
231 computeDeclContext(*SS))
232 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000233
Douglas Gregor18473f32010-01-12 21:28:44 +0000234 // The code is missing a 'template' keyword prior to the dependent template
235 // name.
236 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
237 Diag(IILoc, diag::err_template_kw_missing)
238 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000239 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000240 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000241 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
242 SuggestedKind = TNK_Dependent_template_name;
243 return true;
244}
245
John McCalle66edc12009-11-24 19:00:30 +0000246void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000247 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000248 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000249 bool EnteringContext,
250 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000251 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000252 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-11-24 19:00:30 +0000253 DeclContext *LookupCtx = 0;
254 bool isDependent = false;
255 if (!ObjectType.isNull()) {
256 // This nested-name-specifier occurs in a member access expression, e.g.,
257 // x->B::f, and we are looking into the type of the object.
258 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
259 LookupCtx = computeDeclContext(ObjectType);
260 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000261 assert((isDependent || !ObjectType->isIncompleteType() ||
262 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000263 "Caller should have completed object type");
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000264
265 // Template names cannot appear inside an Objective-C class or object type.
266 if (ObjectType->isObjCObjectOrInterfaceType()) {
267 Found.clear();
268 return;
269 }
John McCalle66edc12009-11-24 19:00:30 +0000270 } else if (SS.isSet()) {
271 // This nested-name-specifier occurs after another nested-name-specifier,
272 // so long into the context associated with the prior nested-name-specifier.
273 LookupCtx = computeDeclContext(SS, EnteringContext);
274 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000275
John McCalle66edc12009-11-24 19:00:30 +0000276 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000277 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000278 return;
279 }
280
281 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000282 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000283 if (LookupCtx) {
284 // Perform "qualified" name lookup into the declaration context we
285 // computed, which is either the type of the base of a member access
286 // expression or the declaration context associated with a prior
287 // nested-name-specifier.
288 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000289 if (!ObjectType.isNull() && Found.empty()) {
290 // C++ [basic.lookup.classref]p1:
291 // In a class member access expression (5.2.5), if the . or -> token is
292 // immediately followed by an identifier followed by a <, the
293 // identifier must be looked up to determine whether the < is the
294 // beginning of a template argument list (14.2) or a less-than operator.
295 // The identifier is first looked up in the class of the object
296 // expression. If the identifier is not found, it is then looked up in
297 // the context of the entire postfix-expression and shall name a class
298 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000299 if (S) LookupName(Found, S);
300 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000301 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000302 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000303 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000304 // We cannot look into a dependent object type or nested nme
305 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000306 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000307 return;
308 } else {
309 // Perform unqualified name lookup in the current scope.
310 LookupName(Found, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000311
312 if (!ObjectType.isNull())
313 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000314 }
315
Douglas Gregorc119dd52010-01-12 17:06:20 +0000316 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000317 // If we did not find any names, attempt to correct any typos.
318 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000319 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000320 // Simple filter callback that, for keywords, only accepts the C++ *_cast
321 CorrectionCandidateCallback FilterCCC;
322 FilterCCC.WantTypeSpecifiers = false;
323 FilterCCC.WantExpressionKeywords = false;
324 FilterCCC.WantRemainingKeywords = false;
325 FilterCCC.WantCXXNamedCasts = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000326 if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(),
327 Found.getLookupKind(), S, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +0000328 FilterCCC, CTK_ErrorRecovery,
329 LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000330 Found.setLookupName(Corrected.getCorrection());
331 if (Corrected.getCorrectionDecl())
332 Found.addDecl(Corrected.getCorrectionDecl());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000333 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000334 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000335 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000336 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
337 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000338 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000339 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
340 << Name << LookupCtx << DroppedSpecifier
341 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000342 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000343 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000344 }
John McCalle9cccd82010-06-16 08:42:20 +0000345 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000346 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000347 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000348 }
349 }
350
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000351 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000352 if (Found.empty()) {
353 if (isDependent)
354 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000355 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000356 }
John McCalle66edc12009-11-24 19:00:30 +0000357
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000358 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000359 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000360 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000361 // [...] If the lookup in the class of the object expression finds a
362 // template, the name is also looked up in the context of the entire
363 // postfix-expression and [...]
364 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000365 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000366 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
367 LookupOrdinaryName);
368 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000369 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000370
John McCalle66edc12009-11-24 19:00:30 +0000371 if (FoundOuter.empty()) {
372 // - if the name is not found, the name found in the class of the
373 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000374 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
375 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000376 // - if the name is found in the context of the entire
377 // postfix-expression and does not name a class template, the name
378 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000379 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000380 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000381 // - if the name found is a class template, it must refer to the same
382 // entity as the one found in the class of the object expression,
383 // otherwise the program is ill-formed.
384 if (!Found.isSingleResult() ||
385 Found.getFoundDecl()->getCanonicalDecl()
386 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000387 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000388 diag::ext_nested_name_member_ref_lookup_ambiguous)
389 << Found.getLookupName()
390 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000391 Diag(Found.getRepresentativeDecl()->getLocation(),
392 diag::note_ambig_member_ref_object_type)
393 << ObjectType;
394 Diag(FoundOuter.getFoundDecl()->getLocation(),
395 diag::note_ambig_member_ref_scope);
396
397 // Recover by taking the template that we found in the object
398 // expression's type.
399 }
400 }
401 }
402}
403
John McCallcd4b4772009-12-02 03:53:29 +0000404/// ActOnDependentIdExpression - Handle a dependent id-expression that
405/// was just parsed. This is only possible with an explicit scope
406/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000407ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000408Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000409 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000410 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000411 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000412 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000413 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000414
John McCallcd4b4772009-12-02 03:53:29 +0000415 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000416 isa<CXXMethodDecl>(DC) &&
417 cast<CXXMethodDecl>(DC)->isInstance()) {
418 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000419
John McCalle66edc12009-11-24 19:00:30 +0000420 // Since the 'this' expression is synthesized, we don't need to
421 // perform the double-lookup check.
422 NamedDecl *FirstQualifierInScope = 0;
423
John McCall2d74de92009-12-01 22:10:20 +0000424 return Owned(CXXDependentScopeMemberExpr::Create(Context,
425 /*This*/ 0, ThisType,
426 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000427 /*Op*/ SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +0000428 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000429 TemplateKWLoc,
John McCalle66edc12009-11-24 19:00:30 +0000430 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000431 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000432 TemplateArgs));
433 }
434
Abramo Bagnara7945c982012-01-27 09:46:47 +0000435 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000436}
437
John McCalldadc5752010-08-24 06:29:42 +0000438ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000439Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000440 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000441 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000442 const TemplateArgumentListInfo *TemplateArgs) {
443 return Owned(DependentScopeDeclRefExpr::Create(Context,
Douglas Gregor3a43fd62011-02-25 20:49:16 +0000444 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000445 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000446 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000447 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000448}
449
Douglas Gregor5101c242008-12-05 18:15:24 +0000450/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
451/// that the template parameter 'PrevDecl' is being shadowed by a new
452/// declaration at location Loc. Returns true to indicate that this is
453/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000454void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000455 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000456
457 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000458 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000459 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000460
461 // C++ [temp.local]p4:
462 // A template-parameter shall not be redeclared within its
463 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000464 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000465 << cast<NamedDecl>(PrevDecl)->getDeclName();
466 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000467 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000468}
469
Douglas Gregor463421d2009-03-03 04:44:36 +0000470/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000471/// the parameter D to reference the templated declaration and return a pointer
472/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000473TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
474 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
475 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000476 return Temp;
477 }
478 return 0;
479}
480
Douglas Gregoreb29d182011-01-05 17:40:24 +0000481ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
482 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000483 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000484 "Only template template arguments can be pack expansions here");
485 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
486 "Template template argument pack expansion without packs");
487 ParsedTemplateArgument Result(*this);
488 Result.EllipsisLoc = EllipsisLoc;
489 return Result;
490}
491
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000492static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
493 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000494
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000495 switch (Arg.getKind()) {
496 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000497 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000498 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000499 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000500 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000501 return TemplateArgumentLoc(TemplateArgument(T), DI);
502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000504 case ParsedTemplateArgument::NonType: {
505 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
506 return TemplateArgumentLoc(TemplateArgument(E), E);
507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000508
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000509 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000510 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000511 TemplateArgument TArg;
512 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000513 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000514 else
515 TArg = Template;
516 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000517 Arg.getScopeSpec().getWithLocInContext(
518 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000519 Arg.getLocation(),
520 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000521 }
522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000523
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000524 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000525}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000526
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000527/// \brief Translates template arguments as provided by the parser
528/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000529void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
530 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000531 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000532 TemplateArgs.addArgument(translateTemplateArgument(*this,
533 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000534}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000535
Richard Smithb80d5402013-06-25 22:21:36 +0000536static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
537 SourceLocation Loc,
538 IdentifierInfo *Name) {
539 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
540 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
541 if (PrevDecl && PrevDecl->isTemplateParameter())
542 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
543}
544
Douglas Gregor5101c242008-12-05 18:15:24 +0000545/// ActOnTypeParameter - Called when a C++ template type parameter
546/// (e.g., "typename T") has been parsed. Typename specifies whether
547/// the keyword "typename" was used to declare the type parameter
548/// (otherwise, "class" was used), and KeyLoc is the location of the
549/// "class" or "typename" keyword. ParamName is the name of the
550/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000551/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000552/// If the type parameter has a default argument, it will be added
553/// later via ActOnTypeParameterDefault.
John McCall48871652010-08-21 09:40:31 +0000554Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
555 SourceLocation EllipsisLoc,
556 SourceLocation KeyLoc,
557 IdentifierInfo *ParamName,
558 SourceLocation ParamNameLoc,
559 unsigned Depth, unsigned Position,
560 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000561 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000562 assert(S->isTemplateParamScope() &&
563 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000564 bool Invalid = false;
565
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000566 SourceLocation Loc = ParamNameLoc;
567 if (!ParamName)
568 Loc = KeyLoc;
569
Douglas Gregor5101c242008-12-05 18:15:24 +0000570 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000571 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000572 KeyLoc, Loc, Depth, Position, ParamName,
573 Typename, Ellipsis);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000574 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000575 if (Invalid)
576 Param->setInvalidDecl();
577
578 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000579 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
580
Douglas Gregor5101c242008-12-05 18:15:24 +0000581 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000582 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000583 IdResolver.AddDecl(Param);
584 }
585
Douglas Gregorf5500772011-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 Gregordc13ded2010-07-01 00:00:45 +0000594 // Handle the default argument, if provided.
595 if (DefaultArg) {
596 TypeSourceInfo *DefaultTInfo;
597 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
Douglas Gregordc13ded2010-07-01 00:00:45 +0000599 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000601 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000602 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000603 UPPC_DefaultArgument))
604 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregordc13ded2010-07-01 00:00:45 +0000606 // Check the template argument itself.
607 if (CheckTemplateArgument(Param, DefaultTInfo)) {
608 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000609 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000610 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000611
Douglas Gregordc13ded2010-07-01 00:00:45 +0000612 Param->setDefaultArgument(DefaultTInfo, false);
613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614
John McCall48871652010-08-21 09:40:31 +0000615 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000616}
617
Douglas Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000623QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000624Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-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 Gregor463421d2009-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 Gregorb90df602010-06-16 00:17:44 +0000639 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000640 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000641 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000642 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000643 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000644 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000645 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000646 // -- std::nullptr_t.
647 T->isNullPtrType() ||
Douglas Gregor463421d2009-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 Smithd0e1c952012-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 Gregor463421d2009-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 Takumif9cbcc42011-01-27 07:10:08 +0000667
Douglas Gregor463421d2009-03-03 04:44:36 +0000668 Diag(Loc, diag::err_template_nontype_parm_bad_type)
669 << T;
670
671 return QualType();
672}
673
John McCall48871652010-08-21 09:40:31 +0000674Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
675 unsigned Depth,
676 unsigned Position,
677 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000678 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000679 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
680 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000681
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000682 assert(S->isTemplateParamScope() &&
683 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000684 bool Invalid = false;
685
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000686 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
687 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000688 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000689 Invalid = true;
690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691
Richard Smithb80d5402013-06-25 22:21:36 +0000692 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000693 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000694 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000695 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000696 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000697 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000699 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000700 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000701
Douglas Gregor5101c242008-12-05 18:15:24 +0000702 if (Invalid)
703 Param->setInvalidDecl();
704
Richard Smithb80d5402013-06-25 22:21:36 +0000705 if (ParamName) {
706 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
707 ParamName);
708
Douglas Gregor5101c242008-12-05 18:15:24 +0000709 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000710 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000711 IdResolver.AddDecl(Param);
712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000713
Douglas Gregorf5500772011-01-05 15:48:55 +0000714 // C++0x [temp.param]p9:
715 // A default template-argument may be specified for any kind of
716 // template-parameter that is not a template parameter pack.
717 if (Default && IsParameterPack) {
718 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
719 Default = 0;
720 }
721
Douglas Gregordc13ded2010-07-01 00:00:45 +0000722 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000723 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000724 // Check for unexpanded parameter packs.
725 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
726 return Param;
727
Douglas Gregordc13ded2010-07-01 00:00:45 +0000728 TemplateArgument Converted;
John Wiegley01296292011-04-08 18:41:53 +0000729 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
730 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000731 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000732 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000733 }
John Wiegley01296292011-04-08 18:41:53 +0000734 Default = DefaultRes.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
John McCallb268a282010-08-23 23:25:46 +0000736 Param->setDefaultArgument(Default, false);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000738
John McCall48871652010-08-21 09:40:31 +0000739 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000740}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000741
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000742/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000743/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000744/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000745Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
746 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000747 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000748 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000749 IdentifierInfo *Name,
750 SourceLocation NameLoc,
751 unsigned Depth,
752 unsigned Position,
753 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000754 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000755 assert(S->isTemplateParamScope() &&
756 "Template template parameter not in template parameter scope!");
757
758 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000759 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000760 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000761 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762 NameLoc.isInvalid()? TmpLoc : NameLoc,
763 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000764 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000765 Param->setAccess(AS_public);
766
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000767 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000768 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000769 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000770 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
771
John McCall48871652010-08-21 09:40:31 +0000772 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000773 IdResolver.AddDecl(Param);
774 }
775
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000776 if (Params->size() == 0) {
777 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
778 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
779 Param->setInvalidDecl();
780 }
781
Douglas Gregorf5500772011-01-05 15:48:55 +0000782 // C++0x [temp.param]p9:
783 // A default template-argument may be specified for any kind of
784 // template-parameter that is not a template parameter pack.
785 if (IsParameterPack && !Default.isInvalid()) {
786 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
787 Default = ParsedTemplateArgument();
788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789
Douglas Gregordc13ded2010-07-01 00:00:45 +0000790 if (!Default.isInvalid()) {
791 // Check only that we have a template template argument. We don't want to
792 // try to check well-formedness now, because our template template parameter
793 // might have dependent types in its template parameters, which we wouldn't
794 // be able to match now.
795 //
796 // If none of the template template parameter's template arguments mention
797 // other template parameters, we could actually perform more checking here.
798 // However, it isn't worth doing.
799 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
800 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
801 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
802 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000803 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000805
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000806 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000807 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000808 DefaultArg.getArgument().getAsTemplate(),
809 UPPC_DefaultArgument))
810 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811
Douglas Gregordc13ded2010-07-01 00:00:45 +0000812 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000814
John McCall48871652010-08-21 09:40:31 +0000815 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000816}
817
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000818/// ActOnTemplateParameterList - Builds a TemplateParameterList that
819/// contains the template parameters in Params/NumParams.
Richard Trieu9becef62011-09-09 03:18:59 +0000820TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000821Sema::ActOnTemplateParameterList(unsigned Depth,
822 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000823 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000824 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000825 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000826 SourceLocation RAngleLoc) {
827 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000828 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000829
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000830 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000831 (NamedDecl**)Params, NumParams,
Douglas Gregorbe999392009-09-15 16:23:51 +0000832 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000833}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000834
John McCall3e11ebe2010-03-15 10:12:16 +0000835static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
836 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000837 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000838}
839
John McCallfaf5fb42010-08-26 23:41:50 +0000840DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000841Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000842 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000843 IdentifierInfo *Name, SourceLocation NameLoc,
844 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000845 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000846 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000847 unsigned NumOuterTemplateParamLists,
848 TemplateParameterList** OuterTemplateParamLists) {
Mike Stump11289f42009-09-09 15:08:12 +0000849 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000850 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000851 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000852 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000853
854 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000855 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000856 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000857
Abramo Bagnara6150c882010-05-11 21:36:43 +0000858 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
859 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000860
861 // There is no such thing as an unnamed class template.
862 if (!Name) {
863 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000864 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000865 }
866
Richard Smith6483d222012-04-21 01:27:54 +0000867 // Find any previous declaration with this name. For a friend with no
868 // scope explicitly specified, we only look for tag declarations (per
869 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000870 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000871 LookupResult Previous(*this, Name, NameLoc,
872 (SS.isEmpty() && TUK == TUK_Friend)
873 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000874 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000875 if (SS.isNotEmpty() && !SS.isInvalid()) {
876 SemanticContext = computeDeclContext(SS, true);
877 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000878 // FIXME: Horrible, horrible hack! We can't currently represent this
879 // in the AST, and historically we have just ignored such friend
880 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000881 Diag(NameLoc, TUK == TUK_Friend
882 ? diag::warn_template_qualified_friend_ignored
883 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000884 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000885 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000886 }
Mike Stump11289f42009-09-09 15:08:12 +0000887
John McCall0b66eb32010-05-01 00:40:08 +0000888 if (RequireCompleteDeclContext(SS, SemanticContext))
889 return true;
890
Douglas Gregor041b0842011-10-14 15:31:12 +0000891 // If we're adding a template to a dependent context, we may need to
892 // rebuilding some of the types used within the template parameter list,
893 // now that we know what the current instantiation is.
894 if (SemanticContext->isDependentContext()) {
895 ContextRAII SavedContext(*this, SemanticContext);
896 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
897 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000898 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
899 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000900
John McCall27b18f82009-11-17 02:14:36 +0000901 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000902 } else {
903 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000904 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000905 }
Mike Stump11289f42009-09-09 15:08:12 +0000906
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000907 if (Previous.isAmbiguous())
908 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000909
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000910 NamedDecl *PrevDecl = 0;
911 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000912 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000913
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000914 // If there is a previous declaration with the same name, check
915 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000916 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000917 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000918
919 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000920 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000921 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000922 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000923 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
924 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000925 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000926 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
927 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
928 PrevClassTemplate
929 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
930 ->getSpecializedTemplate();
931 }
932 }
933
John McCalld43784f2009-12-18 11:25:59 +0000934 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000935 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000936 // [...] When looking for a prior declaration of a class or a function
937 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000938 // function is neither a qualified name nor a template-id, scopes outside
939 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000940 if (!SS.isSet()) {
941 DeclContext *OutermostContext = CurContext;
942 while (!OutermostContext->isFileContext())
943 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000944
Richard Smith61e582f2012-04-20 07:12:26 +0000945 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000946 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
947 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
948 SemanticContext = PrevDecl->getDeclContext();
949 } else {
950 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000951 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000952 // declaration.
953 PrevDecl = PrevClassTemplate = 0;
954 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000955
956 // Check that the chosen semantic context doesn't already contain a
957 // declaration of this name as a non-tag type.
958 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
959 ForRedeclaration);
960 DeclContext *LookupContext = SemanticContext;
961 while (LookupContext->isTransparentContext())
962 LookupContext = LookupContext->getLookupParent();
963 LookupQualifiedName(Previous, LookupContext);
964
965 if (Previous.isAmbiguous())
966 return true;
967
968 if (Previous.begin() != Previous.end())
969 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000970 }
John McCall90d3bb92009-12-17 23:21:11 +0000971 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000972 } else if (PrevDecl &&
973 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
John McCall90d3bb92009-12-17 23:21:11 +0000974 PrevDecl = PrevClassTemplate = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000975
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000976 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +0000977 // Ensure that the template parameter lists are compatible. Skip this check
978 // for a friend in a dependent context: the template parameter list itself
979 // could be dependent.
980 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
981 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000982 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000983 /*Complain=*/true,
984 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000985 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000986
987 // C++ [temp.class]p4:
988 // In a redeclaration, partial specialization, explicit
989 // specialization or explicit instantiation of a class template,
990 // the class-key shall agree in kind with the original class
991 // template declaration (7.1.5.3).
992 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +0000993 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
994 TUK == TUK_Definition, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000995 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000996 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000997 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000998 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000999 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001000 }
1001
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001002 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001003 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001004 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001005 Diag(NameLoc, diag::err_redefinition) << Name;
1006 Diag(Def->getLocation(), diag::note_previous_definition);
1007 // FIXME: Would it make sense to try to "forget" the previous
1008 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001009 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001010 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001011 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001012 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1013 // Maybe we will complain about the shadowed template parameter.
1014 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1015 // Just pretend that we didn't see the previous declaration.
1016 PrevDecl = 0;
1017 } else if (PrevDecl) {
1018 // C++ [temp]p5:
1019 // A class template shall not have the same name as any other
1020 // template, class, function, object, enumeration, enumerator,
1021 // namespace, or type in the same scope (3.3), except as specified
1022 // in (14.5.4).
1023 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1024 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001025 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001026 }
1027
Douglas Gregordba32632009-02-10 19:49:53 +00001028 // Check the template parameter list of this declaration, possibly
1029 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001030 // template declaration. Skip this check for a friend in a dependent
1031 // context, because the template parameter list might be dependent.
1032 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001033 CheckTemplateParameterList(
1034 TemplateParams,
1035 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters() : 0,
1036 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1037 SemanticContext->isDependentContext())
1038 ? TPC_ClassTemplateMember
1039 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1040 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001041 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001042
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001043 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001045 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001046 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1047 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001048 : diag::err_member_decl_does_not_match)
1049 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001050 Invalid = true;
1051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001052 }
1053
Mike Stump11289f42009-09-09 15:08:12 +00001054 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001055 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001056 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001057 PrevClassTemplate->getTemplatedDecl() : 0,
1058 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001059 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001060 if (NumOuterTemplateParamLists > 0)
1061 NewClass->setTemplateParameterListsInfo(Context,
1062 NumOuterTemplateParamLists,
1063 OuterTemplateParamLists);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001064
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001065 // Add alignment attributes if necessary; these attributes are checked when
1066 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001067 if (TUK == TUK_Definition) {
1068 AddAlignmentAttributesForRecord(NewClass);
1069 AddMsStructLayoutForRecord(NewClass);
1070 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001071
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001072 ClassTemplateDecl *NewTemplate
1073 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1074 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001075 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001076 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001077
Douglas Gregor21823bf2011-12-20 18:11:52 +00001078 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001079 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001080
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001081 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001082 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001083 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001084 assert(T->isDependentType() && "Class template type is not dependent?");
1085 (void)T;
1086
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001087 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001088 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001089 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001090 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1091 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001092
Anders Carlsson137108d2009-03-26 01:24:28 +00001093 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001094 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001095 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001096
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001097 // Set the lexical context of these templates
1098 NewClass->setLexicalDeclContext(CurContext);
1099 NewTemplate->setLexicalDeclContext(CurContext);
1100
John McCall9bb74a52009-07-31 02:45:11 +00001101 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001102 NewClass->startDefinition();
1103
1104 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001105 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001106
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001107 if (PrevClassTemplate)
1108 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1109
Rafael Espindola385c0422012-07-13 18:04:45 +00001110 AddPushedVisibilityAttribute(NewClass);
1111
John McCall27b5c252009-09-14 21:59:20 +00001112 if (TUK != TUK_Friend)
1113 PushOnScopeChains(NewTemplate, S);
1114 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001115 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001116 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001117 NewClass->setAccess(PrevClassTemplate->getAccess());
1118 }
John McCall27b5c252009-09-14 21:59:20 +00001119
Richard Smith64017682013-07-17 23:53:16 +00001120 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001121
John McCall27b5c252009-09-14 21:59:20 +00001122 // Friend templates are visible in fairly strange ways.
1123 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001124 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001125 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001126 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1127 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001128 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001130
Douglas Gregor3dad8422009-09-26 06:47:28 +00001131 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1132 NewClass->getLocation(),
1133 NewTemplate,
1134 /*FIXME:*/NewClass->getLocation());
1135 Friend->setAccess(AS_public);
1136 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001137 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001138
Douglas Gregordba32632009-02-10 19:49:53 +00001139 if (Invalid) {
1140 NewTemplate->setInvalidDecl();
1141 NewClass->setInvalidDecl();
1142 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001143
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001144 ActOnDocumentableDecl(NewTemplate);
1145
John McCall48871652010-08-21 09:40:31 +00001146 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001147}
1148
Douglas Gregored5731f2009-11-25 17:50:39 +00001149/// \brief Diagnose the presence of a default template argument on a
1150/// template parameter, which is ill-formed in certain contexts.
1151///
1152/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001153static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001154 Sema::TemplateParamListContext TPC,
1155 SourceLocation ParamLoc,
1156 SourceRange DefArgRange) {
1157 switch (TPC) {
1158 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001159 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001160 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001161 return false;
1162
1163 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001164 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001165 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001166 // A default template-argument shall not be specified in a
1167 // function template declaration or a function template
1168 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001169 // If a friend function template declaration specifies a default
1170 // template-argument, that declaration shall be a definition and shall be
1171 // the only declaration of the function template in the translation unit.
1172 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001173 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001174 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1175 : diag::ext_template_parameter_default_in_function_template)
1176 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001177 return false;
1178
1179 case Sema::TPC_ClassTemplateMember:
1180 // C++0x [temp.param]p9:
1181 // A default template-argument shall not be specified in the
1182 // template-parameter-lists of the definition of a member of a
1183 // class template that appears outside of the member's class.
1184 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1185 << DefArgRange;
1186 return true;
1187
David Majnemerba8f17a2013-06-25 22:08:55 +00001188 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001189 case Sema::TPC_FriendFunctionTemplate:
1190 // C++ [temp.param]p9:
1191 // A default template-argument shall not be specified in a
1192 // friend template declaration.
1193 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1194 << DefArgRange;
1195 return true;
1196
1197 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1198 // for friend function templates if there is only a single
1199 // declaration (and it is a definition). Strange!
1200 }
1201
David Blaikie8a40f702012-01-17 06:56:22 +00001202 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001203}
1204
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001205/// \brief Check for unexpanded parameter packs within the template parameters
1206/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001207static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1208 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001209 // A template template parameter which is a parameter pack is also a pack
1210 // expansion.
1211 if (TTP->isParameterPack())
1212 return false;
1213
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001214 TemplateParameterList *Params = TTP->getTemplateParameters();
1215 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1216 NamedDecl *P = Params->getParam(I);
1217 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001218 if (!NTTP->isParameterPack() &&
1219 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001220 NTTP->getTypeSourceInfo(),
1221 Sema::UPPC_NonTypeTemplateParameterType))
1222 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001223
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001224 continue;
1225 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001226
1227 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001228 = dyn_cast<TemplateTemplateParmDecl>(P))
1229 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1230 return true;
1231 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001232
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001233 return false;
1234}
1235
Douglas Gregordba32632009-02-10 19:49:53 +00001236/// \brief Checks the validity of a template parameter list, possibly
1237/// considering the template parameter list from a previous
1238/// declaration.
1239///
1240/// If an "old" template parameter list is provided, it must be
1241/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1242/// template parameter list.
1243///
1244/// \param NewParams Template parameter list for a new template
1245/// declaration. This template parameter list will be updated with any
1246/// default arguments that are carried through from the previous
1247/// template parameter list.
1248///
1249/// \param OldParams If provided, template parameter list from a
1250/// previous declaration of the same template. Default template
1251/// arguments will be merged from the old template parameter list to
1252/// the new template parameter list.
1253///
Douglas Gregored5731f2009-11-25 17:50:39 +00001254/// \param TPC Describes the context in which we are checking the given
1255/// template parameter list.
1256///
Douglas Gregordba32632009-02-10 19:49:53 +00001257/// \returns true if an error occurred, false otherwise.
1258bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001259 TemplateParameterList *OldParams,
1260 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001261 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001262
Douglas Gregordba32632009-02-10 19:49:53 +00001263 // C++ [temp.param]p10:
1264 // The set of default template-arguments available for use with a
1265 // template declaration or definition is obtained by merging the
1266 // default arguments from the definition (if in scope) and all
1267 // declarations in scope in the same way default function
1268 // arguments are (8.3.6).
1269 bool SawDefaultArgument = false;
1270 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001271
Mike Stumpc89c8e32009-02-11 23:03:27 +00001272 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001273 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001274 if (OldParams)
1275 OldParam = OldParams->begin();
1276
Douglas Gregor0693def2011-01-27 01:40:17 +00001277 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001278 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1279 NewParamEnd = NewParams->end();
1280 NewParam != NewParamEnd; ++NewParam) {
1281 // Variables used to diagnose redundant default arguments
1282 bool RedundantDefaultArg = false;
1283 SourceLocation OldDefaultLoc;
1284 SourceLocation NewDefaultLoc;
1285
David Blaikie651c73c2011-10-19 05:19:50 +00001286 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001287 bool MissingDefaultArg = false;
1288
David Blaikie651c73c2011-10-19 05:19:50 +00001289 // Variable used to diagnose non-final parameter packs
1290 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001291
Douglas Gregordba32632009-02-10 19:49:53 +00001292 if (TemplateTypeParmDecl *NewTypeParm
1293 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001294 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001295 if (NewTypeParm->hasDefaultArgument() &&
1296 DiagnoseDefaultTemplateArgument(*this, TPC,
1297 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001298 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001299 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001300 NewTypeParm->removeDefaultArgument();
1301
1302 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001303 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001304 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001305
Anders Carlsson327865d2009-06-12 23:20:15 +00001306 if (NewTypeParm->isParameterPack()) {
1307 assert(!NewTypeParm->hasDefaultArgument() &&
1308 "Parameter packs can't have a default argument!");
1309 SawParameterPack = true;
Mike Stump11289f42009-09-09 15:08:12 +00001310 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001311 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001312 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1313 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1314 SawDefaultArgument = true;
1315 RedundantDefaultArg = true;
1316 PreviousDefaultArgLoc = NewDefaultLoc;
1317 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1318 // Merge the default argument from the old declaration to the
1319 // new declaration.
John McCall0ad16662009-10-29 08:12:44 +00001320 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001321 true);
1322 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1323 } else if (NewTypeParm->hasDefaultArgument()) {
1324 SawDefaultArgument = true;
1325 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1326 } else if (SawDefaultArgument)
1327 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001328 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001329 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001330 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001331 if (!NewNonTypeParm->isParameterPack() &&
1332 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001333 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001334 UPPC_NonTypeTemplateParameterType)) {
1335 Invalid = true;
1336 continue;
1337 }
1338
Douglas Gregored5731f2009-11-25 17:50:39 +00001339 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001340 if (NewNonTypeParm->hasDefaultArgument() &&
1341 DiagnoseDefaultTemplateArgument(*this, TPC,
1342 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001343 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001344 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001345 }
1346
Mike Stump12b8ce12009-08-04 21:02:39 +00001347 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001348 NonTypeTemplateParmDecl *OldNonTypeParm
1349 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001350 if (NewNonTypeParm->isParameterPack()) {
1351 assert(!NewNonTypeParm->hasDefaultArgument() &&
1352 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001353 if (!NewNonTypeParm->isPackExpansion())
1354 SawParameterPack = true;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001355 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Richard Smith35828f12013-07-22 03:31:14 +00001356 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001357 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1358 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1359 SawDefaultArgument = true;
1360 RedundantDefaultArg = true;
1361 PreviousDefaultArgLoc = NewDefaultLoc;
1362 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1363 // Merge the default argument from the old declaration to the
1364 // new declaration.
Douglas Gregordba32632009-02-10 19:49:53 +00001365 // FIXME: We need to create a new kind of "default argument"
Douglas Gregorf5500772011-01-05 15:48:55 +00001366 // expression that points to a previous non-type template
Douglas Gregordba32632009-02-10 19:49:53 +00001367 // parameter.
1368 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001369 OldNonTypeParm->getDefaultArgument(),
1370 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001371 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1372 } else if (NewNonTypeParm->hasDefaultArgument()) {
1373 SawDefaultArgument = true;
1374 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1375 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001376 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001377 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001378 TemplateTemplateParmDecl *NewTemplateParm
1379 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001380
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001381 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001382 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001383 Invalid = true;
1384 continue;
1385 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001386
David Blaikie651c73c2011-10-19 05:19:50 +00001387 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001388 if (NewTemplateParm->hasDefaultArgument() &&
1389 DiagnoseDefaultTemplateArgument(*this, TPC,
1390 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001391 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001392 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001393
1394 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001395 TemplateTemplateParmDecl *OldTemplateParm
1396 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001397 if (NewTemplateParm->isParameterPack()) {
1398 assert(!NewTemplateParm->hasDefaultArgument() &&
1399 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001400 if (!NewTemplateParm->isPackExpansion())
1401 SawParameterPack = true;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001402 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001403 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001404 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1405 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001406 SawDefaultArgument = true;
1407 RedundantDefaultArg = true;
1408 PreviousDefaultArgLoc = NewDefaultLoc;
1409 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1410 // Merge the default argument from the old declaration to the
1411 // new declaration.
Mike Stump87c57ac2009-05-16 07:39:55 +00001412 // FIXME: We need to create a new kind of "default argument" expression
1413 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001414 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001415 OldTemplateParm->getDefaultArgument(),
1416 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001417 PreviousDefaultArgLoc
1418 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001419 } else if (NewTemplateParm->hasDefaultArgument()) {
1420 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001421 PreviousDefaultArgLoc
1422 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001423 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001424 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001425 }
1426
Richard Smith1fde8ec2012-09-07 02:06:42 +00001427 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001428 // If a template parameter of a primary class template or alias template
1429 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001430 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001431 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1432 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001433 Diag((*NewParam)->getLocation(),
1434 diag::err_template_param_pack_must_be_last_template_parameter);
1435 Invalid = true;
1436 }
1437
Douglas Gregordba32632009-02-10 19:49:53 +00001438 if (RedundantDefaultArg) {
1439 // C++ [temp.param]p12:
1440 // A template-parameter shall not be given default arguments
1441 // by two different declarations in the same scope.
1442 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1443 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1444 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001445 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001446 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001447 // If a template-parameter of a class template has a default
1448 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001449 // have a default template-argument supplied or be a template parameter
1450 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001451 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001452 diag::err_template_param_default_arg_missing);
1453 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1454 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001455 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001456 }
1457
1458 // If we have an old template parameter list that we're merging
1459 // in, move on to the next parameter.
1460 if (OldParams)
1461 ++OldParam;
1462 }
1463
Douglas Gregor0693def2011-01-27 01:40:17 +00001464 // We were missing some default arguments at the end of the list, so remove
1465 // all of the default arguments.
1466 if (RemoveDefaultArguments) {
1467 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1468 NewParamEnd = NewParams->end();
1469 NewParam != NewParamEnd; ++NewParam) {
1470 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1471 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001472 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001473 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1474 NTTP->removeDefaultArgument();
1475 else
1476 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1477 }
1478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001479
Douglas Gregordba32632009-02-10 19:49:53 +00001480 return Invalid;
1481}
Douglas Gregord32e0282009-02-09 23:23:08 +00001482
John McCalla020a012010-10-20 05:44:58 +00001483namespace {
1484
1485/// A class which looks for a use of a certain level of template
1486/// parameter.
1487struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1488 typedef RecursiveASTVisitor<DependencyChecker> super;
1489
1490 unsigned Depth;
1491 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001492 SourceLocation MatchLoc;
1493
1494 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001495
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
Richard Smith6056d5e2014-02-09 00:54:43 +00001508 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001509 if (ParmDepth >= Depth) {
1510 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001511 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001512 return true;
1513 }
1514 return false;
1515 }
1516
Richard Smith6056d5e2014-02-09 00:54:43 +00001517 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1518 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1519 }
1520
John McCalla020a012010-10-20 05:44:58 +00001521 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1522 return !Matches(T->getDepth());
1523 }
1524
1525 bool TraverseTemplateName(TemplateName N) {
1526 if (TemplateTemplateParmDecl *PD =
1527 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001528 if (Matches(PD->getDepth()))
1529 return false;
John McCalla020a012010-10-20 05:44:58 +00001530 return super::TraverseTemplateName(N);
1531 }
1532
1533 bool VisitDeclRefExpr(DeclRefExpr *E) {
1534 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001535 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1536 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001537 return false;
John McCalla020a012010-10-20 05:44:58 +00001538 return super::VisitDeclRefExpr(E);
1539 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001540
1541 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1542 return TraverseType(T->getReplacementType());
1543 }
1544
1545 bool
1546 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1547 return TraverseTemplateArgument(T->getArgumentPack());
1548 }
1549
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001550 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1551 return TraverseType(T->getInjectedSpecializationType());
1552 }
John McCalla020a012010-10-20 05:44:58 +00001553};
1554}
1555
Douglas Gregor972fe532011-05-10 18:27:06 +00001556/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001557/// list.
1558static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001559DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001560 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001561 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001562 return Checker.Match;
1563}
1564
Douglas Gregor972fe532011-05-10 18:27:06 +00001565// Find the source range corresponding to the named type in the given
1566// nested-name-specifier, if any.
1567static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1568 QualType T,
1569 const CXXScopeSpec &SS) {
1570 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1571 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1572 if (const Type *CurType = NNS->getAsType()) {
1573 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1574 return NNSLoc.getTypeLoc().getSourceRange();
1575 } else
1576 break;
1577
1578 NNSLoc = NNSLoc.getPrefix();
1579 }
1580
1581 return SourceRange();
1582}
1583
Mike Stump11289f42009-09-09 15:08:12 +00001584/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001585/// specifier, returning the template parameter list that applies to the
1586/// name.
1587///
1588/// \param DeclStartLoc the start of the declaration that has a scope
1589/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001590///
Douglas Gregor972fe532011-05-10 18:27:06 +00001591/// \param DeclLoc The location of the declaration itself.
1592///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001593/// \param SS the scope specifier that will be matched to the given template
1594/// parameter lists. This scope specifier precedes a qualified name that is
1595/// being declared.
1596///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001597/// \param TemplateId The template-id following the scope specifier, if there
1598/// is one. Used to check for a missing 'template<>'.
1599///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001600/// \param ParamLists the template parameter lists, from the outermost to the
1601/// innermost template parameter lists.
1602///
John McCalle820e5e2010-04-13 20:37:33 +00001603/// \param IsFriend Whether to apply the slightly different rules for
1604/// matching template parameters to scope specifiers in friend
1605/// declarations.
1606///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001607/// \param IsExplicitSpecialization will be set true if the entity being
1608/// declared is an explicit specialization, false otherwise.
1609///
Mike Stump11289f42009-09-09 15:08:12 +00001610/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001611/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001612/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001613/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001614/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001615/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001616TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1617 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001618 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001619 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1620 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001621 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001622 Invalid = false;
1623
1624 // The sequence of nested types to which we will match up the template
1625 // parameter lists. We first build this list by starting with the type named
1626 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001627 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001628 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001629 if (SS.getScopeRep()) {
1630 if (CXXRecordDecl *Record
1631 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1632 T = Context.getTypeDeclType(Record);
1633 else
1634 T = QualType(SS.getScopeRep()->getAsType(), 0);
1635 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001636
1637 // If we found an explicit specialization that prevents us from needing
1638 // 'template<>' headers, this will be set to the location of that
1639 // explicit specialization.
1640 SourceLocation ExplicitSpecLoc;
1641
1642 while (!T.isNull()) {
1643 NestedTypes.push_back(T);
1644
1645 // Retrieve the parent of a record type.
1646 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1647 // If this type is an explicit specialization, we're done.
1648 if (ClassTemplateSpecializationDecl *Spec
1649 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1650 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1651 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1652 ExplicitSpecLoc = Spec->getLocation();
1653 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001654 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001655 } else if (Record->getTemplateSpecializationKind()
1656 == TSK_ExplicitSpecialization) {
1657 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001658 break;
1659 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001660
1661 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1662 T = Context.getTypeDeclType(Parent);
1663 else
1664 T = QualType();
1665 continue;
1666 }
1667
1668 if (const TemplateSpecializationType *TST
1669 = T->getAs<TemplateSpecializationType>()) {
1670 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1671 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1672 T = Context.getTypeDeclType(Parent);
1673 else
1674 T = QualType();
1675 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001676 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001677 }
1678
1679 // Look one step prior in a dependent template specialization type.
1680 if (const DependentTemplateSpecializationType *DependentTST
1681 = T->getAs<DependentTemplateSpecializationType>()) {
1682 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1683 T = QualType(NNS->getAsType(), 0);
1684 else
1685 T = QualType();
1686 continue;
1687 }
1688
1689 // Look one step prior in a dependent name type.
1690 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1691 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1692 T = QualType(NNS->getAsType(), 0);
1693 else
1694 T = QualType();
1695 continue;
1696 }
1697
1698 // Retrieve the parent of an enumeration type.
1699 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1700 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1701 // check here.
1702 EnumDecl *Enum = EnumT->getDecl();
1703
1704 // Get to the parent type.
1705 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1706 T = Context.getTypeDeclType(Parent);
1707 else
1708 T = QualType();
1709 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001710 }
Mike Stump11289f42009-09-09 15:08:12 +00001711
Douglas Gregor972fe532011-05-10 18:27:06 +00001712 T = QualType();
1713 }
1714 // Reverse the nested types list, since we want to traverse from the outermost
1715 // to the innermost while checking template-parameter-lists.
1716 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001717
Douglas Gregor972fe532011-05-10 18:27:06 +00001718 // C++0x [temp.expl.spec]p17:
1719 // A member or a member template may be nested within many
1720 // enclosing class templates. In an explicit specialization for
1721 // such a member, the member declaration shall be preceded by a
1722 // template<> for each enclosing class template that is
1723 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001724 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001725
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001726 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001727 if (SawNonEmptyTemplateParameterList) {
1728 Diag(DeclLoc, diag::err_specialize_member_of_template)
1729 << !Recovery << Range;
1730 Invalid = true;
1731 IsExplicitSpecialization = false;
1732 return true;
1733 }
1734
1735 return false;
1736 };
1737
1738 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1739 // Check that we can have an explicit specialization here.
1740 if (CheckExplicitSpecialization(Range, true))
1741 return true;
1742
1743 // We don't have a template header, but we should.
1744 SourceLocation ExpectedTemplateLoc;
1745 if (!ParamLists.empty())
1746 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1747 else
1748 ExpectedTemplateLoc = DeclStartLoc;
1749
1750 Diag(DeclLoc, diag::err_template_spec_needs_header)
1751 << Range
1752 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1753 return false;
1754 };
1755
Douglas Gregor972fe532011-05-10 18:27:06 +00001756 unsigned ParamIdx = 0;
1757 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1758 ++TypeIdx) {
1759 T = NestedTypes[TypeIdx];
1760
1761 // Whether we expect a 'template<>' header.
1762 bool NeedEmptyTemplateHeader = false;
1763
1764 // Whether we expect a template header with parameters.
1765 bool NeedNonemptyTemplateHeader = false;
1766
1767 // For a dependent type, the set of template parameters that we
1768 // expect to see.
1769 TemplateParameterList *ExpectedTemplateParams = 0;
1770
Douglas Gregor373af9b2011-05-11 23:26:17 +00001771 // C++0x [temp.expl.spec]p15:
1772 // A member or a member template may be nested within many enclosing
1773 // class templates. In an explicit specialization for such a member, the
1774 // member declaration shall be preceded by a template<> for each
1775 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001776 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1777 if (ClassTemplatePartialSpecializationDecl *Partial
1778 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1779 ExpectedTemplateParams = Partial->getTemplateParameters();
1780 NeedNonemptyTemplateHeader = true;
1781 } else if (Record->isDependentType()) {
1782 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001783 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001784 ->getTemplateParameters();
1785 NeedNonemptyTemplateHeader = true;
1786 }
1787 } else if (ClassTemplateSpecializationDecl *Spec
1788 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1789 // C++0x [temp.expl.spec]p4:
1790 // Members of an explicitly specialized class template are defined
1791 // in the same manner as members of normal classes, and not using
1792 // the template<> syntax.
1793 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1794 NeedEmptyTemplateHeader = true;
1795 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001796 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001797 } else if (Record->getTemplateSpecializationKind()) {
1798 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001799 != TSK_ExplicitSpecialization &&
1800 TypeIdx == NumTypes - 1)
1801 IsExplicitSpecialization = true;
1802
1803 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001804 }
1805 } else if (const TemplateSpecializationType *TST
1806 = T->getAs<TemplateSpecializationType>()) {
1807 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1808 ExpectedTemplateParams = Template->getTemplateParameters();
1809 NeedNonemptyTemplateHeader = true;
1810 }
1811 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1812 // FIXME: We actually could/should check the template arguments here
1813 // against the corresponding template parameter list.
1814 NeedNonemptyTemplateHeader = false;
1815 }
1816
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001817 // C++ [temp.expl.spec]p16:
1818 // In an explicit specialization declaration for a member of a class
1819 // template or a member template that ap- pears in namespace scope, the
1820 // member template and some of its enclosing class templates may remain
1821 // unspecialized, except that the declaration shall not explicitly
1822 // specialize a class member template if its en- closing class templates
1823 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001824 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001825 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001826 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1827 false))
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001828 return 0;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001829 } else
1830 SawNonEmptyTemplateParameterList = true;
1831 }
1832
Douglas Gregor972fe532011-05-10 18:27:06 +00001833 if (NeedEmptyTemplateHeader) {
1834 // If we're on the last of the types, and we need a 'template<>' header
1835 // here, then it's an explicit specialization.
1836 if (TypeIdx == NumTypes - 1)
1837 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001838
1839 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001840 if (ParamLists[ParamIdx]->size() > 0) {
1841 // The header has template parameters when it shouldn't. Complain.
1842 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1843 diag::err_template_param_list_matches_nontemplate)
1844 << T
1845 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1846 ParamLists[ParamIdx]->getRAngleLoc())
1847 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1848 Invalid = true;
1849 return 0;
1850 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001851
Douglas Gregor972fe532011-05-10 18:27:06 +00001852 // Consume this template header.
1853 ++ParamIdx;
1854 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001855 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001856
1857 if (!IsFriend)
1858 if (DiagnoseMissingExplicitSpecialization(
1859 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
1860 return 0;
1861
Douglas Gregor972fe532011-05-10 18:27:06 +00001862 continue;
1863 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001864
Douglas Gregor972fe532011-05-10 18:27:06 +00001865 if (NeedNonemptyTemplateHeader) {
1866 // In friend declarations we can have template-ids which don't
1867 // depend on the corresponding template parameter lists. But
1868 // assume that empty parameter lists are supposed to match this
1869 // template-id.
1870 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001871 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001872 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1873 ExpectedTemplateParams = 0;
1874 else
1875 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001876 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001877
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001878 if (ParamIdx < ParamLists.size()) {
1879 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001880 if (ExpectedTemplateParams &&
1881 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1882 ExpectedTemplateParams,
1883 true, TPL_TemplateMatch))
1884 Invalid = true;
1885
1886 if (!Invalid &&
1887 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1888 TPC_ClassTemplateMember))
1889 Invalid = true;
1890
1891 ++ParamIdx;
1892 continue;
1893 }
1894
1895 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1896 << T
1897 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1898 Invalid = true;
1899 continue;
1900 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001901 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001902
Douglas Gregord8d297c2009-07-21 23:53:31 +00001903 // If there were at least as many template-ids as there were template
1904 // parameter lists, then there are no template parameter lists remaining for
1905 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001906 if (ParamIdx >= ParamLists.size()) {
1907 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001908 // We don't have a template header for the declaration itself, but we
1909 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001910 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001911 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1912 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001913
1914 // Fabricate an empty template parameter list for the invented header.
1915 return TemplateParameterList::Create(Context, SourceLocation(),
1916 SourceLocation(), 0, 0,
1917 SourceLocation());
1918 }
1919
Douglas Gregord8d297c2009-07-21 23:53:31 +00001920 return 0;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001921 }
Mike Stump11289f42009-09-09 15:08:12 +00001922
Douglas Gregord8d297c2009-07-21 23:53:31 +00001923 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001924 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001925 bool HasAnyExplicitSpecHeader = false;
1926 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001927 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001928 if (ParamLists[I]->size() == 0)
1929 HasAnyExplicitSpecHeader = true;
1930 else
1931 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001932 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001933
Douglas Gregor972fe532011-05-10 18:27:06 +00001934 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001935 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1936 : diag::err_template_spec_extra_headers)
1937 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1938 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001939
1940 // If there was a specialization somewhere, such that 'template<>' is
1941 // not required, and there were any 'template<>' headers, note where the
1942 // specialization occurred.
1943 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1944 Diag(ExplicitSpecLoc,
1945 diag::note_explicit_template_spec_does_not_need_header)
1946 << NestedTypes.back();
1947
1948 // We have a template parameter list with no corresponding scope, which
1949 // means that the resulting template declaration can't be instantiated
1950 // properly (we'll end up with dependent nodes when we shouldn't).
1951 if (!AllExplicitSpecHeaders)
1952 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001953 }
Mike Stump11289f42009-09-09 15:08:12 +00001954
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001955 // C++ [temp.expl.spec]p16:
1956 // In an explicit specialization declaration for a member of a class
1957 // template or a member template that ap- pears in namespace scope, the
1958 // member template and some of its enclosing class templates may remain
1959 // unspecialized, except that the declaration shall not explicitly
1960 // specialize a class member template if its en- closing class templates
1961 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00001962 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001963 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1964 false))
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001965 return 0;
Richard Smith11a80dc2014-04-17 03:52:20 +00001966
Douglas Gregord8d297c2009-07-21 23:53:31 +00001967 // Return the last template parameter list, which corresponds to the
1968 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001969 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001970}
1971
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001972void Sema::NoteAllFoundTemplates(TemplateName Name) {
1973 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1974 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00001975 << (isa<FunctionTemplateDecl>(Template)
1976 ? 0
1977 : isa<ClassTemplateDecl>(Template)
1978 ? 1
1979 : isa<VarTemplateDecl>(Template)
1980 ? 2
1981 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1982 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001983 return;
1984 }
1985
1986 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1987 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1988 IEnd = OST->end();
1989 I != IEnd; ++I)
1990 Diag((*I)->getLocation(), diag::note_template_declared_here)
1991 << 0 << (*I)->getDeclName();
1992
1993 return;
1994 }
1995}
1996
Douglas Gregordc572a32009-03-30 22:58:21 +00001997QualType Sema::CheckTemplateIdType(TemplateName Name,
1998 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00001999 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002000 DependentTemplateName *DTN
2001 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002002 if (DTN && DTN->isIdentifier())
2003 // When building a template-id where the template-name is dependent,
2004 // assume the template is a type template. Either our assumption is
2005 // correct, or the code is ill-formed and will be diagnosed when the
2006 // dependent name is substituted.
2007 return Context.getDependentTemplateSpecializationType(ETK_None,
2008 DTN->getQualifier(),
2009 DTN->getIdentifier(),
2010 TemplateArgs);
2011
Douglas Gregordc572a32009-03-30 22:58:21 +00002012 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002013 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2014 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002015 // We might have a substituted template template parameter pack. If so,
2016 // build a template specialization type for it.
2017 if (Name.getAsSubstTemplateTemplateParmPack())
2018 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002019
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002020 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2021 << Name;
2022 NoteAllFoundTemplates(Name);
2023 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002024 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002025
Douglas Gregorc40290e2009-03-09 23:48:35 +00002026 // Check that the template argument list is well-formed for this
2027 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002028 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002029 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002030 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002031 return QualType();
2032
Douglas Gregorc40290e2009-03-09 23:48:35 +00002033 QualType CanonType;
2034
Douglas Gregor678d76c2011-07-01 01:22:09 +00002035 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002036 if (TypeAliasTemplateDecl *AliasTemplate =
2037 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002038 // Find the canonical type for this type alias template specialization.
2039 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2040 if (Pattern->isInvalidDecl())
2041 return QualType();
2042
2043 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2044 Converted.data(), Converted.size());
2045
2046 // Only substitute for the innermost template argument list.
2047 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002048 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002049 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2050 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002051 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002052
Richard Smith802c4b72012-08-23 06:16:52 +00002053 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002054 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002055 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002056 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002057
Richard Smith3f1b5d02011-05-05 21:57:07 +00002058 CanonType = SubstType(Pattern->getUnderlyingType(),
2059 TemplateArgLists, AliasTemplate->getLocation(),
2060 AliasTemplate->getDeclName());
2061 if (CanonType.isNull())
2062 return QualType();
2063 } else if (Name.isDependent() ||
2064 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002065 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002066 // This class template specialization is a dependent
2067 // type. Therefore, its canonical type is another class template
2068 // specialization type that contains all of the converted
2069 // arguments in canonical form. This ensures that, e.g., A<T> and
2070 // A<T, T> have identical types when A is declared as:
2071 //
2072 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002073 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002074 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002075 Converted.data(),
2076 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002077
Douglas Gregora8e02e72009-07-28 23:00:59 +00002078 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002079 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002080 // In the future, we need to teach getTemplateSpecializationType to only
2081 // build the canonical type and return that to us.
2082 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002083
2084 // This might work out to be a current instantiation, in which
2085 // case the canonical type needs to be the InjectedClassNameType.
2086 //
2087 // TODO: in theory this could be a simple hashtable lookup; most
2088 // changes to CurContext don't change the set of current
2089 // instantiations.
2090 if (isa<ClassTemplateDecl>(Template)) {
2091 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2092 // If we get out to a namespace, we're done.
2093 if (Ctx->isFileContext()) break;
2094
2095 // If this isn't a record, keep looking.
2096 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2097 if (!Record) continue;
2098
2099 // Look for one of the two cases with InjectedClassNameTypes
2100 // and check whether it's the same template.
2101 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2102 !Record->getDescribedClassTemplate())
2103 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002104
John McCall2408e322010-04-27 00:57:59 +00002105 // Fetch the injected class name type and check whether its
2106 // injected type is equal to the type we just built.
2107 QualType ICNT = Context.getTypeDeclType(Record);
2108 QualType Injected = cast<InjectedClassNameType>(ICNT)
2109 ->getInjectedSpecializationType();
2110
2111 if (CanonType != Injected->getCanonicalTypeInternal())
2112 continue;
2113
2114 // If so, the canonical type of this TST is the injected
2115 // class name type of the record we just found.
2116 assert(ICNT.isCanonical());
2117 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002118 break;
2119 }
2120 }
Mike Stump11289f42009-09-09 15:08:12 +00002121 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002122 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002123 // Find the class template specialization declaration that
2124 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002125 void *InsertPos = 0;
2126 ClassTemplateSpecializationDecl *Decl
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002127 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002128 InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002129 if (!Decl) {
2130 // This is the first time we have referenced this class template
2131 // specialization. Create the canonical declaration and add it to
2132 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002133 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002134 ClassTemplate->getTemplatedDecl()->getTagKind(),
2135 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002136 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002137 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002138 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002139 Converted.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002140 Converted.size(), 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002141 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002142 if (ClassTemplate->isOutOfLine())
2143 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002144 }
2145
Chandler Carruth2acfb222013-09-27 22:14:40 +00002146 // Diagnose uses of this specialization.
2147 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2148
Douglas Gregorc40290e2009-03-09 23:48:35 +00002149 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002150 assert(isa<RecordType>(CanonType) &&
2151 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00002152 }
Mike Stump11289f42009-09-09 15:08:12 +00002153
Douglas Gregorc40290e2009-03-09 23:48:35 +00002154 // Build the fully-sugared type for this class template
2155 // specialization, which refers back to the class template
2156 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002157 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002158}
2159
John McCallfaf5fb42010-08-26 23:41:50 +00002160TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002161Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002162 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002163 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002164 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002165 SourceLocation RAngleLoc,
2166 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002167 if (SS.isInvalid())
2168 return true;
2169
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002170 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002171
Douglas Gregorc40290e2009-03-09 23:48:35 +00002172 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002173 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002174 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002175
Douglas Gregor5a064722011-02-28 17:23:35 +00002176 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002177 QualType T
2178 = Context.getDependentTemplateSpecializationType(ETK_None,
2179 DTN->getQualifier(),
2180 DTN->getIdentifier(),
2181 TemplateArgs);
2182 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002183 TypeLocBuilder TLB;
2184 DependentTemplateSpecializationTypeLoc SpecTL
2185 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002186 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2187 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002188 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002189 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002190 SpecTL.setLAngleLoc(LAngleLoc);
2191 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002192 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2193 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2194 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2195 }
2196
John McCall6b51f282009-11-23 01:53:49 +00002197 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002198
2199 if (Result.isNull())
2200 return true;
2201
Douglas Gregore7c20652011-03-02 00:47:37 +00002202 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002203 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002204 TemplateSpecializationTypeLoc SpecTL
2205 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002206 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002207 SpecTL.setTemplateNameLoc(TemplateLoc);
2208 SpecTL.setLAngleLoc(LAngleLoc);
2209 SpecTL.setRAngleLoc(RAngleLoc);
2210 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2211 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002212
Abramo Bagnara4244b432012-01-27 08:46:19 +00002213 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2214 // constructor or destructor name (in such a case, the scope specifier
2215 // will be attached to the enclosing Decl or Expr node).
2216 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002217 // Create an elaborated-type-specifier containing the nested-name-specifier.
2218 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2219 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002220 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002221 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2222 }
2223
2224 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002225}
John McCall06f6fe8d2009-09-04 01:14:41 +00002226
Douglas Gregore7c20652011-03-02 00:47:37 +00002227TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002228 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002229 SourceLocation TagLoc,
2230 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002231 SourceLocation TemplateKWLoc,
2232 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002233 SourceLocation TemplateLoc,
2234 SourceLocation LAngleLoc,
2235 ASTTemplateArgsPtr TemplateArgsIn,
2236 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002237 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002238
2239 // Translate the parser's template argument list in our AST format.
2240 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2241 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2242
2243 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002244 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002245 ElaboratedTypeKeyword Keyword
2246 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002247
Douglas Gregore7c20652011-03-02 00:47:37 +00002248 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2249 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2250 DTN->getQualifier(),
2251 DTN->getIdentifier(),
2252 TemplateArgs);
2253
2254 // Build type-source information.
2255 TypeLocBuilder TLB;
2256 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002257 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2258 SpecTL.setElaboratedKeywordLoc(TagLoc);
2259 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002260 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002261 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002262 SpecTL.setLAngleLoc(LAngleLoc);
2263 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002264 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2265 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2266 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2267 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002268
2269 if (TypeAliasTemplateDecl *TAT =
2270 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2271 // C++0x [dcl.type.elab]p2:
2272 // If the identifier resolves to a typedef-name or the simple-template-id
2273 // resolves to an alias template specialization, the
2274 // elaborated-type-specifier is ill-formed.
2275 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2276 Diag(TAT->getLocation(), diag::note_declared_at);
2277 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002278
2279 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2280 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002281 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002282
2283 // Check the tag kind
2284 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002285 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002286
John McCalld8fe9af2009-09-08 17:47:29 +00002287 IdentifierInfo *Id = D->getIdentifier();
2288 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002289
Richard Trieucaa33d32011-06-10 03:11:26 +00002290 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2291 TagLoc, *Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002292 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002293 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002294 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002295 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002296 }
2297 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002298
Douglas Gregore7c20652011-03-02 00:47:37 +00002299 // Provide source-location information for the template specialization.
2300 TypeLocBuilder TLB;
2301 TemplateSpecializationTypeLoc SpecTL
2302 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002303 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002304 SpecTL.setTemplateNameLoc(TemplateLoc);
2305 SpecTL.setLAngleLoc(LAngleLoc);
2306 SpecTL.setRAngleLoc(RAngleLoc);
2307 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2308 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002309
Douglas Gregore7c20652011-03-02 00:47:37 +00002310 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002311 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002312 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2313 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002314 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002315 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2316 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002317}
2318
Larisse Voufo39a1e502013-08-06 01:03:05 +00002319static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002320 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2321 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002322
2323static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2324 NamedDecl *PrevDecl,
2325 SourceLocation Loc,
2326 bool IsPartialSpecialization);
2327
2328static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002329
Richard Smith300e0c32013-09-24 04:49:23 +00002330static bool isTemplateArgumentTemplateParameter(
2331 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2332 switch (Arg.getKind()) {
2333 case TemplateArgument::Null:
2334 case TemplateArgument::NullPtr:
2335 case TemplateArgument::Integral:
2336 case TemplateArgument::Declaration:
2337 case TemplateArgument::Pack:
2338 case TemplateArgument::TemplateExpansion:
2339 return false;
2340
2341 case TemplateArgument::Type: {
2342 QualType Type = Arg.getAsType();
2343 const TemplateTypeParmType *TPT =
2344 Arg.getAsType()->getAs<TemplateTypeParmType>();
2345 return TPT && !Type.hasQualifiers() &&
2346 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2347 }
2348
2349 case TemplateArgument::Expression: {
2350 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2351 if (!DRE || !DRE->getDecl())
2352 return false;
2353 const NonTypeTemplateParmDecl *NTTP =
2354 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2355 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2356 }
2357
2358 case TemplateArgument::Template:
2359 const TemplateTemplateParmDecl *TTP =
2360 dyn_cast_or_null<TemplateTemplateParmDecl>(
2361 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2362 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2363 }
2364 llvm_unreachable("unexpected kind of template argument");
2365}
2366
2367static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2368 ArrayRef<TemplateArgument> Args) {
2369 if (Params->size() != Args.size())
2370 return false;
2371
2372 unsigned Depth = Params->getDepth();
2373
2374 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2375 TemplateArgument Arg = Args[I];
2376
2377 // If the parameter is a pack expansion, the argument must be a pack
2378 // whose only element is a pack expansion.
2379 if (Params->getParam(I)->isParameterPack()) {
2380 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2381 !Arg.pack_begin()->isPackExpansion())
2382 return false;
2383 Arg = Arg.pack_begin()->getPackExpansionPattern();
2384 }
2385
2386 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2387 return false;
2388 }
2389
2390 return true;
2391}
2392
Richard Smith4b55a9c2014-04-17 03:29:33 +00002393/// Convert the parser's template argument list representation into our form.
2394static TemplateArgumentListInfo
2395makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2396 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2397 TemplateId.RAngleLoc);
2398 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2399 TemplateId.NumArgs);
2400 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2401 return TemplateArgs;
2402}
2403
Larisse Voufo39a1e502013-08-06 01:03:05 +00002404DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002405 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2406 TemplateParameterList *TemplateParams, VarDecl::StorageClass SC,
2407 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002408 // D must be variable template id.
2409 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2410 "Variable template specialization is declared with a template it.");
2411
2412 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002413 TemplateArgumentListInfo TemplateArgs =
2414 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002415 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2416 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2417 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002418
Richard Smithbeef3452014-01-16 23:39:20 +00002419 TemplateName Name = TemplateId->Template.get();
2420
2421 // The template-id must name a variable template.
2422 VarTemplateDecl *VarTemplate =
2423 dyn_cast<VarTemplateDecl>(Name.getAsTemplateDecl());
2424 if (!VarTemplate)
2425 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2426 << IsPartialSpecialization;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002427
2428 // Check for unexpanded parameter packs in any of the template arguments.
2429 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2430 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2431 UPPC_PartialSpecialization))
2432 return true;
2433
2434 // Check that the template argument list is well-formed for this
2435 // template.
2436 SmallVector<TemplateArgument, 4> Converted;
2437 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2438 false, Converted))
2439 return true;
2440
2441 // Check that the type of this variable template specialization
2442 // matches the expected type.
2443 TypeSourceInfo *ExpectedDI;
2444 {
2445 // Do substitution on the type of the declaration
2446 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2447 Converted.data(), Converted.size());
2448 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002449 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002450 return true;
2451 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2452 ExpectedDI =
2453 SubstType(Templated->getTypeSourceInfo(),
2454 MultiLevelTemplateArgumentList(TemplateArgList),
2455 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2456 }
2457 if (!ExpectedDI)
2458 return true;
2459
Larisse Voufo39a1e502013-08-06 01:03:05 +00002460 // Find the variable template (partial) specialization declaration that
2461 // corresponds to these arguments.
2462 if (IsPartialSpecialization) {
2463 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002464 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2465 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002466 return true;
2467
2468 bool InstantiationDependent;
2469 if (!Name.isDependent() &&
2470 !TemplateSpecializationType::anyDependentTemplateArguments(
2471 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2472 InstantiationDependent)) {
2473 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2474 << VarTemplate->getDeclName();
2475 IsPartialSpecialization = false;
2476 }
Richard Smith300e0c32013-09-24 04:49:23 +00002477
2478 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2479 Converted)) {
2480 // C++ [temp.class.spec]p9b3:
2481 //
2482 // -- The argument list of the specialization shall not be identical
2483 // to the implicit argument list of the primary template.
2484 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2485 << /*variable template*/ 1
2486 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2487 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2488 // FIXME: Recover from this by treating the declaration as a redeclaration
2489 // of the primary template.
2490 return true;
2491 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002492 }
2493
2494 void *InsertPos = 0;
2495 VarTemplateSpecializationDecl *PrevDecl = 0;
2496
2497 if (IsPartialSpecialization)
2498 // FIXME: Template parameter list matters too
2499 PrevDecl = VarTemplate->findPartialSpecialization(
2500 Converted.data(), Converted.size(), InsertPos);
2501 else
2502 PrevDecl = VarTemplate->findSpecialization(Converted.data(),
2503 Converted.size(), InsertPos);
2504
2505 VarTemplateSpecializationDecl *Specialization = 0;
2506
2507 // Check whether we can declare a variable template specialization in
2508 // the current scope.
2509 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2510 TemplateNameLoc,
2511 IsPartialSpecialization))
2512 return true;
2513
2514 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2515 // Since the only prior variable template specialization with these
2516 // arguments was referenced but not declared, reuse that
2517 // declaration node as our own, updating its source location and
2518 // the list of outer template parameters to reflect our new declaration.
2519 Specialization = PrevDecl;
2520 Specialization->setLocation(TemplateNameLoc);
2521 PrevDecl = 0;
2522 } else if (IsPartialSpecialization) {
2523 // Create a new class template partial specialization declaration node.
2524 VarTemplatePartialSpecializationDecl *PrevPartial =
2525 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002526 VarTemplatePartialSpecializationDecl *Partial =
2527 VarTemplatePartialSpecializationDecl::Create(
2528 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2529 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002530 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002531
2532 if (!PrevPartial)
2533 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2534 Specialization = Partial;
2535
2536 // If we are providing an explicit specialization of a member variable
2537 // template specialization, make a note of that.
2538 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002539 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002540
2541 // Check that all of the template parameters of the variable template
2542 // partial specialization are deducible from the template
2543 // arguments. If not, this variable template partial specialization
2544 // will never be used.
2545 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2546 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2547 TemplateParams->getDepth(), DeducibleParams);
2548
2549 if (!DeducibleParams.all()) {
2550 unsigned NumNonDeducible =
2551 DeducibleParams.size() - DeducibleParams.count();
2552 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002553 << /*variable template*/ 1 << (NumNonDeducible > 1)
2554 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002555 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2556 if (!DeducibleParams[I]) {
2557 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2558 if (Param->getDeclName())
2559 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2560 << Param->getDeclName();
2561 else
2562 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002563 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002564 }
2565 }
2566 }
2567 } else {
2568 // Create a new class template specialization declaration node for
2569 // this explicit specialization or friend declaration.
2570 Specialization = VarTemplateSpecializationDecl::Create(
2571 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2572 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2573 Specialization->setTemplateArgsInfo(TemplateArgs);
2574
2575 if (!PrevDecl)
2576 VarTemplate->AddSpecialization(Specialization, InsertPos);
2577 }
2578
2579 // C++ [temp.expl.spec]p6:
2580 // If a template, a member template or the member of a class template is
2581 // explicitly specialized then that specialization shall be declared
2582 // before the first use of that specialization that would cause an implicit
2583 // instantiation to take place, in every translation unit in which such a
2584 // use occurs; no diagnostic is required.
2585 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2586 bool Okay = false;
2587 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2588 // Is there any previous explicit specialization declaration?
2589 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2590 Okay = true;
2591 break;
2592 }
2593 }
2594
2595 if (!Okay) {
2596 SourceRange Range(TemplateNameLoc, RAngleLoc);
2597 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2598 << Name << Range;
2599
2600 Diag(PrevDecl->getPointOfInstantiation(),
2601 diag::note_instantiation_required_here)
2602 << (PrevDecl->getTemplateSpecializationKind() !=
2603 TSK_ImplicitInstantiation);
2604 return true;
2605 }
2606 }
2607
2608 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2609 Specialization->setLexicalDeclContext(CurContext);
2610
2611 // Add the specialization into its lexical context, so that it can
2612 // be seen when iterating through the list of declarations in that
2613 // context. However, specializations are not found by name lookup.
2614 CurContext->addDecl(Specialization);
2615
2616 // Note that this is an explicit specialization.
2617 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2618
2619 if (PrevDecl) {
2620 // Check that this isn't a redefinition of this specialization,
2621 // merging with previous declarations.
2622 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2623 ForRedeclaration);
2624 PrevSpec.addDecl(PrevDecl);
2625 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002626 } else if (Specialization->isStaticDataMember() &&
2627 Specialization->isOutOfLine()) {
2628 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002629 }
2630
2631 // Link instantiations of static data members back to the template from
2632 // which they were instantiated.
2633 if (Specialization->isStaticDataMember())
2634 Specialization->setInstantiationOfStaticDataMember(
2635 VarTemplate->getTemplatedDecl(),
2636 Specialization->getSpecializationKind());
2637
2638 return Specialization;
2639}
2640
2641namespace {
2642/// \brief A partial specialization whose template arguments have matched
2643/// a given template-id.
2644struct PartialSpecMatchResult {
2645 VarTemplatePartialSpecializationDecl *Partial;
2646 TemplateArgumentList *Args;
2647};
2648}
2649
2650DeclResult
2651Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2652 SourceLocation TemplateNameLoc,
2653 const TemplateArgumentListInfo &TemplateArgs) {
2654 assert(Template && "A variable template id without template?");
2655
2656 // Check that the template argument list is well-formed for this template.
2657 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002658 if (CheckTemplateArgumentList(
2659 Template, TemplateNameLoc,
2660 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002661 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002662 return true;
2663
2664 // Find the variable template specialization declaration that
2665 // corresponds to these arguments.
2666 void *InsertPos = 0;
2667 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2668 Converted.data(), Converted.size(), InsertPos))
2669 // If we already have a variable template specialization, return it.
2670 return Spec;
2671
2672 // This is the first time we have referenced this variable template
2673 // specialization. Create the canonical declaration and add it to
2674 // the set of specializations, based on the closest partial specialization
2675 // that it represents. That is,
2676 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2677 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2678 Converted.data(), Converted.size());
2679 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2680 bool AmbiguousPartialSpec = false;
2681 typedef PartialSpecMatchResult MatchResult;
2682 SmallVector<MatchResult, 4> Matched;
2683 SourceLocation PointOfInstantiation = TemplateNameLoc;
2684 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2685
2686 // 1. Attempt to find the closest partial specialization that this
2687 // specializes, if any.
2688 // If any of the template arguments is dependent, then this is probably
2689 // a placeholder for an incomplete declarative context; which must be
2690 // complete by instantiation time. Thus, do not search through the partial
2691 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002692 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2693 // Perhaps better after unification of DeduceTemplateArguments() and
2694 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002695 bool InstantiationDependent = false;
2696 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2697 TemplateArgs, InstantiationDependent)) {
2698
2699 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2700 Template->getPartialSpecializations(PartialSpecs);
2701
2702 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2703 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2704 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2705
2706 if (TemplateDeductionResult Result =
2707 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2708 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002709 // TODO: Actually use the failed-deduction info?
Larisse Voufo39a1e502013-08-06 01:03:05 +00002710 FailedCandidates.addCandidate()
2711 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2712 (void)Result;
2713 } else {
2714 Matched.push_back(PartialSpecMatchResult());
2715 Matched.back().Partial = Partial;
2716 Matched.back().Args = Info.take();
2717 }
2718 }
2719
Larisse Voufo39a1e502013-08-06 01:03:05 +00002720 if (Matched.size() >= 1) {
2721 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2722 if (Matched.size() == 1) {
2723 // -- If exactly one matching specialization is found, the
2724 // instantiation is generated from that specialization.
2725 // We don't need to do anything for this.
2726 } else {
2727 // -- If more than one matching specialization is found, the
2728 // partial order rules (14.5.4.2) are used to determine
2729 // whether one of the specializations is more specialized
2730 // than the others. If none of the specializations is more
2731 // specialized than all of the other matching
2732 // specializations, then the use of the variable template is
2733 // ambiguous and the program is ill-formed.
2734 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2735 PEnd = Matched.end();
2736 P != PEnd; ++P) {
2737 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2738 PointOfInstantiation) ==
2739 P->Partial)
2740 Best = P;
2741 }
2742
2743 // Determine if the best partial specialization is more specialized than
2744 // the others.
2745 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2746 PEnd = Matched.end();
2747 P != PEnd; ++P) {
2748 if (P != Best && getMoreSpecializedPartialSpecialization(
2749 P->Partial, Best->Partial,
2750 PointOfInstantiation) != Best->Partial) {
2751 AmbiguousPartialSpec = true;
2752 break;
2753 }
2754 }
2755 }
2756
2757 // Instantiate using the best variable template partial specialization.
2758 InstantiationPattern = Best->Partial;
2759 InstantiationArgs = Best->Args;
2760 } else {
2761 // -- If no match is found, the instantiation is generated
2762 // from the primary template.
2763 // InstantiationPattern = Template->getTemplatedDecl();
2764 }
2765 }
2766
Larisse Voufo39a1e502013-08-06 01:03:05 +00002767 // 2. Create the canonical declaration.
2768 // Note that we do not instantiate the variable just yet, since
2769 // instantiation is handled in DoMarkVarDeclReferenced().
2770 // FIXME: LateAttrs et al.?
2771 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2772 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2773 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2774 if (!Decl)
2775 return true;
2776
2777 if (AmbiguousPartialSpec) {
2778 // Partial ordering did not produce a clear winner. Complain.
2779 Decl->setInvalidDecl();
2780 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2781 << Decl;
2782
2783 // Print the matching partial specializations.
2784 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2785 PEnd = Matched.end();
2786 P != PEnd; ++P)
2787 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2788 << getTemplateArgumentBindingsText(
2789 P->Partial->getTemplateParameters(), *P->Args);
2790 return true;
2791 }
2792
2793 if (VarTemplatePartialSpecializationDecl *D =
2794 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2795 Decl->setInstantiationOf(D, InstantiationArgs);
2796
2797 assert(Decl && "No variable template specialization?");
2798 return Decl;
2799}
2800
2801ExprResult
2802Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2803 const DeclarationNameInfo &NameInfo,
2804 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2805 const TemplateArgumentListInfo *TemplateArgs) {
2806
2807 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2808 *TemplateArgs);
2809 if (Decl.isInvalid())
2810 return ExprError();
2811
2812 VarDecl *Var = cast<VarDecl>(Decl.get());
2813 if (!Var->getTemplateSpecializationKind())
2814 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2815 NameInfo.getLoc());
2816
2817 // Build an ordinary singleton decl ref.
2818 return BuildDeclarationNameExpr(SS, NameInfo, Var,
2819 /*FoundD=*/0, TemplateArgs);
2820}
2821
John McCalldadc5752010-08-24 06:29:42 +00002822ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002823 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002824 LookupResult &R,
2825 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002826 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002827 // FIXME: Can we do any checking at this point? I guess we could check the
2828 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002829 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002830 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002831 // foo<int> could identify a single function unambiguously
2832 // This approach does NOT work, since f<int>(1);
2833 // gets resolved prior to resorting to overload resolution
2834 // i.e., template<class T> void f(double);
2835 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002836
2837 // These should be filtered out by our callers.
2838 assert(!R.empty() && "empty lookup results when building templateid");
2839 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2840
Larisse Voufo39a1e502013-08-06 01:03:05 +00002841 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002842 bool InstantiationDependent;
2843 if (R.getAsSingle<VarTemplateDecl>() &&
2844 !TemplateSpecializationType::anyDependentTemplateArguments(
2845 *TemplateArgs, InstantiationDependent)) {
2846 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2847 R.getAsSingle<VarTemplateDecl>(),
2848 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002849 }
2850
John McCall58cc69d2010-01-27 01:50:18 +00002851 // We don't want lookup warnings at this point.
2852 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002853
John McCalle66edc12009-11-24 19:00:30 +00002854 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002855 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002856 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002857 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002858 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002859 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002860 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002861
2862 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00002863}
2864
John McCalle66edc12009-11-24 19:00:30 +00002865// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002866ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002867Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002868 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002869 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002870 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002871
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002872 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002873 DeclContext *DC;
2874 if (!(DC = computeDeclContext(SS, false)) ||
2875 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002876 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002877 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002878
Douglas Gregor786123d2010-05-21 23:18:07 +00002879 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002880 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00002881 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
2882 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002883
John McCalle66edc12009-11-24 19:00:30 +00002884 if (R.isAmbiguous())
2885 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002886
John McCalle66edc12009-11-24 19:00:30 +00002887 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002888 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2889 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002890 return ExprError();
2891 }
2892
2893 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002894 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00002895 << SS.getScopeRep()
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002896 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002897 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2898 return ExprError();
2899 }
2900
Abramo Bagnara7945c982012-01-27 09:46:47 +00002901 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00002902}
2903
Douglas Gregorb67535d2009-03-31 00:43:58 +00002904/// \brief Form a dependent template name.
2905///
2906/// This action forms a dependent template name given the template
2907/// name and its (presumably dependent) scope specifier. For
2908/// example, given "MetaFun::template apply", the scope specifier \p
2909/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2910/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002911TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00002912 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002913 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00002914 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00002915 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00002916 bool EnteringContext,
2917 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00002918 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2919 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002920 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002921 diag::warn_cxx98_compat_template_outside_of_template :
2922 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002923 << FixItHint::CreateRemoval(TemplateKWLoc);
2924
Douglas Gregor9abe2372010-01-19 16:01:07 +00002925 DeclContext *LookupCtx = 0;
2926 if (SS.isSet())
2927 LookupCtx = computeDeclContext(SS, EnteringContext);
2928 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00002929 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00002930 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00002931 // C++0x [temp.names]p5:
2932 // If a name prefixed by the keyword template is not the name of
2933 // a template, the program is ill-formed. [Note: the keyword
2934 // template may not be applied to non-template members of class
2935 // templates. -end note ] [ Note: as is the case with the
2936 // typename prefix, the template prefix is allowed in cases
2937 // where it is not strictly necessary; i.e., when the
2938 // nested-name-specifier or the expression on the left of the ->
2939 // or . is not dependent on a template-parameter, or the use
2940 // does not appear in the scope of a template. -end note]
2941 //
2942 // Note: C++03 was more strict here, because it banned the use of
2943 // the "template" keyword prior to a template-name that was not a
2944 // dependent name. C++ DR468 relaxed this requirement (the
2945 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00002946 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00002947 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00002948 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002949 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00002950 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00002951 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2952 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00002953 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2954 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00002955 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00002956 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002957 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00002958 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002959 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00002960 << Name.getSourceRange()
2961 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00002962 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00002963 } else {
2964 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00002965 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00002966 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00002967 }
2968
Aaron Ballman4a979672014-01-03 13:56:08 +00002969 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002970
Douglas Gregor3cf81312009-11-03 23:16:33 +00002971 switch (Name.getKind()) {
2972 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002973 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00002974 Name.Identifier));
2975 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002976
Douglas Gregor71395fa2009-11-04 00:56:37 +00002977 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00002978 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002979 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00002980 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00002981
2982 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00002983 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00002984
Douglas Gregor3cf81312009-11-03 23:16:33 +00002985 default:
2986 break;
2987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002988
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002989 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00002990 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002991 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00002992 << Name.getSourceRange()
2993 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00002994 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00002995}
2996
Mike Stump11289f42009-09-09 15:08:12 +00002997bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00002998 const TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002999 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003000 const TemplateArgument &Arg = AL.getArgument();
3001
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003002 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003003 switch(Arg.getKind()) {
3004 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003005 // C++ [temp.arg.type]p1:
3006 // A template-argument for a template-parameter which is a
3007 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003008 break;
3009 case TemplateArgument::Template: {
3010 // We have a template type parameter but the template argument
3011 // is a template without any arguments.
3012 SourceRange SR = AL.getSourceRange();
3013 TemplateName Name = Arg.getAsTemplate();
3014 Diag(SR.getBegin(), diag::err_template_missing_args)
3015 << Name << SR;
3016 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3017 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003018
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003019 return true;
3020 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003021 case TemplateArgument::Expression: {
3022 // We have a template type parameter but the template argument is an
3023 // expression; see if maybe it is missing the "typename" keyword.
3024 CXXScopeSpec SS;
3025 DeclarationNameInfo NameInfo;
3026
3027 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3028 SS.Adopt(ArgExpr->getQualifierLoc());
3029 NameInfo = ArgExpr->getNameInfo();
3030 } else if (DependentScopeDeclRefExpr *ArgExpr =
3031 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3032 SS.Adopt(ArgExpr->getQualifierLoc());
3033 NameInfo = ArgExpr->getNameInfo();
3034 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3035 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003036 if (ArgExpr->isImplicitAccess()) {
3037 SS.Adopt(ArgExpr->getQualifierLoc());
3038 NameInfo = ArgExpr->getMemberNameInfo();
3039 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003040 }
3041
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003042 if (NameInfo.getName().isIdentifier()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003043 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3044 LookupParsedName(Result, CurScope, &SS);
3045
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003046 if (Result.getAsSingle<TypeDecl>() ||
3047 Result.getResultKind() ==
3048 LookupResult::NotFoundInCurrentInstantiation) {
3049 // FIXME: Add a FixIt and fix up the template argument for recovery.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003050 SourceLocation Loc = AL.getSourceRange().getBegin();
3051 Diag(Loc, diag::err_template_arg_must_be_type_suggest);
3052 Diag(Param->getLocation(), diag::note_template_param_here);
3053 return true;
3054 }
3055 }
3056 // fallthrough
3057 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003058 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003059 // We have a template type parameter but the template argument
3060 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003061 SourceRange SR = AL.getSourceRange();
3062 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003063 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003064
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003065 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003066 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003067 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003068
John McCallbcd03502009-12-07 02:54:59 +00003069 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003070 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003071
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003072 // Add the converted template type argument.
Douglas Gregore46db902011-06-17 22:11:49 +00003073 QualType ArgType = Context.getCanonicalType(Arg.getAsType());
3074
3075 // Objective-C ARC:
3076 // If an explicitly-specified template argument type is a lifetime type
3077 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003078 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003079 ArgType->isObjCLifetimeType() &&
3080 !ArgType.getObjCLifetime()) {
3081 Qualifiers Qs;
3082 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3083 ArgType = Context.getQualifiedType(ArgType, Qs);
3084 }
3085
3086 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003087 return false;
3088}
3089
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003090/// \brief Substitute template arguments into the default template argument for
3091/// the given template type parameter.
3092///
3093/// \param SemaRef the semantic analysis object for which we are performing
3094/// the substitution.
3095///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003096/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003097/// for.
3098///
3099/// \param TemplateLoc the location of the template name that started the
3100/// template-id we are checking.
3101///
3102/// \param RAngleLoc the location of the right angle bracket ('>') that
3103/// terminates the template-id.
3104///
3105/// \param Param the template template parameter whose default we are
3106/// substituting into.
3107///
3108/// \param Converted the list of template arguments provided for template
3109/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003110/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003111static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003112SubstDefaultTemplateArgument(Sema &SemaRef,
3113 TemplateDecl *Template,
3114 SourceLocation TemplateLoc,
3115 SourceLocation RAngleLoc,
3116 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003117 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003118 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003119
3120 // If the argument type is dependent, instantiate it now based
3121 // on the previously-computed template arguments.
3122 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003123 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003124 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003125 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003126 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003127 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003128
David Majnemer89189202013-08-28 23:48:32 +00003129 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3130 Converted.data(), Converted.size());
3131
3132 // Only substitute for the innermost template argument list.
3133 MultiLevelTemplateArgumentList TemplateArgLists;
3134 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3135 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3136 TemplateArgLists.addOuterTemplateArguments(None);
3137
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003138 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003139 ArgType =
3140 SemaRef.SubstType(ArgType, TemplateArgLists,
3141 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003142 }
3143
3144 return ArgType;
3145}
3146
3147/// \brief Substitute template arguments into the default template argument for
3148/// the given non-type template parameter.
3149///
3150/// \param SemaRef the semantic analysis object for which we are performing
3151/// the substitution.
3152///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003154/// for.
3155///
3156/// \param TemplateLoc the location of the template name that started the
3157/// template-id we are checking.
3158///
3159/// \param RAngleLoc the location of the right angle bracket ('>') that
3160/// terminates the template-id.
3161///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003162/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003163/// substituting into.
3164///
3165/// \param Converted the list of template arguments provided for template
3166/// parameters that precede \p Param in the template parameter list.
3167///
3168/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003169static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003170SubstDefaultTemplateArgument(Sema &SemaRef,
3171 TemplateDecl *Template,
3172 SourceLocation TemplateLoc,
3173 SourceLocation RAngleLoc,
3174 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003175 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003176 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003177 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003178 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003179 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003180 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003181
David Majnemer89189202013-08-28 23:48:32 +00003182 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3183 Converted.data(), Converted.size());
3184
3185 // Only substitute for the innermost template argument list.
3186 MultiLevelTemplateArgumentList TemplateArgLists;
3187 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3188 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3189 TemplateArgLists.addOuterTemplateArguments(None);
3190
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003191 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
Eli Friedmanc25372b2012-04-26 22:43:24 +00003192 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
David Majnemer89189202013-08-28 23:48:32 +00003193 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003194}
3195
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003196/// \brief Substitute template arguments into the default template argument for
3197/// the given template template parameter.
3198///
3199/// \param SemaRef the semantic analysis object for which we are performing
3200/// the substitution.
3201///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003202/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003203/// for.
3204///
3205/// \param TemplateLoc the location of the template name that started the
3206/// template-id we are checking.
3207///
3208/// \param RAngleLoc the location of the right angle bracket ('>') that
3209/// terminates the template-id.
3210///
3211/// \param Param the template template parameter whose default we are
3212/// substituting into.
3213///
3214/// \param Converted the list of template arguments provided for template
3215/// parameters that precede \p Param in the template parameter list.
3216///
Douglas Gregordf846d12011-03-02 18:46:51 +00003217/// \param QualifierLoc Will be set to the nested-name-specifier (with
3218/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003219///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003220/// \returns the substituted template argument, or NULL if an error occurred.
3221static TemplateName
3222SubstDefaultTemplateArgument(Sema &SemaRef,
3223 TemplateDecl *Template,
3224 SourceLocation TemplateLoc,
3225 SourceLocation RAngleLoc,
3226 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003227 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003228 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003229 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003230 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003231 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003232 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003233
David Majnemer89189202013-08-28 23:48:32 +00003234 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3235 Converted.data(), Converted.size());
3236
3237 // Only substitute for the innermost template argument list.
3238 MultiLevelTemplateArgumentList TemplateArgLists;
3239 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3240 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3241 TemplateArgLists.addOuterTemplateArguments(None);
3242
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003243 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003244 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003245 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003246 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003247 QualifierLoc =
3248 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003249 if (!QualifierLoc)
3250 return TemplateName();
3251 }
David Majnemer89189202013-08-28 23:48:32 +00003252
3253 return SemaRef.SubstTemplateName(
3254 QualifierLoc,
3255 Param->getDefaultArgument().getArgument().getAsTemplate(),
3256 Param->getDefaultArgument().getTemplateNameLoc(),
3257 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003258}
3259
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003260/// \brief If the given template parameter has a default template
3261/// argument, substitute into that default template argument and
3262/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003263TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003264Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3265 SourceLocation TemplateLoc,
3266 SourceLocation RAngleLoc,
3267 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003268 SmallVectorImpl<TemplateArgument>
3269 &Converted,
3270 bool &HasDefaultArg) {
3271 HasDefaultArg = false;
3272
3273 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003274 if (!TypeParm->hasDefaultArgument())
3275 return TemplateArgumentLoc();
3276
Richard Smithc87b9382013-07-04 01:01:24 +00003277 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003278 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003279 TemplateLoc,
3280 RAngleLoc,
3281 TypeParm,
3282 Converted);
3283 if (DI)
3284 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3285
3286 return TemplateArgumentLoc();
3287 }
3288
3289 if (NonTypeTemplateParmDecl *NonTypeParm
3290 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3291 if (!NonTypeParm->hasDefaultArgument())
3292 return TemplateArgumentLoc();
3293
Richard Smithc87b9382013-07-04 01:01:24 +00003294 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003295 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003296 TemplateLoc,
3297 RAngleLoc,
3298 NonTypeParm,
3299 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003300 if (Arg.isInvalid())
3301 return TemplateArgumentLoc();
3302
3303 Expr *ArgE = Arg.takeAs<Expr>();
3304 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3305 }
3306
3307 TemplateTemplateParmDecl *TempTempParm
3308 = cast<TemplateTemplateParmDecl>(Param);
3309 if (!TempTempParm->hasDefaultArgument())
3310 return TemplateArgumentLoc();
3311
Richard Smithc87b9382013-07-04 01:01:24 +00003312 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003313 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003314 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003315 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003316 RAngleLoc,
3317 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003318 Converted,
3319 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003320 if (TName.isNull())
3321 return TemplateArgumentLoc();
3322
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003323 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003324 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003325 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3326}
3327
Douglas Gregorda0fb532009-11-11 19:31:23 +00003328/// \brief Check that the given template argument corresponds to the given
3329/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003330///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003331/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003332/// checked.
3333///
3334/// \param Arg The template argument.
3335///
3336/// \param Template The template in which the template argument resides.
3337///
3338/// \param TemplateLoc The location of the template name for the template
3339/// whose argument list we're matching.
3340///
3341/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3342/// the template argument list.
3343///
3344/// \param ArgumentPackIndex The index into the argument pack where this
3345/// argument will be placed. Only valid if the parameter is a parameter pack.
3346///
3347/// \param Converted The checked, converted argument will be added to the
3348/// end of this small vector.
3349///
3350/// \param CTAK Describes how we arrived at this particular template argument:
3351/// explicitly written, deduced, etc.
3352///
3353/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003354bool Sema::CheckTemplateArgument(NamedDecl *Param,
3355 const TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003356 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003357 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003358 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003359 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003360 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003361 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003362 // Check template type parameters.
3363 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003364 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003365
Douglas Gregoreebed722009-11-11 19:41:09 +00003366 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003368 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003369 // with the template arguments we've seen thus far. But if the
3370 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003371 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003372 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3373 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003374
Peter Collingbourne01687632010-12-10 17:08:53 +00003375 if (NTTPType->isDependentType() &&
3376 !isa<TemplateTemplateParmDecl>(Template) &&
3377 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003378 // Do substitution on the type of the non-type template parameter.
3379 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003380 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003381 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003382 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003383 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384
3385 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003386 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003387 NTTPType = SubstType(NTTPType,
3388 MultiLevelTemplateArgumentList(TemplateArgs),
3389 NTTP->getLocation(),
3390 NTTP->getDeclName());
3391 // If that worked, check the non-type template parameter type
3392 // for validity.
3393 if (!NTTPType.isNull())
3394 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3395 NTTP->getLocation());
3396 if (NTTPType.isNull())
3397 return true;
3398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003399
Douglas Gregorda0fb532009-11-11 19:31:23 +00003400 switch (Arg.getArgument().getKind()) {
3401 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003402 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403
Douglas Gregorda0fb532009-11-11 19:31:23 +00003404 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003405 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003406 ExprResult Res =
3407 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3408 Result, CTAK);
3409 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003410 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003412 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003413 break;
3414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003415
Douglas Gregorda0fb532009-11-11 19:31:23 +00003416 case TemplateArgument::Declaration:
3417 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003418 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003419 // We've already checked this template argument, so just copy
3420 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003421 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003422 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003423
Douglas Gregorda0fb532009-11-11 19:31:23 +00003424 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003425 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003426 // We were given a template template argument. It may not be ill-formed;
3427 // see below.
3428 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003429 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3430 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003431 // We have a template argument such as \c T::template X, which we
3432 // parsed as a template template argument. However, since we now
3433 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003434 // template name into an expression.
3435
3436 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3437 Arg.getTemplateNameLoc());
3438
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003439 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003440 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003441 // FIXME: the template-template arg was a DependentTemplateName,
3442 // so it was provided with a template keyword. However, its source
3443 // location is not stored in the template argument structure.
3444 SourceLocation TemplateKWLoc;
John Wiegley01296292011-04-08 18:41:53 +00003445 ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context,
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003446 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003447 TemplateKWLoc,
3448 NameInfo, 0));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003449
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003450 // If we parsed the template argument as a pack expansion, create a
3451 // pack expansion expression.
3452 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
John Wiegley01296292011-04-08 18:41:53 +00003453 E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc());
3454 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003455 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003456 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003457
Douglas Gregorda0fb532009-11-11 19:31:23 +00003458 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003459 E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result);
3460 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003461 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003462
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003463 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003464 break;
3465 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466
Douglas Gregorda0fb532009-11-11 19:31:23 +00003467 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003468 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003469 // therefore cannot be a non-type template argument.
3470 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3471 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003472
Douglas Gregorda0fb532009-11-11 19:31:23 +00003473 Diag(Param->getLocation(), diag::note_template_param_here);
3474 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003475
Douglas Gregorda0fb532009-11-11 19:31:23 +00003476 case TemplateArgument::Type: {
3477 // We have a non-type template parameter but the template
3478 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003479
Douglas Gregorda0fb532009-11-11 19:31:23 +00003480 // C++ [temp.arg]p2:
3481 // In a template-argument, an ambiguity between a type-id and
3482 // an expression is resolved to a type-id, regardless of the
3483 // form of the corresponding template-parameter.
3484 //
3485 // We warn specifically about this case, since it can be rather
3486 // confusing for users.
3487 QualType T = Arg.getArgument().getAsType();
3488 SourceRange SR = Arg.getSourceRange();
3489 if (T->isFunctionType())
3490 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3491 else
3492 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3493 Diag(Param->getLocation(), diag::note_template_param_here);
3494 return true;
3495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003496
Douglas Gregorda0fb532009-11-11 19:31:23 +00003497 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003498 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003500
Douglas Gregorda0fb532009-11-11 19:31:23 +00003501 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502 }
3503
3504
Douglas Gregorda0fb532009-11-11 19:31:23 +00003505 // Check template template parameters.
3506 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003507
Douglas Gregorda0fb532009-11-11 19:31:23 +00003508 // Substitute into the template parameter list of the template
3509 // template parameter, since previously-supplied template arguments
3510 // may appear within the template template parameter.
3511 {
3512 // Set up a template instantiation context.
3513 LocalInstantiationScope Scope(*this);
3514 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003515 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003516 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003517 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003518 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003519
3520 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003521 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003522 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003523 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003524 MultiLevelTemplateArgumentList(TemplateArgs)));
3525 if (!TempParm)
3526 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003527 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003528
Douglas Gregorda0fb532009-11-11 19:31:23 +00003529 switch (Arg.getArgument().getKind()) {
3530 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003531 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003532
Douglas Gregorda0fb532009-11-11 19:31:23 +00003533 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003534 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003535 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003536 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003537
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003538 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003539 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003540
Douglas Gregorda0fb532009-11-11 19:31:23 +00003541 case TemplateArgument::Expression:
3542 case TemplateArgument::Type:
3543 // We have a template template parameter but the template
3544 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003545 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003546 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003547 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003548
Douglas Gregorda0fb532009-11-11 19:31:23 +00003549 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003550 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003551 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003552 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003553 case TemplateArgument::NullPtr:
3554 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003555
Douglas Gregorda0fb532009-11-11 19:31:23 +00003556 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003557 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003559
Douglas Gregorda0fb532009-11-11 19:31:23 +00003560 return false;
3561}
3562
Douglas Gregor8e072612012-02-03 07:34:46 +00003563/// \brief Diagnose an arity mismatch in the
3564static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3565 SourceLocation TemplateLoc,
3566 TemplateArgumentListInfo &TemplateArgs) {
3567 TemplateParameterList *Params = Template->getTemplateParameters();
3568 unsigned NumParams = Params->size();
3569 unsigned NumArgs = TemplateArgs.size();
3570
3571 SourceRange Range;
3572 if (NumArgs > NumParams)
3573 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3574 TemplateArgs.getRAngleLoc());
3575 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3576 << (NumArgs > NumParams)
3577 << (isa<ClassTemplateDecl>(Template)? 0 :
3578 isa<FunctionTemplateDecl>(Template)? 1 :
3579 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3580 << Template << Range;
3581 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3582 << Params->getSourceRange();
3583 return true;
3584}
3585
Richard Smith1fde8ec2012-09-07 02:06:42 +00003586/// \brief Check whether the template parameter is a pack expansion, and if so,
3587/// determine the number of parameters produced by that expansion. For instance:
3588///
3589/// \code
3590/// template<typename ...Ts> struct A {
3591/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3592/// };
3593/// \endcode
3594///
3595/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3596/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003597static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003598 if (NonTypeTemplateParmDecl *NTTP
3599 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3600 if (NTTP->isExpandedParameterPack())
3601 return NTTP->getNumExpansionTypes();
3602 }
3603
3604 if (TemplateTemplateParmDecl *TTP
3605 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3606 if (TTP->isExpandedParameterPack())
3607 return TTP->getNumExpansionTemplateParameters();
3608 }
3609
David Blaikie7a30dc52013-02-21 01:47:18 +00003610 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003611}
3612
Douglas Gregord32e0282009-02-09 23:23:08 +00003613/// \brief Check that the given template argument list is well-formed
3614/// for specializing the given template.
3615bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3616 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003617 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003618 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003619 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00003620 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003621
John McCall6b51f282009-11-23 01:53:49 +00003622 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
3623
Mike Stump11289f42009-09-09 15:08:12 +00003624 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003625 // [...] The type and form of each template-argument specified in
3626 // a template-id shall match the type and form specified for the
3627 // corresponding parameter declared by the template in its
3628 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003629 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003630 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003631 unsigned ArgIdx = 0, NumArgs = TemplateArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003632 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003633 for (TemplateParameterList::iterator Param = Params->begin(),
3634 ParamEnd = Params->end();
3635 Param != ParamEnd; /* increment in loop */) {
3636 // If we have an expanded parameter pack, make sure we don't have too
3637 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003638 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003639 if (*Expansions == ArgumentPack.size()) {
3640 // We're done with this parameter pack. Pack up its arguments and add
3641 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003642 Converted.push_back(
3643 TemplateArgument::CreatePackCopy(Context,
3644 ArgumentPack.data(),
3645 ArgumentPack.size()));
3646 ArgumentPack.clear();
3647
Richard Smith1fde8ec2012-09-07 02:06:42 +00003648 // This argument is assigned to the next parameter.
3649 ++Param;
3650 continue;
3651 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3652 // Not enough arguments for this parameter pack.
3653 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3654 << false
3655 << (isa<ClassTemplateDecl>(Template)? 0 :
3656 isa<FunctionTemplateDecl>(Template)? 1 :
3657 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3658 << Template;
3659 Diag(Template->getLocation(), diag::note_template_decl_here)
3660 << Params->getSourceRange();
3661 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003662 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003664
Richard Smith1fde8ec2012-09-07 02:06:42 +00003665 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003666 // Check the template argument we were given.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
3668 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003669 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003670 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Richard Smith83b11aa2014-01-09 02:22:22 +00003672 if (TemplateArgs[ArgIdx].getArgument().isPackExpansion() &&
3673 isa<TypeAliasTemplateDecl>(Template) &&
3674 !(Param + 1 == ParamEnd && (*Param)->isTemplateParameterPack() &&
3675 !getExpandedPackSize(*Param))) {
3676 // Core issue 1430: we have a pack expansion as an argument to an
3677 // alias template, and it's not part of a final parameter pack. This
3678 // can't be canonicalized, so reject it now.
3679 Diag(TemplateArgs[ArgIdx].getLocation(),
3680 diag::err_alias_template_expansion_into_fixed_list)
3681 << TemplateArgs[ArgIdx].getSourceRange();
3682 Diag((*Param)->getLocation(), diag::note_template_param_here);
3683 return true;
3684 }
3685
Richard Smith1fde8ec2012-09-07 02:06:42 +00003686 // We're now done with this argument.
3687 ++ArgIdx;
3688
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003689 if ((*Param)->isTemplateParameterPack()) {
3690 // The template parameter was a template parameter pack, so take the
3691 // deduced argument and place it on the argument pack. Note that we
3692 // stay on the same template parameter so that we can deduce more
3693 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003694 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003695 } else {
3696 // Move to the next template parameter.
3697 ++Param;
3698 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003699
3700 // If we just saw a pack expansion, then directly convert the remaining
3701 // arguments, because we don't know what parameters they'll match up
3702 // with.
3703 if (TemplateArgs[ArgIdx-1].getArgument().isPackExpansion()) {
3704 bool InFinalParameterPack = Param != ParamEnd &&
3705 Param + 1 == ParamEnd &&
3706 (*Param)->isTemplateParameterPack() &&
3707 !getExpandedPackSize(*Param);
3708
3709 if (!InFinalParameterPack && !ArgumentPack.empty()) {
3710 // If we were part way through filling in an expanded parameter pack,
3711 // fall back to just producing individual arguments.
3712 Converted.insert(Converted.end(),
3713 ArgumentPack.begin(), ArgumentPack.end());
3714 ArgumentPack.clear();
3715 }
3716
3717 while (ArgIdx < NumArgs) {
3718 if (InFinalParameterPack)
3719 ArgumentPack.push_back(TemplateArgs[ArgIdx].getArgument());
3720 else
3721 Converted.push_back(TemplateArgs[ArgIdx].getArgument());
3722 ++ArgIdx;
3723 }
3724
3725 // Push the argument pack onto the list of converted arguments.
3726 if (InFinalParameterPack) {
Eli Friedmanb826a002012-09-26 02:36:12 +00003727 Converted.push_back(
3728 TemplateArgument::CreatePackCopy(Context,
3729 ArgumentPack.data(),
3730 ArgumentPack.size()));
3731 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003732 }
3733
3734 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003735 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003736
Douglas Gregor84d49a22009-11-11 21:54:23 +00003737 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003738 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
Douglas Gregor2f157c92011-06-03 02:59:40 +00003740 // If we're checking a partial template argument list, we're done.
3741 if (PartialTemplateArgs) {
3742 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3743 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3744 ArgumentPack.data(),
3745 ArgumentPack.size()));
3746
Richard Smith1fde8ec2012-09-07 02:06:42 +00003747 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003748 }
3749
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003751 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003752 if ((*Param)->isTemplateParameterPack()) {
3753 assert(!getExpandedPackSize(*Param) &&
3754 "Should have dealt with this already");
3755
3756 // A non-expanded parameter pack before the end of the parameter list
3757 // only occurs for an ill-formed template parameter list, unless we've
3758 // got a partial argument list for a function template, so just bail out.
3759 if (Param + 1 != ParamEnd)
3760 return true;
3761
Eli Friedmanb826a002012-09-26 02:36:12 +00003762 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3763 ArgumentPack.data(),
3764 ArgumentPack.size()));
3765 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003766
3767 ++Param;
3768 continue;
3769 }
3770
Douglas Gregor8e072612012-02-03 07:34:46 +00003771 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003772 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003773
Douglas Gregor84d49a22009-11-11 21:54:23 +00003774 // Retrieve the default template argument from the template
3775 // parameter. For each kind of template parameter, we substitute the
3776 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003778 // the default argument.
3779 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Douglas Gregor8e072612012-02-03 07:34:46 +00003780 if (!TTP->hasDefaultArgument())
3781 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3782 TemplateArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003783
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003784 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003785 Template,
3786 TemplateLoc,
3787 RAngleLoc,
3788 TTP,
3789 Converted);
3790 if (!ArgType)
3791 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003792
Douglas Gregor84d49a22009-11-11 21:54:23 +00003793 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3794 ArgType);
3795 } else if (NonTypeTemplateParmDecl *NTTP
3796 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Douglas Gregor8e072612012-02-03 07:34:46 +00003797 if (!NTTP->hasDefaultArgument())
3798 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3799 TemplateArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003800
John McCalldadc5752010-08-24 06:29:42 +00003801 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003802 TemplateLoc,
3803 RAngleLoc,
3804 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003805 Converted);
3806 if (E.isInvalid())
3807 return true;
3808
3809 Expr *Ex = E.takeAs<Expr>();
3810 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3811 } else {
3812 TemplateTemplateParmDecl *TempParm
3813 = cast<TemplateTemplateParmDecl>(*Param);
3814
Douglas Gregor8e072612012-02-03 07:34:46 +00003815 if (!TempParm->hasDefaultArgument())
3816 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3817 TemplateArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003818
Douglas Gregordf846d12011-03-02 18:46:51 +00003819 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003820 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003821 TemplateLoc,
3822 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003823 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003824 Converted,
3825 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003826 if (Name.isNull())
3827 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003828
Douglas Gregor9d802122011-03-02 17:09:35 +00003829 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3830 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003832
Douglas Gregor84d49a22009-11-11 21:54:23 +00003833 // Introduce an instantiation record that describes where we are using
3834 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003835 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3836 SourceRange(TemplateLoc, RAngleLoc));
3837 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003838 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839
Douglas Gregor84d49a22009-11-11 21:54:23 +00003840 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003841 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003842 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003843 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003844
Douglas Gregor739b107a2011-03-03 02:41:12 +00003845 // Core issue 150 (assumed resolution): if this is a template template
3846 // parameter, keep track of the default template arguments from the
3847 // template definition.
3848 if (isTemplateTemplateParameter)
3849 TemplateArgs.addArgument(Arg);
3850
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003851 // Move to the next template parameter and argument.
3852 ++Param;
3853 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003854 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003855
Douglas Gregor8e072612012-02-03 07:34:46 +00003856 // If we have any leftover arguments, then there were too many arguments.
3857 // Complain and fail.
3858 if (ArgIdx < NumArgs)
3859 return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003860
Richard Smith1fde8ec2012-09-07 02:06:42 +00003861 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00003862}
3863
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003864namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003865 class UnnamedLocalNoLinkageFinder
3866 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003867 {
3868 Sema &S;
3869 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003870
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003871 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003872
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003873 public:
3874 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3875
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003876 bool Visit(QualType T) {
3877 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003878 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003879
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003880#define TYPE(Class, Parent) \
3881 bool Visit##Class##Type(const Class##Type *);
3882#define ABSTRACT_TYPE(Class, Parent) \
3883 bool Visit##Class##Type(const Class##Type *) { return false; }
3884#define NON_CANONICAL_TYPE(Class, Parent) \
3885 bool Visit##Class##Type(const Class##Type *) { return false; }
3886#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003887
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003888 bool VisitTagDecl(const TagDecl *Tag);
3889 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3890 };
3891}
3892
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003894 return false;
3895}
3896
3897bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3898 return Visit(T->getElementType());
3899}
3900
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003901bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003902 return Visit(T->getPointeeType());
3903}
3904
3905bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003906 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003907 return Visit(T->getPointeeType());
3908}
3909
3910bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003911 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003912 return Visit(T->getPointeeType());
3913}
3914
3915bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003916 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003917 return Visit(T->getPointeeType());
3918}
3919
3920bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003921 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003922 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3923}
3924
3925bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003926 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003927 return Visit(T->getElementType());
3928}
3929
3930bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003931 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003932 return Visit(T->getElementType());
3933}
3934
3935bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003936 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003937 return Visit(T->getElementType());
3938}
3939
3940bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003941 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003942 return Visit(T->getElementType());
3943}
3944
3945bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003946 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003947 return Visit(T->getElementType());
3948}
3949
3950bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3951 return Visit(T->getElementType());
3952}
3953
3954bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3955 return Visit(T->getElementType());
3956}
3957
3958bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3959 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003960 for (const auto &A : T->param_types()) {
3961 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003962 return true;
3963 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003964
Alp Toker314cc812014-01-25 16:55:45 +00003965 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003966}
3967
3968bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3969 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00003970 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003971}
3972
3973bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3974 const UnresolvedUsingType*) {
3975 return false;
3976}
3977
3978bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3979 return false;
3980}
3981
3982bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
3983 return Visit(T->getUnderlyingType());
3984}
3985
3986bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
3987 return false;
3988}
3989
Alexis Hunte852b102011-05-24 22:41:36 +00003990bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
3991 const UnaryTransformType*) {
3992 return false;
3993}
3994
Richard Smith30482bc2011-02-20 03:19:35 +00003995bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
3996 return Visit(T->getDeducedType());
3997}
3998
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003999bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4000 return VisitTagDecl(T->getDecl());
4001}
4002
4003bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4004 return VisitTagDecl(T->getDecl());
4005}
4006
4007bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4008 const TemplateTypeParmType*) {
4009 return false;
4010}
4011
Douglas Gregorada4b792011-01-14 02:55:32 +00004012bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4013 const SubstTemplateTypeParmPackType *) {
4014 return false;
4015}
4016
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004017bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4018 const TemplateSpecializationType*) {
4019 return false;
4020}
4021
4022bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4023 const InjectedClassNameType* T) {
4024 return VisitTagDecl(T->getDecl());
4025}
4026
4027bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4028 const DependentNameType* T) {
4029 return VisitNestedNameSpecifier(T->getQualifier());
4030}
4031
4032bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4033 const DependentTemplateSpecializationType* T) {
4034 return VisitNestedNameSpecifier(T->getQualifier());
4035}
4036
Douglas Gregord2fa7662010-12-20 02:24:11 +00004037bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4038 const PackExpansionType* T) {
4039 return Visit(T->getPattern());
4040}
4041
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004042bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4043 return false;
4044}
4045
4046bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4047 const ObjCInterfaceType *) {
4048 return false;
4049}
4050
4051bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4052 const ObjCObjectPointerType *) {
4053 return false;
4054}
4055
Eli Friedman0dfb8892011-10-06 23:00:33 +00004056bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4057 return Visit(T->getValueType());
4058}
4059
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004060bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4061 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004062 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004063 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004064 diag::warn_cxx98_compat_template_arg_local_type :
4065 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004066 << S.Context.getTypeDeclType(Tag) << SR;
4067 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004068 }
4069
John McCall5ea95772013-03-09 00:54:27 +00004070 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004071 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004072 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004073 diag::warn_cxx98_compat_template_arg_unnamed_type :
4074 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004075 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4076 return true;
4077 }
4078
4079 return false;
4080}
4081
4082bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4083 NestedNameSpecifier *NNS) {
4084 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4085 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004086
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004087 switch (NNS->getKind()) {
4088 case NestedNameSpecifier::Identifier:
4089 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004090 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004091 case NestedNameSpecifier::Global:
4092 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004093
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004094 case NestedNameSpecifier::TypeSpec:
4095 case NestedNameSpecifier::TypeSpecWithTemplate:
4096 return Visit(QualType(NNS->getAsType(), 0));
4097 }
David Blaikie8a40f702012-01-17 06:56:22 +00004098 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004099}
4100
4101
Douglas Gregord32e0282009-02-09 23:23:08 +00004102/// \brief Check a template argument against its corresponding
4103/// template type parameter.
4104///
4105/// This routine implements the semantics of C++ [temp.arg.type]. It
4106/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004107bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004108 TypeSourceInfo *ArgInfo) {
4109 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004110 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004111 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004112
4113 if (Arg->isVariablyModifiedType()) {
4114 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004115 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004116 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004117 }
4118
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004119 // C++03 [temp.arg.type]p2:
4120 // A local type, a type with no linkage, an unnamed type or a type
4121 // compounded from any of these types shall not be used as a
4122 // template-argument for a template type-parameter.
4123 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004124 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004125 // a warning.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004126 if (LangOpts.CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004127 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_unnamed_type,
4128 SR.getBegin()) != DiagnosticsEngine::Ignored ||
4129 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_local_type,
4130 SR.getBegin()) != DiagnosticsEngine::Ignored :
4131 Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004132 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4133 (void)Finder.Visit(Context.getCanonicalType(Arg));
4134 }
4135
Douglas Gregord32e0282009-02-09 23:23:08 +00004136 return false;
4137}
4138
Douglas Gregor20fdef32012-04-10 17:08:25 +00004139enum NullPointerValueKind {
4140 NPV_NotNullPointer,
4141 NPV_NullPointer,
4142 NPV_Error
4143};
4144
4145/// \brief Determine whether the given template argument is a null pointer
4146/// value of the appropriate type.
4147static NullPointerValueKind
4148isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4149 QualType ParamType, Expr *Arg) {
4150 if (Arg->isValueDependent() || Arg->isTypeDependent())
4151 return NPV_NotNullPointer;
4152
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004153 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004154 return NPV_NotNullPointer;
4155
4156 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004157 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4158 if (ArgRV.isInvalid())
4159 return NPV_Error;
4160 Arg = ArgRV.take();
4161
Douglas Gregor20fdef32012-04-10 17:08:25 +00004162 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004163 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004164 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004165 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004166 EvalResult.HasSideEffects) {
4167 SourceLocation DiagLoc = Arg->getExprLoc();
4168
4169 // If our only note is the usual "invalid subexpression" note, just point
4170 // the caret at its location rather than producing an essentially
4171 // redundant note.
4172 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4173 diag::note_invalid_subexpr_in_const_expr) {
4174 DiagLoc = Notes[0].first;
4175 Notes.clear();
4176 }
4177
4178 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4179 << Arg->getType() << Arg->getSourceRange();
4180 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4181 S.Diag(Notes[I].first, Notes[I].second);
4182
4183 S.Diag(Param->getLocation(), diag::note_template_param_here);
4184 return NPV_Error;
4185 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004186
4187 // C++11 [temp.arg.nontype]p1:
4188 // - an address constant expression of type std::nullptr_t
4189 if (Arg->getType()->isNullPtrType())
4190 return NPV_NullPointer;
4191
4192 // - a constant expression that evaluates to a null pointer value (4.10); or
4193 // - a constant expression that evaluates to a null member pointer value
4194 // (4.11); or
4195 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4196 (EvalResult.Val.isMemberPointer() &&
4197 !EvalResult.Val.getMemberPointerDecl())) {
4198 // If our expression has an appropriate type, we've succeeded.
4199 bool ObjCLifetimeConversion;
4200 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4201 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4202 ObjCLifetimeConversion))
4203 return NPV_NullPointer;
4204
4205 // The types didn't match, but we know we got a null pointer; complain,
4206 // then recover as if the types were correct.
4207 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4208 << Arg->getType() << ParamType << Arg->getSourceRange();
4209 S.Diag(Param->getLocation(), diag::note_template_param_here);
4210 return NPV_NullPointer;
4211 }
4212
4213 // If we don't have a null pointer value, but we do have a NULL pointer
4214 // constant, suggest a cast to the appropriate type.
4215 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4216 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4217 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
4218 << ParamType
4219 << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4220 << FixItHint::CreateInsertion(S.PP.getLocForEndOfToken(Arg->getLocEnd()),
4221 ")");
4222 S.Diag(Param->getLocation(), diag::note_template_param_here);
4223 return NPV_NullPointer;
4224 }
4225
4226 // FIXME: If we ever want to support general, address-constant expressions
4227 // as non-type template arguments, we should return the ExprResult here to
4228 // be interpreted by the caller.
4229 return NPV_NotNullPointer;
4230}
4231
David Majnemer61c39a12013-08-23 05:39:39 +00004232/// \brief Checks whether the given template argument is compatible with its
4233/// template parameter.
4234static bool CheckTemplateArgumentIsCompatibleWithParameter(
4235 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4236 Expr *Arg, QualType ArgType) {
4237 bool ObjCLifetimeConversion;
4238 if (ParamType->isPointerType() &&
4239 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4240 S.IsQualificationConversion(ArgType, ParamType, false,
4241 ObjCLifetimeConversion)) {
4242 // For pointer-to-object types, qualification conversions are
4243 // permitted.
4244 } else {
4245 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4246 if (!ParamRef->getPointeeType()->isFunctionType()) {
4247 // C++ [temp.arg.nontype]p5b3:
4248 // For a non-type template-parameter of type reference to
4249 // object, no conversions apply. The type referred to by the
4250 // reference may be more cv-qualified than the (otherwise
4251 // identical) type of the template- argument. The
4252 // template-parameter is bound directly to the
4253 // template-argument, which shall be an lvalue.
4254
4255 // FIXME: Other qualifiers?
4256 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4257 unsigned ArgQuals = ArgType.getCVRQualifiers();
4258
4259 if ((ParamQuals | ArgQuals) != ParamQuals) {
4260 S.Diag(Arg->getLocStart(),
4261 diag::err_template_arg_ref_bind_ignores_quals)
4262 << ParamType << Arg->getType() << Arg->getSourceRange();
4263 S.Diag(Param->getLocation(), diag::note_template_param_here);
4264 return true;
4265 }
4266 }
4267 }
4268
4269 // At this point, the template argument refers to an object or
4270 // function with external linkage. We now need to check whether the
4271 // argument and parameter types are compatible.
4272 if (!S.Context.hasSameUnqualifiedType(ArgType,
4273 ParamType.getNonReferenceType())) {
4274 // We can't perform this conversion or binding.
4275 if (ParamType->isReferenceType())
4276 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4277 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4278 else
4279 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4280 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4281 S.Diag(Param->getLocation(), diag::note_template_param_here);
4282 return true;
4283 }
4284 }
4285
4286 return false;
4287}
4288
Douglas Gregorccb07762009-02-11 19:52:55 +00004289/// \brief Checks whether the given template argument is the address
4290/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004291static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004292CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4293 NonTypeTemplateParmDecl *Param,
4294 QualType ParamType,
4295 Expr *ArgIn,
4296 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004297 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004298 Expr *Arg = ArgIn;
4299 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004300
Douglas Gregor20fdef32012-04-10 17:08:25 +00004301 // If our parameter has pointer type, check for a null template value.
4302 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4303 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4304 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004305 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Eli Friedmanb826a002012-09-26 02:36:12 +00004306 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004307 return false;
4308
4309 case NPV_Error:
4310 return true;
4311
4312 case NPV_NotNullPointer:
4313 break;
4314 }
4315 }
John McCall7c454bb2011-07-15 05:09:51 +00004316
Douglas Gregorb242683d2010-04-01 18:32:35 +00004317 bool AddressTaken = false;
4318 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004319 if (S.getLangOpts().MicrosoftExt) {
4320 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4321 // dereference and address-of operators.
4322 Arg = Arg->IgnoreParenCasts();
4323
4324 bool ExtWarnMSTemplateArg = false;
4325 UnaryOperatorKind FirstOpKind;
4326 SourceLocation FirstOpLoc;
4327 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4328 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4329 if (UnOpKind == UO_Deref)
4330 ExtWarnMSTemplateArg = true;
4331 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4332 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4333 if (!AddrOpLoc.isValid()) {
4334 FirstOpKind = UnOpKind;
4335 FirstOpLoc = UnOp->getOperatorLoc();
4336 }
4337 } else
4338 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004339 }
David Majnemer61c39a12013-08-23 05:39:39 +00004340 if (FirstOpLoc.isValid()) {
4341 if (ExtWarnMSTemplateArg)
4342 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4343 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004344
David Majnemer61c39a12013-08-23 05:39:39 +00004345 if (FirstOpKind == UO_AddrOf)
4346 AddressTaken = true;
4347 else if (Arg->getType()->isPointerType()) {
4348 // We cannot let pointers get dereferenced here, that is obviously not a
4349 // constant expression.
4350 assert(FirstOpKind == UO_Deref);
4351 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4352 << Arg->getSourceRange();
4353 }
4354 }
4355 } else {
4356 // See through any implicit casts we added to fix the type.
4357 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004358
David Majnemer61c39a12013-08-23 05:39:39 +00004359 // C++ [temp.arg.nontype]p1:
4360 //
4361 // A template-argument for a non-type, non-template
4362 // template-parameter shall be one of: [...]
4363 //
4364 // -- the address of an object or function with external
4365 // linkage, including function templates and function
4366 // template-ids but excluding non-static class members,
4367 // expressed as & id-expression where the & is optional if
4368 // the name refers to a function or array, or if the
4369 // corresponding template-parameter is a reference; or
4370
4371 // In C++98/03 mode, give an extension warning on any extra parentheses.
4372 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4373 bool ExtraParens = false;
4374 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4375 if (!Invalid && !ExtraParens) {
4376 S.Diag(Arg->getLocStart(),
4377 S.getLangOpts().CPlusPlus11
4378 ? diag::warn_cxx98_compat_template_arg_extra_parens
4379 : diag::ext_template_arg_extra_parens)
4380 << Arg->getSourceRange();
4381 ExtraParens = true;
4382 }
4383
4384 Arg = Parens->getSubExpr();
4385 }
4386
4387 while (SubstNonTypeTemplateParmExpr *subst =
4388 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4389 Arg = subst->getReplacement()->IgnoreImpCasts();
4390
4391 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4392 if (UnOp->getOpcode() == UO_AddrOf) {
4393 Arg = UnOp->getSubExpr();
4394 AddressTaken = true;
4395 AddrOpLoc = UnOp->getOperatorLoc();
4396 }
4397 }
4398
4399 while (SubstNonTypeTemplateParmExpr *subst =
4400 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4401 Arg = subst->getReplacement()->IgnoreImpCasts();
4402 }
John McCall7c454bb2011-07-15 05:09:51 +00004403
Chandler Carruth724a8a12010-01-31 10:01:20 +00004404 // Stop checking the precise nature of the argument if it is value dependent,
4405 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004406 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004407 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004408 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004409 }
David Majnemer61c39a12013-08-23 05:39:39 +00004410
4411 if (isa<CXXUuidofExpr>(Arg)) {
4412 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4413 ArgIn, Arg, ArgType))
4414 return true;
4415
4416 Converted = TemplateArgument(ArgIn);
4417 return false;
4418 }
4419
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004420 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4421 if (!DRE) {
4422 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4423 << Arg->getSourceRange();
4424 S.Diag(Param->getLocation(), diag::note_template_param_here);
4425 return true;
4426 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004427
Eli Friedmanb826a002012-09-26 02:36:12 +00004428 ValueDecl *Entity = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00004429
4430 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004431 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004432 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004433 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004434 S.Diag(Param->getLocation(), diag::note_template_param_here);
4435 return true;
4436 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004437
4438 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004439 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004440 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004441 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004442 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004443 S.Diag(Param->getLocation(), diag::note_template_param_here);
4444 return true;
4445 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004446 }
Mike Stump11289f42009-09-09 15:08:12 +00004447
Richard Smith9380e0e2012-04-04 21:11:30 +00004448 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4449 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004450
Richard Smith9380e0e2012-04-04 21:11:30 +00004451 // A non-type template argument must refer to an object or function.
4452 if (!Func && !Var) {
4453 // We found something, but we don't know specifically what it is.
4454 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4455 << Arg->getSourceRange();
4456 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4457 return true;
4458 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004459
Richard Smith9380e0e2012-04-04 21:11:30 +00004460 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004461 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004462 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004463 diag::warn_cxx98_compat_template_arg_object_internal :
4464 diag::ext_template_arg_object_internal)
4465 << !Func << Entity << Arg->getSourceRange();
4466 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4467 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004468 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004469 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4470 << !Func << Entity << Arg->getSourceRange();
4471 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4472 << !Func;
4473 return true;
4474 }
4475
4476 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004477 // If the template parameter has pointer type, the function decays.
4478 if (ParamType->isPointerType() && !AddressTaken)
4479 ArgType = S.Context.getPointerType(Func->getType());
4480 else if (AddressTaken && ParamType->isReferenceType()) {
4481 // If we originally had an address-of operator, but the
4482 // parameter has reference type, complain and (if things look
4483 // like they will work) drop the address-of operator.
4484 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4485 ParamType.getNonReferenceType())) {
4486 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4487 << ParamType;
4488 S.Diag(Param->getLocation(), diag::note_template_param_here);
4489 return true;
4490 }
4491
4492 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4493 << ParamType
4494 << FixItHint::CreateRemoval(AddrOpLoc);
4495 S.Diag(Param->getLocation(), diag::note_template_param_here);
4496
4497 ArgType = Func->getType();
4498 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004499 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004500 // A value of reference type is not an object.
4501 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004502 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004503 diag::err_template_arg_reference_var)
4504 << Var->getType() << Arg->getSourceRange();
4505 S.Diag(Param->getLocation(), diag::note_template_param_here);
4506 return true;
4507 }
4508
Richard Smith9380e0e2012-04-04 21:11:30 +00004509 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004510 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004511 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4512 << Arg->getSourceRange();
4513 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4514 return true;
4515 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004516
4517 // If the template parameter has pointer type, we must have taken
4518 // the address of this object.
4519 if (ParamType->isReferenceType()) {
4520 if (AddressTaken) {
4521 // If we originally had an address-of operator, but the
4522 // parameter has reference type, complain and (if things look
4523 // like they will work) drop the address-of operator.
4524 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4525 ParamType.getNonReferenceType())) {
4526 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4527 << ParamType;
4528 S.Diag(Param->getLocation(), diag::note_template_param_here);
4529 return true;
4530 }
4531
4532 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4533 << ParamType
4534 << FixItHint::CreateRemoval(AddrOpLoc);
4535 S.Diag(Param->getLocation(), diag::note_template_param_here);
4536
4537 ArgType = Var->getType();
4538 }
4539 } else if (!AddressTaken && ParamType->isPointerType()) {
4540 if (Var->getType()->isArrayType()) {
4541 // Array-to-pointer decay.
4542 ArgType = S.Context.getArrayDecayedType(Var->getType());
4543 } else {
4544 // If the template parameter has pointer type but the address of
4545 // this object was not taken, complain and (possibly) recover by
4546 // taking the address of the entity.
4547 ArgType = S.Context.getPointerType(Var->getType());
4548 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4549 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4550 << ParamType;
4551 S.Diag(Param->getLocation(), diag::note_template_param_here);
4552 return true;
4553 }
4554
4555 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4556 << ParamType
4557 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4558
4559 S.Diag(Param->getLocation(), diag::note_template_param_here);
4560 }
4561 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004562 }
Mike Stump11289f42009-09-09 15:08:12 +00004563
David Majnemer61c39a12013-08-23 05:39:39 +00004564 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4565 Arg, ArgType))
4566 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004567
4568 // Create the template argument.
Eli Friedmanb826a002012-09-26 02:36:12 +00004569 Converted = TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
4570 ParamType->isReferenceType());
Nick Lewycky45b50522013-02-02 00:25:55 +00004571 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004572 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004573}
4574
4575/// \brief Checks whether the given template argument is a pointer to
4576/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004577static bool CheckTemplateArgumentPointerToMember(Sema &S,
4578 NonTypeTemplateParmDecl *Param,
4579 QualType ParamType,
4580 Expr *&ResultArg,
4581 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004582 bool Invalid = false;
4583
Douglas Gregor20fdef32012-04-10 17:08:25 +00004584 // Check for a null pointer value.
4585 Expr *Arg = ResultArg;
4586 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4587 case NPV_Error:
4588 return true;
4589 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004590 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Eli Friedmanb826a002012-09-26 02:36:12 +00004591 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
David Majnemer763584d2014-02-06 10:59:19 +00004592 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4593 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004594 return false;
4595 case NPV_NotNullPointer:
4596 break;
4597 }
4598
4599 bool ObjCLifetimeConversion;
4600 if (S.IsQualificationConversion(Arg->getType(),
4601 ParamType.getNonReferenceType(),
4602 false, ObjCLifetimeConversion)) {
4603 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4604 Arg->getValueKind()).take();
4605 ResultArg = Arg;
4606 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4607 ParamType.getNonReferenceType())) {
4608 // We can't perform this conversion.
4609 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4610 << Arg->getType() << ParamType << Arg->getSourceRange();
4611 S.Diag(Param->getLocation(), diag::note_template_param_here);
4612 return true;
4613 }
4614
Douglas Gregorccb07762009-02-11 19:52:55 +00004615 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004616 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004617 Arg = Cast->getSubExpr();
4618
4619 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004620 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004621 // A template-argument for a non-type, non-template
4622 // template-parameter shall be one of: [...]
4623 //
4624 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004625 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00004626
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004627 // In C++98/03 mode, give an extension warning on any extra parentheses.
4628 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4629 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004630 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004631 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004632 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004633 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004634 diag::warn_cxx98_compat_template_arg_extra_parens :
4635 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004636 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004637 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004638 }
4639
4640 Arg = Parens->getSubExpr();
4641 }
4642
John McCall7c454bb2011-07-15 05:09:51 +00004643 while (SubstNonTypeTemplateParmExpr *subst =
4644 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4645 Arg = subst->getReplacement()->IgnoreImpCasts();
4646
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004647 // A pointer-to-member constant written &Class::member.
4648 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004649 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004650 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4651 if (DRE && !DRE->getQualifier())
4652 DRE = 0;
4653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004654 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004655 // A constant of pointer-to-member type.
4656 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4657 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4658 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004659 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004660 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004661 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004662 } else {
4663 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4664 Converted = TemplateArgument(VD, /*isReferenceParam*/false);
4665 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004666 return Invalid;
4667 }
4668 }
4669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004670
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004671 DRE = 0;
4672 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673
Douglas Gregorccb07762009-02-11 19:52:55 +00004674 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004675 return S.Diag(Arg->getLocStart(),
4676 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004677 << Arg->getSourceRange();
4678
David Majnemer3ac84e62013-10-22 21:56:38 +00004679 if (isa<FieldDecl>(DRE->getDecl()) ||
4680 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4681 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004682 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004683 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004684 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4685 "Only non-static member pointers can make it here");
4686
4687 // Okay: this is the address of a non-static member, and therefore
4688 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004689 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004690 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004691 } else {
4692 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4693 Converted = TemplateArgument(D, /*isReferenceParam*/false);
4694 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004695 return Invalid;
4696 }
4697
4698 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004699 S.Diag(Arg->getLocStart(),
4700 diag::err_template_arg_not_pointer_to_member_form)
4701 << Arg->getSourceRange();
4702 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004703 return true;
4704}
4705
Douglas Gregord32e0282009-02-09 23:23:08 +00004706/// \brief Check a template argument against its corresponding
4707/// non-type template parameter.
4708///
Douglas Gregor463421d2009-03-03 04:44:36 +00004709/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004710/// If an error occurred, it returns ExprError(); otherwise, it
4711/// returns the converted template argument. \p
Douglas Gregor463421d2009-03-03 04:44:36 +00004712/// InstantiatedParamType is the type of the non-type template
4713/// parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004714ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4715 QualType InstantiatedParamType, Expr *Arg,
4716 TemplateArgument &Converted,
4717 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004718 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004719
Douglas Gregor86560402009-02-10 23:36:10 +00004720 // If either the parameter has a dependent type or the argument is
4721 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00004722 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
4723 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004724 Converted = TemplateArgument(Arg);
John Wiegley01296292011-04-08 18:41:53 +00004725 return Owned(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00004726 }
Douglas Gregor86560402009-02-10 23:36:10 +00004727
4728 // C++ [temp.arg.nontype]p5:
4729 // The following conversions are performed on each expression used
4730 // as a non-type template-argument. If a non-type
4731 // template-argument cannot be converted to the type of the
4732 // corresponding template-parameter then the program is
4733 // ill-formed.
Douglas Gregor463421d2009-03-03 04:44:36 +00004734 QualType ParamType = InstantiatedParamType;
Douglas Gregorb90df602010-06-16 00:17:44 +00004735 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00004736 // C++11:
4737 // -- for a non-type template-parameter of integral or
4738 // enumeration type, conversions permitted in a converted
4739 // constant expression are applied.
4740 //
4741 // C++98:
4742 // -- for a non-type template-parameter of integral or
4743 // enumeration type, integral promotions (4.5) and integral
4744 // conversions (4.7) are applied.
4745
4746 if (CTAK == CTAK_Deduced &&
4747 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4748 // C++ [temp.deduct.type]p17:
4749 // If, in the declaration of a function template with a non-type
4750 // template-parameter, the non-type template-parameter is used
4751 // in an expression in the function parameter-list and, if the
4752 // corresponding template-argument is deduced, the
4753 // template-argument type shall match the type of the
4754 // template-parameter exactly, except that a template-argument
4755 // deduced from an array bound may be of any integral type.
4756 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4757 << Arg->getType().getUnqualifiedType()
4758 << ParamType.getUnqualifiedType();
4759 Diag(Param->getLocation(), diag::note_template_param_here);
4760 return ExprError();
4761 }
4762
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004763 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00004764 // We can't check arbitrary value-dependent arguments.
4765 // FIXME: If there's no viable conversion to the template parameter type,
4766 // we should be able to diagnose that prior to instantiation.
4767 if (Arg->isValueDependent()) {
4768 Converted = TemplateArgument(Arg);
4769 return Owned(Arg);
4770 }
4771
4772 // C++ [temp.arg.nontype]p1:
4773 // A template-argument for a non-type, non-template template-parameter
4774 // shall be one of:
4775 //
4776 // -- for a non-type template-parameter of integral or enumeration
4777 // type, a converted constant expression of the type of the
4778 // template-parameter; or
4779 llvm::APSInt Value;
4780 ExprResult ArgResult =
4781 CheckConvertedConstantExpression(Arg, ParamType, Value,
4782 CCEK_TemplateArg);
4783 if (ArgResult.isInvalid())
4784 return ExprError();
4785
4786 // Widen the argument value to sizeof(parameter type). This is almost
4787 // always a no-op, except when the parameter type is bool. In
4788 // that case, this may extend the argument from 1 bit to 8 bits.
4789 QualType IntegerType = ParamType;
4790 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4791 IntegerType = Enum->getDecl()->getIntegerType();
4792 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4793
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004794 Converted = TemplateArgument(Context, Value,
4795 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00004796 return ArgResult;
4797 }
4798
Richard Smith08b12f12011-10-27 22:11:44 +00004799 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4800 if (ArgResult.isInvalid())
4801 return ExprError();
4802 Arg = ArgResult.take();
4803
4804 QualType ArgType = Arg->getType();
4805
Douglas Gregor86560402009-02-10 23:36:10 +00004806 // C++ [temp.arg.nontype]p1:
4807 // A template-argument for a non-type, non-template
4808 // template-parameter shall be one of:
4809 //
4810 // -- an integral constant-expression of integral or enumeration
4811 // type; or
4812 // -- the name of a non-type template-parameter; or
4813 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004814 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00004815 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004816 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00004817 diag::err_template_arg_not_integral_or_enumeral)
4818 << ArgType << Arg->getSourceRange();
4819 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00004820 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00004821 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00004822 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4823 QualType T;
4824
4825 public:
4826 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00004827
4828 void diagnoseNotICE(Sema &S, SourceLocation Loc,
4829 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00004830 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
4831 }
4832 } Diagnoser(ArgType);
4833
4834 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
4835 false).take();
Richard Smithf4c51d92012-02-04 09:53:13 +00004836 if (!Arg)
4837 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00004838 }
4839
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004840 // From here on out, all we care about are the unqualified forms
4841 // of the parameter and argument types.
4842 ParamType = ParamType.getUnqualifiedType();
4843 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00004844
4845 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00004846 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00004847 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00004848 } else if (ParamType->isBooleanType()) {
4849 // This is an integral-to-boolean conversion.
John Wiegley01296292011-04-08 18:41:53 +00004850 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take();
Douglas Gregor86560402009-02-10 23:36:10 +00004851 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
4852 !ParamType->isEnumeralType()) {
4853 // This is an integral promotion or conversion.
John Wiegley01296292011-04-08 18:41:53 +00004854 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take();
Douglas Gregor86560402009-02-10 23:36:10 +00004855 } else {
4856 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004857 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00004858 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00004859 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00004860 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00004861 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00004862 }
4863
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004864 // Add the value of this argument to the list of converted
4865 // arguments. We use the bitwidth and signedness of the template
4866 // parameter.
4867 if (Arg->isValueDependent()) {
4868 // The argument is value-dependent. Create a new
4869 // TemplateArgument with the converted expression.
4870 Converted = TemplateArgument(Arg);
4871 return Owned(Arg);
4872 }
4873
Douglas Gregor52aba872009-03-14 00:20:21 +00004874 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00004875 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004876 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00004877
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004878 if (ParamType->isBooleanType()) {
4879 // Value must be zero or one.
4880 Value = Value != 0;
4881 unsigned AllowedBits = Context.getTypeSize(IntegerType);
4882 if (Value.getBitWidth() != AllowedBits)
4883 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004884 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004885 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004886 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004887
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004888 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004889 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00004890 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00004891 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004892 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004893 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004894
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004895 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004896 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004897 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004898 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004899 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4900 << Arg->getSourceRange();
4901 Diag(Param->getLocation(), diag::note_template_param_here);
4902 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004903
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004904 // Complain if we overflowed the template parameter's type.
4905 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004906 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004907 RequiredBits = OldValue.getActiveBits();
4908 else if (OldValue.isUnsigned())
4909 RequiredBits = OldValue.getActiveBits() + 1;
4910 else
4911 RequiredBits = OldValue.getMinSignedBits();
4912 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004913 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004914 diag::warn_template_arg_too_large)
4915 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4916 << Arg->getSourceRange();
4917 Diag(Param->getLocation(), diag::note_template_param_here);
4918 }
Douglas Gregor52aba872009-03-14 00:20:21 +00004919 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004920
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004921 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00004922 ParamType->isEnumeralType()
4923 ? Context.getCanonicalType(ParamType)
4924 : IntegerType);
John Wiegley01296292011-04-08 18:41:53 +00004925 return Owned(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00004926 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00004927
Richard Smith08b12f12011-10-27 22:11:44 +00004928 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00004929 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
4930
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004931 // Handle pointer-to-function, reference-to-function, and
4932 // pointer-to-member-function all in (roughly) the same way.
4933 if (// -- For a non-type template-parameter of type pointer to
4934 // function, only the function-to-pointer conversion (4.3) is
4935 // applied. If the template-argument represents a set of
4936 // overloaded functions (or a pointer to such), the matching
4937 // function is selected from the set (13.4).
4938 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004939 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004940 // -- For a non-type template-parameter of type reference to
4941 // function, no conversions apply. If the template-argument
4942 // represents a set of overloaded functions, the matching
4943 // function is selected from the set (13.4).
4944 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004945 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004946 // -- For a non-type template-parameter of type pointer to
4947 // member function, no conversions apply. If the
4948 // template-argument represents a set of overloaded member
4949 // functions, the matching member function is selected from
4950 // the set (13.4).
4951 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004952 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004953 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004954
Douglas Gregor064fdb22010-04-14 23:11:21 +00004955 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004956 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00004957 true,
4958 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004959 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00004960 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00004961
4962 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4963 ArgType = Arg->getType();
4964 } else
John Wiegley01296292011-04-08 18:41:53 +00004965 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00004966 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004967
John Wiegley01296292011-04-08 18:41:53 +00004968 if (!ParamType->isMemberPointerType()) {
4969 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4970 ParamType,
4971 Arg, Converted))
4972 return ExprError();
4973 return Owned(Arg);
4974 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004975
Douglas Gregor20fdef32012-04-10 17:08:25 +00004976 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
4977 Converted))
John Wiegley01296292011-04-08 18:41:53 +00004978 return ExprError();
4979 return Owned(Arg);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00004980 }
4981
Chris Lattner696197c2009-02-20 21:37:53 +00004982 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004983 // -- for a non-type template-parameter of type pointer to
4984 // object, qualification conversions (4.4) and the
4985 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00004986 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00004987 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004988 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00004989
John Wiegley01296292011-04-08 18:41:53 +00004990 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4991 ParamType,
4992 Arg, Converted))
4993 return ExprError();
4994 return Owned(Arg);
Douglas Gregora9faa442009-02-11 00:44:29 +00004995 }
Mike Stump11289f42009-09-09 15:08:12 +00004996
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004997 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004998 // -- For a non-type template-parameter of type reference to
4999 // object, no conversions apply. The type referred to by the
5000 // reference may be more cv-qualified than the (otherwise
5001 // identical) type of the template-argument. The
5002 // template-parameter is bound directly to the
5003 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005004 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005005 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005006
Douglas Gregor064fdb22010-04-14 23:11:21 +00005007 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005008 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5009 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005010 true,
5011 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005012 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005013 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005014
5015 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5016 ArgType = Arg->getType();
5017 } else
John Wiegley01296292011-04-08 18:41:53 +00005018 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005020
John Wiegley01296292011-04-08 18:41:53 +00005021 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5022 ParamType,
5023 Arg, Converted))
5024 return ExprError();
5025 return Owned(Arg);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005026 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005027
Douglas Gregor20fdef32012-04-10 17:08:25 +00005028 // Deal with parameters of type std::nullptr_t.
5029 if (ParamType->isNullPtrType()) {
5030 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5031 Converted = TemplateArgument(Arg);
5032 return Owned(Arg);
5033 }
5034
5035 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5036 case NPV_NotNullPointer:
5037 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5038 << Arg->getType() << ParamType;
5039 Diag(Param->getLocation(), diag::note_template_param_here);
5040 return ExprError();
5041
5042 case NPV_Error:
5043 return ExprError();
5044
5045 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005046 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Eli Friedmanb826a002012-09-26 02:36:12 +00005047 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005048 return Owned(Arg);
Douglas Gregor20fdef32012-04-10 17:08:25 +00005049 }
5050 }
5051
Douglas Gregor0e558532009-02-11 16:16:59 +00005052 // -- For a non-type template-parameter of type pointer to data
5053 // member, qualification conversions (4.4) are applied.
5054 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5055
Douglas Gregor20fdef32012-04-10 17:08:25 +00005056 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5057 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005058 return ExprError();
5059 return Owned(Arg);
Douglas Gregord32e0282009-02-09 23:23:08 +00005060}
5061
5062/// \brief Check a template argument against its corresponding
5063/// template template parameter.
5064///
5065/// This routine implements the semantics of C++ [temp.arg.template].
5066/// It returns true if an error occurred, and false otherwise.
5067bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005068 const TemplateArgumentLoc &Arg,
5069 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005070 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005071 TemplateDecl *Template = Name.getAsTemplateDecl();
5072 if (!Template) {
5073 // Any dependent template name is fine.
5074 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5075 return false;
5076 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005077
Richard Smith3f1b5d02011-05-05 21:57:07 +00005078 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005079 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005080 // the name of a class template or an alias template, expressed as an
5081 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005082 // primary class templates are considered when matching the
5083 // template template argument with the corresponding parameter;
5084 // partial specializations are not considered even if their
5085 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005086 //
5087 // Note that we also allow template template parameters here, which
5088 // will happen when we are dealing with, e.g., class template
5089 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005090 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005091 !isa<TemplateTemplateParmDecl>(Template) &&
5092 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005093 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005094 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005095 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005096 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005097 << Template;
5098 }
5099
Richard Smith1fde8ec2012-09-07 02:06:42 +00005100 TemplateParameterList *Params = Param->getTemplateParameters();
5101 if (Param->isExpandedParameterPack())
5102 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5103
Douglas Gregor85e0f662009-02-10 00:24:35 +00005104 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005105 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005106 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005107 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005108 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005109}
5110
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005111/// \brief Given a non-type template argument that refers to a
5112/// declaration and the type of its corresponding non-type template
5113/// parameter, produce an expression that properly refers to that
5114/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005115ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005116Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5117 QualType ParamType,
5118 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005119 // C++ [temp.param]p8:
5120 //
5121 // A non-type template-parameter of type "array of T" or
5122 // "function returning T" is adjusted to be of type "pointer to
5123 // T" or "pointer to function returning T", respectively.
5124 if (ParamType->isArrayType())
5125 ParamType = Context.getArrayDecayedType(ParamType);
5126 else if (ParamType->isFunctionType())
5127 ParamType = Context.getPointerType(ParamType);
5128
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005129 // For a NULL non-type template argument, return nullptr casted to the
5130 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005131 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005132 return ImpCastExprToType(
5133 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5134 ParamType,
5135 ParamType->getAs<MemberPointerType>()
5136 ? CK_NullToMemberPointer
5137 : CK_NullToPointer);
5138 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005139 assert(Arg.getKind() == TemplateArgument::Declaration &&
5140 "Only declaration template arguments permitted here");
5141
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005142 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5143
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005144 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005145 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5146 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005147 // If the value is a class member, we might have a pointer-to-member.
5148 // Determine whether the non-type template template parameter is of
5149 // pointer-to-member type. If so, we need to build an appropriate
5150 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5151 // would refer to the member itself.
5152 if (ParamType->isMemberPointerType()) {
5153 QualType ClassType
5154 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5155 NestedNameSpecifier *Qualifier
John McCallb268a282010-08-23 23:25:46 +00005156 = NestedNameSpecifier::Create(Context, 0, false,
5157 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005158 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005159 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005160
5161 // The actual value-ness of this is unimportant, but for
5162 // internal consistency's sake, references to instance methods
5163 // are r-values.
5164 ExprValueKind VK = VK_LValue;
5165 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5166 VK = VK_RValue;
5167
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005168 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005169 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005170 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005171 Loc,
5172 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005173 if (RefExpr.isInvalid())
5174 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005175
John McCalle3027922010-08-25 11:45:40 +00005176 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005177
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005178 // We might need to perform a trailing qualification conversion, since
5179 // the element type on the parameter could be more qualified than the
5180 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005181 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005182 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005183 ParamType.getUnqualifiedType(), false,
5184 ObjCLifetimeConversion))
John Wiegley01296292011-04-08 18:41:53 +00005185 RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005186
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005187 assert(!RefExpr.isInvalid() &&
5188 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005189 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005190 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005191 }
5192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005193
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005194 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005195
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005196 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005197 // When the non-type template parameter is a pointer, take the
5198 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005199 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005200 if (RefExpr.isInvalid())
5201 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005202
5203 if (T->isFunctionType() || T->isArrayType()) {
5204 // Decay functions and arrays.
John Wiegley01296292011-04-08 18:41:53 +00005205 RefExpr = DefaultFunctionArrayConversion(RefExpr.take());
5206 if (RefExpr.isInvalid())
5207 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005208
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005209 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005210 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005211
Douglas Gregorb242683d2010-04-01 18:32:35 +00005212 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005213 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005214 }
5215
John McCall7decc9e2010-11-18 06:31:45 +00005216 ExprValueKind VK = VK_RValue;
5217
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005218 // If the non-type template parameter has reference type, qualify the
5219 // resulting declaration reference with the extra qualifiers on the
5220 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005221 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5222 VK = VK_LValue;
5223 T = Context.getQualifiedType(T,
5224 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005225 } else if (isa<FunctionDecl>(VD)) {
5226 // References to functions are always lvalues.
5227 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005228 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005229
John McCall7decc9e2010-11-18 06:31:45 +00005230 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005231}
5232
5233/// \brief Construct a new expression that refers to the given
5234/// integral template argument with the given source-location
5235/// information.
5236///
5237/// This routine takes care of the mapping from an integral template
5238/// argument (which may have any integral type) to the appropriate
5239/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005240ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005241Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5242 SourceLocation Loc) {
5243 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005244 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005245 QualType OrigT = Arg.getIntegralType();
5246
5247 // If this is an enum type that we're instantiating, we need to use an integer
5248 // type the same size as the enumerator. We don't want to build an
5249 // IntegerLiteral with enum type. The integer type of an enum type can be of
5250 // any integral type with C++11 enum classes, make sure we create the right
5251 // type of literal for it.
5252 QualType T = OrigT;
5253 if (const EnumType *ET = OrigT->getAs<EnumType>())
5254 T = ET->getDecl()->getIntegerType();
5255
5256 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005257 if (T->isAnyCharacterType()) {
5258 CharacterLiteral::CharacterKind Kind;
5259 if (T->isWideCharType())
5260 Kind = CharacterLiteral::Wide;
5261 else if (T->isChar16Type())
5262 Kind = CharacterLiteral::UTF16;
5263 else if (T->isChar32Type())
5264 Kind = CharacterLiteral::UTF32;
5265 else
5266 Kind = CharacterLiteral::Ascii;
5267
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005268 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5269 Kind, T, Loc);
5270 } else if (T->isBooleanType()) {
5271 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5272 T, Loc);
5273 } else if (T->isNullPtrType()) {
5274 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5275 } else {
5276 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005277 }
5278
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005279 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005280 // FIXME: This is a hack. We need a better way to handle substituted
5281 // non-type template parameters.
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005282 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E, 0,
5283 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005284 Loc, Loc);
5285 }
5286
5287 return Owned(E);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005288}
5289
Douglas Gregor641040a2011-01-12 23:45:44 +00005290/// \brief Match two template parameters within template parameter lists.
5291static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5292 bool Complain,
5293 Sema::TemplateParameterListEqualKind Kind,
5294 SourceLocation TemplateArgLoc) {
5295 // Check the actual kind (type, non-type, template).
5296 if (Old->getKind() != New->getKind()) {
5297 if (Complain) {
5298 unsigned NextDiag = diag::err_template_param_different_kind;
5299 if (TemplateArgLoc.isValid()) {
5300 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5301 NextDiag = diag::note_template_param_different_kind;
5302 }
5303 S.Diag(New->getLocation(), NextDiag)
5304 << (Kind != Sema::TPL_TemplateMatch);
5305 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5306 << (Kind != Sema::TPL_TemplateMatch);
5307 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005308
Douglas Gregor641040a2011-01-12 23:45:44 +00005309 return false;
5310 }
5311
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005312 // Check that both are parameter packs are neither are parameter packs.
5313 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005314 // template template parameter, the template template parameter can have
5315 // a parameter pack where the template template argument does not.
5316 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5317 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5318 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005319 if (Complain) {
5320 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5321 if (TemplateArgLoc.isValid()) {
5322 S.Diag(TemplateArgLoc,
5323 diag::err_template_arg_template_params_mismatch);
5324 NextDiag = diag::note_template_parameter_pack_non_pack;
5325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005326
Douglas Gregor641040a2011-01-12 23:45:44 +00005327 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5328 : isa<NonTypeTemplateParmDecl>(New)? 1
5329 : 2;
5330 S.Diag(New->getLocation(), NextDiag)
5331 << ParamKind << New->isParameterPack();
5332 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5333 << ParamKind << Old->isParameterPack();
5334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005335
Douglas Gregor641040a2011-01-12 23:45:44 +00005336 return false;
5337 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005338
Douglas Gregor641040a2011-01-12 23:45:44 +00005339 // For non-type template parameters, check the type of the parameter.
5340 if (NonTypeTemplateParmDecl *OldNTTP
5341 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5342 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005343
Douglas Gregor641040a2011-01-12 23:45:44 +00005344 // If we are matching a template template argument to a template
5345 // template parameter and one of the non-type template parameter types
5346 // is dependent, then we must wait until template instantiation time
5347 // to actually compare the arguments.
5348 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5349 (OldNTTP->getType()->isDependentType() ||
5350 NewNTTP->getType()->isDependentType()))
5351 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005352
Douglas Gregor641040a2011-01-12 23:45:44 +00005353 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5354 if (Complain) {
5355 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5356 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005357 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005358 diag::err_template_arg_template_params_mismatch);
5359 NextDiag = diag::note_template_nontype_parm_different_type;
5360 }
5361 S.Diag(NewNTTP->getLocation(), NextDiag)
5362 << NewNTTP->getType()
5363 << (Kind != Sema::TPL_TemplateMatch);
5364 S.Diag(OldNTTP->getLocation(),
5365 diag::note_template_nontype_parm_prev_declaration)
5366 << OldNTTP->getType();
5367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005368
Douglas Gregor641040a2011-01-12 23:45:44 +00005369 return false;
5370 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005371
Douglas Gregor641040a2011-01-12 23:45:44 +00005372 return true;
5373 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005374
Douglas Gregor641040a2011-01-12 23:45:44 +00005375 // For template template parameters, check the template parameter types.
5376 // The template parameter lists of template template
5377 // parameters must agree.
5378 if (TemplateTemplateParmDecl *OldTTP
5379 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005380 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005381 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5382 OldTTP->getTemplateParameters(),
5383 Complain,
5384 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005385 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005386 : Kind),
5387 TemplateArgLoc);
5388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005389
Douglas Gregor641040a2011-01-12 23:45:44 +00005390 return true;
5391}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005392
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005393/// \brief Diagnose a known arity mismatch when comparing template argument
5394/// lists.
5395static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005396void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005397 TemplateParameterList *New,
5398 TemplateParameterList *Old,
5399 Sema::TemplateParameterListEqualKind Kind,
5400 SourceLocation TemplateArgLoc) {
5401 unsigned NextDiag = diag::err_template_param_list_different_arity;
5402 if (TemplateArgLoc.isValid()) {
5403 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5404 NextDiag = diag::note_template_param_list_different_arity;
5405 }
5406 S.Diag(New->getTemplateLoc(), NextDiag)
5407 << (New->size() > Old->size())
5408 << (Kind != Sema::TPL_TemplateMatch)
5409 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5410 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5411 << (Kind != Sema::TPL_TemplateMatch)
5412 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5413}
5414
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005415/// \brief Determine whether the given template parameter lists are
5416/// equivalent.
5417///
Mike Stump11289f42009-09-09 15:08:12 +00005418/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005419/// source code as part of a new template declaration.
5420///
5421/// \param Old The old template parameter list, typically found via
5422/// name lookup of the template declared with this template parameter
5423/// list.
5424///
5425/// \param Complain If true, this routine will produce a diagnostic if
5426/// the template parameter lists are not equivalent.
5427///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005428/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005429///
5430/// \param TemplateArgLoc If this source location is valid, then we
5431/// are actually checking the template parameter list of a template
5432/// argument (New) against the template parameter list of its
5433/// corresponding template template parameter (Old). We produce
5434/// slightly different diagnostics in this scenario.
5435///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005436/// \returns True if the template parameter lists are equal, false
5437/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005438bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005439Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5440 TemplateParameterList *Old,
5441 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005442 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005443 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005444 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5445 if (Complain)
5446 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5447 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005448
5449 return false;
5450 }
5451
Douglas Gregor641040a2011-01-12 23:45:44 +00005452 // C++0x [temp.arg.template]p3:
5453 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005454 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005455 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005456 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005457 // template-parameter-list of P. [...]
5458 TemplateParameterList::iterator NewParm = New->begin();
5459 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005460 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005461 OldParmEnd = Old->end();
5462 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005463 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5464 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005465 if (NewParm == NewParmEnd) {
5466 if (Complain)
5467 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5468 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005469
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005470 return false;
5471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005472
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005473 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5474 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005475 return false;
5476
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005477 ++NewParm;
5478 continue;
5479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005480
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005481 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005482 // [...] When P's template- parameter-list contains a template parameter
5483 // pack (14.5.3), the template parameter pack will match zero or more
5484 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005485 // template-parameter-list of A with the same type and form as the
5486 // template parameter pack in P (ignoring whether those template
5487 // parameters are template parameter packs).
5488 for (; NewParm != NewParmEnd; ++NewParm) {
5489 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5490 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005491 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005492 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005493 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005494
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005495 // Make sure we exhausted all of the arguments.
5496 if (NewParm != NewParmEnd) {
5497 if (Complain)
5498 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5499 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005500
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005501 return false;
5502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005503
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005504 return true;
5505}
5506
5507/// \brief Check whether a template can be declared within this scope.
5508///
5509/// If the template declaration is valid in this scope, returns
5510/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005511bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005512Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005513 if (!S)
5514 return false;
5515
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005516 // Find the nearest enclosing declaration scope.
5517 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5518 (S->getFlags() & Scope::TemplateParamScope) != 0)
5519 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005520
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005521 // C++ [temp]p4:
5522 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005523 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005524 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005525 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005526 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005527
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005528 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005529 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005530
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005531 // C++ [temp]p2:
5532 // A template-declaration can appear only as a namespace scope or
5533 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005534 if (Ctx) {
5535 if (Ctx->isFileContext())
5536 return false;
5537 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5538 // C++ [temp.mem]p2:
5539 // A local class shall not have member templates.
5540 if (RD->isLocalClass())
5541 return Diag(TemplateParams->getTemplateLoc(),
5542 diag::err_template_inside_local_class)
5543 << TemplateParams->getSourceRange();
5544 else
5545 return false;
5546 }
5547 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005548
Mike Stump11289f42009-09-09 15:08:12 +00005549 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005550 diag::err_template_outside_namespace_or_class_scope)
5551 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005552}
Douglas Gregor67a65642009-02-17 23:15:12 +00005553
Douglas Gregor54888652009-10-07 00:13:32 +00005554/// \brief Determine what kind of template specialization the given declaration
5555/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005556static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005557 if (!D)
5558 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005559
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005560 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5561 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005562 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5563 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005564 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5565 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005566
Douglas Gregor54888652009-10-07 00:13:32 +00005567 return TSK_Undeclared;
5568}
5569
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005570/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005571/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005572///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005573/// This routine determines whether a template specialization can be declared
5574/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005575///
5576/// \param S the semantic analysis object for which this check is being
5577/// performed.
5578///
5579/// \param Specialized the entity being specialized or instantiated, which
5580/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005581/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005582/// member class).
5583///
5584/// \param PrevDecl the previous declaration of this entity, if any.
5585///
5586/// \param Loc the location of the explicit specialization or instantiation of
5587/// this entity.
5588///
5589/// \param IsPartialSpecialization whether this is a partial specialization of
5590/// a class template.
5591///
Douglas Gregor54888652009-10-07 00:13:32 +00005592/// \returns true if there was an error that we cannot recover from, false
5593/// otherwise.
5594static bool CheckTemplateSpecializationScope(Sema &S,
5595 NamedDecl *Specialized,
5596 NamedDecl *PrevDecl,
5597 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005598 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005599 // Keep these "kind" numbers in sync with the %select statements in the
5600 // various diagnostics emitted by this routine.
5601 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005602 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005603 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005604 else if (isa<VarTemplateDecl>(Specialized))
5605 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005606 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005607 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005608 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005609 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005610 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005611 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005612 else if (isa<RecordDecl>(Specialized))
5613 EntityKind = 7;
5614 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5615 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005616 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005617 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005618 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005619 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005620 return true;
5621 }
5622
Douglas Gregorf47b9112009-02-25 22:02:03 +00005623 // C++ [temp.expl.spec]p2:
5624 // An explicit specialization shall be declared in the namespace
5625 // of which the template is a member, or, for member templates, in
5626 // the namespace of which the enclosing class or enclosing class
5627 // template is a member. An explicit specialization of a member
5628 // function, member class or static data member of a class
5629 // template shall be declared in the namespace of which the class
5630 // template is a member. Such a declaration may also be a
5631 // definition. If the declaration is not a definition, the
5632 // specialization may be defined later in the name- space in which
5633 // the explicit specialization was declared, or in a namespace
5634 // that encloses the one in which the explicit specialization was
5635 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005636 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005637 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005638 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005639 return true;
5640 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005641
Douglas Gregor40fb7442009-10-07 17:30:37 +00005642 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005643 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005644 // Do not warn for class scope explicit specialization during
5645 // instantiation, warning was already emitted during pattern
5646 // semantic analysis.
5647 if (!S.ActiveTemplateInstantiations.size())
5648 S.Diag(Loc, diag::ext_function_specialization_in_class)
5649 << Specialized;
5650 } else {
5651 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5652 << Specialized;
5653 return true;
5654 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005655 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005656
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005657 if (S.CurContext->isRecord() &&
5658 !S.CurContext->Equals(Specialized->getDeclContext())) {
5659 // Make sure that we're specializing in the right record context.
5660 // Otherwise, things can go horribly wrong.
5661 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5662 << Specialized;
5663 return true;
5664 }
5665
Douglas Gregore4b05162009-10-07 17:21:34 +00005666 // C++ [temp.class.spec]p6:
5667 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005668 // in any namespace scope in which its definition may be defined (14.5.1
5669 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005670 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005671 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005672 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005673
5674 // Make sure that this redeclaration (or definition) occurs in an enclosing
5675 // namespace.
5676 // Note that HandleDeclarator() performs this check for explicit
5677 // specializations of function templates, static data members, and member
5678 // functions, so we skip the check here for those kinds of entities.
5679 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5680 // Should we refactor that check, so that it occurs later?
5681 if (!DC->Encloses(SpecializedContext) &&
5682 !(isa<FunctionTemplateDecl>(Specialized) ||
5683 isa<FunctionDecl>(Specialized) ||
5684 isa<VarTemplateDecl>(Specialized) ||
5685 isa<VarDecl>(Specialized))) {
5686 if (isa<TranslationUnitDecl>(SpecializedContext))
5687 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5688 << EntityKind << Specialized;
5689 else if (isa<NamespaceDecl>(SpecializedContext))
5690 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
5691 << EntityKind << Specialized
5692 << cast<NamedDecl>(SpecializedContext);
5693 else
5694 llvm_unreachable("unexpected namespace context for specialization");
5695
5696 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5697 } else if ((!PrevDecl ||
5698 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5699 getTemplateSpecializationKind(PrevDecl) ==
5700 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005701 // C++ [temp.exp.spec]p2:
5702 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005703 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005704 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005705 // An explicit specialization of a member function, member class or
5706 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005707 // namespace of which the class template is a member.
5708 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005709 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005710 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005711 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005712 // C++11 [temp.explicit]p3:
5713 // An explicit instantiation shall appear in an enclosing namespace of its
5714 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005715 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005716 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005717 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005718 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005719 "DC encloses TU but isn't in enclosing namespace set");
5720 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005721 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005722 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5723 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005724 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005725 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005726 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005727 Diag = diag::ext_template_spec_decl_out_of_scope;
5728 else
5729 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5730 S.Diag(Loc, Diag)
5731 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5732 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005733
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005734 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00005735 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00005736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005737
Douglas Gregorf47b9112009-02-25 22:02:03 +00005738 return false;
5739}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005740
Richard Smith6056d5e2014-02-09 00:54:43 +00005741static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5742 if (!E->isInstantiationDependent())
5743 return SourceLocation();
5744 DependencyChecker Checker(Depth);
5745 Checker.TraverseStmt(E);
5746 if (Checker.Match && Checker.MatchLoc.isInvalid())
5747 return E->getSourceRange();
5748 return Checker.MatchLoc;
5749}
5750
5751static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5752 if (!TL.getType()->isDependentType())
5753 return SourceLocation();
5754 DependencyChecker Checker(Depth);
5755 Checker.TraverseTypeLoc(TL);
5756 if (Checker.Match && Checker.MatchLoc.isInvalid())
5757 return TL.getSourceRange();
5758 return Checker.MatchLoc;
5759}
5760
Larisse Voufo39a1e502013-08-06 01:03:05 +00005761/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005762/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005763static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005764 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5765 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005766 for (unsigned I = 0; I != NumArgs; ++I) {
5767 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005768 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005769 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5770 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005771 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005772
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005773 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005774 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005775
Eli Friedmanb826a002012-09-26 02:36:12 +00005776 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005777 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00005778
5779 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005780
Douglas Gregor98318c22011-01-03 21:37:45 +00005781 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005782 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5783 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00005784
5785 // Strip off any implicit casts we added as part of type checking.
5786 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5787 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005788
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005789 // C++ [temp.class.spec]p8:
5790 // A non-type argument is non-specialized if it is the name of a
5791 // non-type parameter. All other non-type arguments are
5792 // specialized.
5793 //
5794 // Below, we check the two conditions that only apply to
5795 // specialized non-type arguments, so skip any non-specialized
5796 // arguments.
5797 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00005798 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005799 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005800
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005801 // C++ [temp.class.spec]p9:
5802 // Within the argument list of a class template partial
5803 // specialization, the following restrictions apply:
5804 // -- A partially specialized non-type argument expression
5805 // shall not involve a template parameter of the partial
5806 // specialization except when the argument expression is a
5807 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00005808 SourceRange ParamUseRange =
5809 findTemplateParameter(Param->getDepth(), ArgExpr);
5810 if (ParamUseRange.isValid()) {
5811 if (IsDefaultArgument) {
5812 S.Diag(TemplateNameLoc,
5813 diag::err_dependent_non_type_arg_in_partial_spec);
5814 S.Diag(ParamUseRange.getBegin(),
5815 diag::note_dependent_non_type_default_arg_in_partial_spec)
5816 << ParamUseRange;
5817 } else {
5818 S.Diag(ParamUseRange.getBegin(),
5819 diag::err_dependent_non_type_arg_in_partial_spec)
5820 << ParamUseRange;
5821 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005822 return true;
5823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005824
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005825 // -- The type of a template parameter corresponding to a
5826 // specialized non-type argument shall not be dependent on a
5827 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00005828 //
5829 // FIXME: We need to delay this check until instantiation in some cases:
5830 //
5831 // template<template<typename> class X> struct A {
5832 // template<typename T, X<T> N> struct B;
5833 // template<typename T> struct B<T, 0>;
5834 // };
5835 // template<typename> using X = int;
5836 // A<X>::B<int, 0> b;
5837 ParamUseRange = findTemplateParameter(
5838 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
5839 if (ParamUseRange.isValid()) {
5840 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
5841 diag::err_dependent_typed_non_type_arg_in_partial_spec)
5842 << Param->getType() << ParamUseRange;
5843 S.Diag(Param->getLocation(), diag::note_template_param_here)
5844 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005845 return true;
5846 }
5847 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005848
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005849 return false;
5850}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005851
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005852/// \brief Check the non-type template arguments of a class template
5853/// partial specialization according to C++ [temp.class.spec]p9.
5854///
Richard Smith6056d5e2014-02-09 00:54:43 +00005855/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005856/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00005857/// template.
5858/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00005859/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00005860/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005861///
Richard Smith6056d5e2014-02-09 00:54:43 +00005862/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005863static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005864 Sema &S, SourceLocation TemplateNameLoc,
5865 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005866 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005867 const TemplateArgument *ArgList = TemplateArgs.data();
5868
5869 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5870 NonTypeTemplateParmDecl *Param
5871 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
5872 if (!Param)
5873 continue;
5874
Richard Smith6056d5e2014-02-09 00:54:43 +00005875 if (CheckNonTypeTemplatePartialSpecializationArgs(
5876 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005877 return true;
5878 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005879
5880 return false;
5881}
5882
John McCall48871652010-08-21 09:40:31 +00005883DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00005884Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
5885 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00005886 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005887 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00005888 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00005889 AttributeList *Attr,
5890 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00005891 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00005892
Richard Smith4b55a9c2014-04-17 03:29:33 +00005893 CXXScopeSpec &SS = TemplateId.SS;
5894
Abramo Bagnara60804e12011-03-18 15:16:37 +00005895 // NOTE: KWLoc is the location of the tag keyword. This will instead
5896 // store the location of the outermost template keyword in the declaration.
5897 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00005898 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
5899 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
5900 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
5901 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00005902
Douglas Gregor67a65642009-02-17 23:15:12 +00005903 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00005904 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00005905 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00005906 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
5907
5908 if (!ClassTemplate) {
5909 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005910 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00005911 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
5912 return true;
5913 }
Douglas Gregor67a65642009-02-17 23:15:12 +00005914
Douglas Gregor5c0405d2009-10-07 22:35:40 +00005915 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00005916 bool isPartialSpecialization = false;
5917
Douglas Gregorf47b9112009-02-25 22:02:03 +00005918 // Check the validity of the template headers that introduce this
5919 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00005920 // FIXME: We probably shouldn't complain about these headers for
5921 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00005922 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00005923 TemplateParameterList *TemplateParams =
5924 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00005925 KWLoc, TemplateNameLoc, SS, &TemplateId,
5926 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
5927 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00005928 if (Invalid)
5929 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005930
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005931 if (TemplateParams && TemplateParams->size() > 0) {
5932 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005933
Douglas Gregorec9518b2010-12-21 08:14:57 +00005934 if (TUK == TUK_Friend) {
5935 Diag(KWLoc, diag::err_partial_specialization_friend)
5936 << SourceRange(LAngleLoc, RAngleLoc);
5937 return true;
5938 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005939
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005940 // C++ [temp.class.spec]p10:
5941 // The template parameter list of a specialization shall not
5942 // contain default template argument values.
5943 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5944 Decl *Param = TemplateParams->getParam(I);
5945 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5946 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00005947 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005948 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00005949 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005950 }
5951 } else if (NonTypeTemplateParmDecl *NTTP
5952 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5953 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00005954 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005955 diag::err_default_arg_in_partial_spec)
5956 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00005957 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005958 }
5959 } else {
5960 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005961 if (TTP->hasDefaultArgument()) {
5962 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005963 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005964 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00005965 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00005966 }
5967 }
5968 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005969 } else if (TemplateParams) {
5970 if (TUK == TUK_Friend)
5971 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00005972 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005973 SourceRange(TemplateParams->getTemplateLoc(),
5974 TemplateParams->getRAngleLoc()))
5975 << SourceRange(LAngleLoc, RAngleLoc);
5976 else
5977 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00005978 } else {
5979 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00005980 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00005981
Douglas Gregor67a65642009-02-17 23:15:12 +00005982 // Check that the specialization uses the same tag kind as the
5983 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00005984 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5985 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00005986 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00005987 Kind, TUK == TUK_Definition, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00005988 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00005989 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00005990 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00005991 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00005992 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00005993 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00005994 diag::note_previous_use);
5995 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5996 }
5997
Douglas Gregorc40290e2009-03-09 23:48:35 +00005998 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00005999 TemplateArgumentListInfo TemplateArgs =
6000 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006001
Douglas Gregor14406932011-01-03 20:35:03 +00006002 // Check for unexpanded parameter packs in any of the template arguments.
6003 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006004 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006005 UPPC_PartialSpecialization))
6006 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006007
Douglas Gregor67a65642009-02-17 23:15:12 +00006008 // Check that the template argument list is well-formed for this
6009 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006010 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006011 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6012 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006013 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006014
Douglas Gregor2373c592009-05-31 09:31:02 +00006015 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006016 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006017 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006018 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006019 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6020 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006021 return true;
6022
Douglas Gregor678d76c2011-07-01 01:22:09 +00006023 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006024 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006025 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006026 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006027 TemplateArgs.size(),
6028 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006029 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6030 << ClassTemplate->getDeclName();
6031 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006032 }
6033 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006034
Douglas Gregor67a65642009-02-17 23:15:12 +00006035 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00006036 ClassTemplateSpecializationDecl *PrevDecl = 0;
6037
6038 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006039 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00006040 PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006041 = ClassTemplate->findPartialSpecialization(Converted.data(),
6042 Converted.size(),
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006043 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006044 else
6045 PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006046 = ClassTemplate->findSpecialization(Converted.data(),
6047 Converted.size(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006048
6049 ClassTemplateSpecializationDecl *Specialization = 0;
6050
Douglas Gregorf47b9112009-02-25 22:02:03 +00006051 // Check whether we can declare a class template specialization in
6052 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006053 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006054 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6055 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006056 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006057 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006058
Douglas Gregor15301382009-07-30 17:40:51 +00006059 // The canonical type
6060 QualType CanonType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006061 if (PrevDecl &&
Douglas Gregor2208a292009-09-26 20:57:03 +00006062 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00006063 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006064 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00006065 // arguments was referenced but not declared, or we're only
6066 // referencing this specialization as a friend, reuse that
Abramo Bagnara60804e12011-03-18 15:16:37 +00006067 // declaration node as our own, updating its source location and
6068 // the list of outer template parameters to reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006069 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00006070 Specialization->setLocation(TemplateNameLoc);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006071 if (TemplateParameterLists.size() > 0) {
6072 Specialization->setTemplateParameterListsInfo(Context,
6073 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006074 TemplateParameterLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006075 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006076 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00006077 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00006078 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006079 // Build the canonical type that describes the converted template
6080 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006081 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6082 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006083 Converted.data(),
6084 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006085
6086 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006087 ClassTemplate->getInjectedClassNameSpecialization())) {
6088 // C++ [temp.class.spec]p9b3:
6089 //
6090 // -- The argument list of the specialization shall not be identical
6091 // to the implicit argument list of the primary template.
6092 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006093 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006094 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006095 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6096 ClassTemplate->getIdentifier(),
6097 TemplateNameLoc,
6098 Attr,
6099 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006100 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006101 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006102 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006103 }
Douglas Gregor15301382009-07-30 17:40:51 +00006104
Douglas Gregor2373c592009-05-31 09:31:02 +00006105 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006106 ClassTemplatePartialSpecializationDecl *PrevPartial
6107 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006108 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006109 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006110 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006111 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006112 TemplateParams,
6113 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006114 Converted.data(),
6115 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006116 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006117 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006118 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006119 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006120 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006121 Partial->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006122 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006123 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006124 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006125
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006126 if (!PrevPartial)
6127 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006128 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006129
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006130 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006131 // template specialization, make a note of that.
6132 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6133 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006134
Douglas Gregor91772d12009-06-13 00:26:55 +00006135 // Check that all of the template parameters of the class template
6136 // partial specialization are deducible from the template
6137 // arguments. If not, this class template partial specialization
6138 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006139 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006140 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006141 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006142 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006143
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006144 if (!DeducibleParams.all()) {
6145 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006146 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006147 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006148 << SourceRange(TemplateNameLoc, RAngleLoc);
6149 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6150 if (!DeducibleParams[I]) {
6151 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6152 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006153 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006154 diag::note_partial_spec_unused_parameter)
6155 << Param->getDeclName();
6156 else
Mike Stump11289f42009-09-09 15:08:12 +00006157 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006158 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006159 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006160 }
6161 }
6162 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006163 } else {
6164 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006165 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006166 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006167 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006168 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006169 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006170 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006171 Converted.data(),
6172 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006173 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006174 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006175 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006176 Specialization->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006177 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006178 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006179 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006180
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006181 if (!PrevDecl)
6182 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006183
6184 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006185 }
6186
Douglas Gregor06db9f52009-10-12 20:18:28 +00006187 // C++ [temp.expl.spec]p6:
6188 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006189 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006190 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006191 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006192 // use occurs; no diagnostic is required.
6193 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006194 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006195 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006196 // Is there any previous explicit specialization declaration?
6197 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6198 Okay = true;
6199 break;
6200 }
6201 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006202
Douglas Gregorc854c662010-02-26 06:03:23 +00006203 if (!Okay) {
6204 SourceRange Range(TemplateNameLoc, RAngleLoc);
6205 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6206 << Context.getTypeDeclType(Specialization) << Range;
6207
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006208 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006209 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006210 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006211 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006212 return true;
6213 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006215
Douglas Gregor2208a292009-09-26 20:57:03 +00006216 // If this is not a friend, note that this is an explicit specialization.
6217 if (TUK != TUK_Friend)
6218 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006219
6220 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006221 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00006222 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006223 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006224 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006225 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006226 Diag(Def->getLocation(), diag::note_previous_definition);
6227 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006228 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006229 }
6230 }
6231
John McCall659a3372010-12-18 03:30:47 +00006232 if (Attr)
6233 ProcessDeclAttributeList(S, Specialization, Attr);
6234
Richard Smith034b94a2012-08-17 03:20:55 +00006235 // Add alignment attributes if necessary; these attributes are checked when
6236 // the ASTContext lays out the structure.
6237 if (TUK == TUK_Definition) {
6238 AddAlignmentAttributesForRecord(Specialization);
6239 AddMsStructLayoutForRecord(Specialization);
6240 }
6241
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006242 if (ModulePrivateLoc.isValid())
6243 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6244 << (isPartialSpecialization? 1 : 0)
6245 << FixItHint::CreateRemoval(ModulePrivateLoc);
6246
Douglas Gregord56a91e2009-02-26 22:19:44 +00006247 // Build the fully-sugared type for this class template
6248 // specialization as the user wrote in the specialization
6249 // itself. This means that we'll pretty-print the type retrieved
6250 // from the specialization's declaration the way that the user
6251 // actually wrote the specialization, rather than formatting the
6252 // name based on the "canonical" representation used to store the
6253 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006254 TypeSourceInfo *WrittenTy
6255 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6256 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006257 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006258 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006259 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006260 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006261
Douglas Gregor1e249f82009-02-25 22:18:32 +00006262 // C++ [temp.expl.spec]p9:
6263 // A template explicit specialization is in the scope of the
6264 // namespace in which the template was defined.
6265 //
6266 // We actually implement this paragraph where we set the semantic
6267 // context (in the creation of the ClassTemplateSpecializationDecl),
6268 // but we also maintain the lexical context where the actual
6269 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006270 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006271
Douglas Gregor67a65642009-02-17 23:15:12 +00006272 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006273 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006274 Specialization->startDefinition();
6275
Douglas Gregor2208a292009-09-26 20:57:03 +00006276 if (TUK == TUK_Friend) {
6277 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6278 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006279 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006280 /*FIXME:*/KWLoc);
6281 Friend->setAccess(AS_public);
6282 CurContext->addDecl(Friend);
6283 } else {
6284 // Add the specialization into its lexical context, so that it can
6285 // be seen when iterating through the list of declarations in that
6286 // context. However, specializations are not found by name lookup.
6287 CurContext->addDecl(Specialization);
6288 }
John McCall48871652010-08-21 09:40:31 +00006289 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006290}
Douglas Gregor333489b2009-03-27 23:10:48 +00006291
John McCall48871652010-08-21 09:40:31 +00006292Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006293 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006294 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006295 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006296 ActOnDocumentableDecl(NewDecl);
6297 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006298}
6299
John McCall48871652010-08-21 09:40:31 +00006300Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00006301 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006302 Declarator &D) {
Douglas Gregor17a7c122009-06-24 00:54:41 +00006303 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006304 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump11289f42009-09-09 15:08:12 +00006305
Douglas Gregor17a7c122009-06-24 00:54:41 +00006306 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00006307 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00006308 }
Mike Stump11289f42009-09-09 15:08:12 +00006309
Douglas Gregor17a7c122009-06-24 00:54:41 +00006310 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006311
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006312 D.setFunctionDefinitionKind(FDK_Definition);
John McCall48871652010-08-21 09:40:31 +00006313 Decl *DP = HandleDeclarator(ParentScope, D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006314 TemplateParameterLists);
Argyrios Kyrtzidis6fada2d2012-12-14 06:53:58 +00006315 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Douglas Gregor17a7c122009-06-24 00:54:41 +00006316}
6317
John McCall4f7ced62010-02-11 01:33:53 +00006318/// \brief Strips various properties off an implicit instantiation
6319/// that has just been explicitly specialized.
6320static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006321 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00006322
6323 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6324 FD->setInlineSpecified(false);
Jordan Rosea0a86be2013-03-08 22:25:36 +00006325
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006326 for (auto I : FD->params())
6327 I->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00006328 }
6329}
6330
Nico Webera8f80b32012-01-09 19:52:25 +00006331/// \brief Compute the diagnostic location for an explicit instantiation
6332// declaration or definition.
6333static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006334 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006335 // Explicit instantiations following a specialization have no effect and
6336 // hence no PointOfInstantiation. In that case, walk decl backwards
6337 // until a valid name loc is found.
6338 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006339 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6340 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006341 PrevDiagLoc = Prev->getLocation();
6342 }
6343 assert(PrevDiagLoc.isValid() &&
6344 "Explicit instantiation without point of instantiation?");
6345 return PrevDiagLoc;
6346}
6347
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006348/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006349/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006350/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006351/// new specialization/instantiation will have any effect.
6352///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006353/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006354/// instantiation.
6355///
6356/// \param NewTSK the kind of the new explicit specialization or instantiation.
6357///
6358/// \param PrevDecl the previous declaration of the entity.
6359///
6360/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6361///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006362/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006363/// declaration was instantiated (either implicitly or explicitly).
6364///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006365/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006366/// specialization or instantiation has no effect and should be ignored.
6367///
6368/// \returns true if there was an error that should prevent the introduction of
6369/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006370bool
6371Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6372 TemplateSpecializationKind NewTSK,
6373 NamedDecl *PrevDecl,
6374 TemplateSpecializationKind PrevTSK,
6375 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006376 bool &HasNoEffect) {
6377 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006378
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006379 switch (NewTSK) {
6380 case TSK_Undeclared:
6381 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006382 assert(
6383 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6384 "previous declaration must be implicit!");
6385 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006386
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006387 case TSK_ExplicitSpecialization:
6388 switch (PrevTSK) {
6389 case TSK_Undeclared:
6390 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006391 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006392 // explicitly specialized or has merely been mentioned without any
6393 // instantiation.
6394 return false;
6395
6396 case TSK_ImplicitInstantiation:
6397 if (PrevPointOfInstantiation.isInvalid()) {
6398 // The declaration itself has not actually been instantiated, so it is
6399 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006400 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006401 return false;
6402 }
6403 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006404
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006405 case TSK_ExplicitInstantiationDeclaration:
6406 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006407 assert((PrevTSK == TSK_ImplicitInstantiation ||
6408 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006409 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006410
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006411 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006412 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006413 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006414 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006415 // implicit instantiation to take place, in every translation unit in
6416 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006417 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006418 // Is there any previous explicit specialization declaration?
6419 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6420 return false;
6421 }
6422
Douglas Gregor1d957a32009-10-27 18:42:08 +00006423 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006424 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006425 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006426 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006427
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006428 return true;
6429 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006430
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006431 case TSK_ExplicitInstantiationDeclaration:
6432 switch (PrevTSK) {
6433 case TSK_ExplicitInstantiationDeclaration:
6434 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006435 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006436 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006437
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006438 case TSK_Undeclared:
6439 case TSK_ImplicitInstantiation:
6440 // We're explicitly instantiating something that may have already been
6441 // implicitly instantiated; that's fine.
6442 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006443
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006444 case TSK_ExplicitSpecialization:
6445 // C++0x [temp.explicit]p4:
6446 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006447 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006448 // specialization for that template, the explicit instantiation has no
6449 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006450 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006451 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006452
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006453 case TSK_ExplicitInstantiationDefinition:
6454 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006455 // If an entity is the subject of both an explicit instantiation
6456 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006457 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006458 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006459 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006460
6461 // Explicit instantiations following a specialization have no effect and
6462 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6463 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006464 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6465 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006466 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006467 return false;
6468 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006469
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006470 case TSK_ExplicitInstantiationDefinition:
6471 switch (PrevTSK) {
6472 case TSK_Undeclared:
6473 case TSK_ImplicitInstantiation:
6474 // We're explicitly instantiating something that may have already been
6475 // implicitly instantiated; that's fine.
6476 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006477
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006478 case TSK_ExplicitSpecialization:
6479 // C++ DR 259, C++0x [temp.explicit]p4:
6480 // For a given set of template parameters, if an explicit
6481 // instantiation of a template appears after a declaration of
6482 // an explicit specialization for that template, the explicit
6483 // instantiation has no effect.
6484 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006485 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006486 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006487 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006488 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006489 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6490 diag::ext_explicit_instantiation_after_specialization)
6491 << PrevDecl;
6492 Diag(PrevDecl->getLocation(),
6493 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006494 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006495 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006496
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006497 case TSK_ExplicitInstantiationDeclaration:
6498 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006499 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006500
6501 // C++0x [temp.explicit]p4:
6502 // For a given set of template parameters, if an explicit instantiation
6503 // of a template appears after a declaration of an explicit
6504 // specialization for that template, the explicit instantiation has no
6505 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006506 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006507 // Is there any previous explicit specialization declaration?
6508 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6509 HasNoEffect = true;
6510 break;
6511 }
6512 }
6513
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006514 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006515
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006516 case TSK_ExplicitInstantiationDefinition:
6517 // C++0x [temp.spec]p5:
6518 // For a given template and a given set of template-arguments,
6519 // - an explicit instantiation definition shall appear at most once
6520 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006521 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006522 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006523 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006524 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006525 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006526 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006527 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006528 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006529
David Blaikie83d382b2011-09-23 05:06:16 +00006530 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006531}
6532
John McCallb9c78482010-04-08 09:05:18 +00006533/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006534/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006535///
James Dennettf14a6e52012-06-15 22:23:43 +00006536/// The only possible way to get a dependent function template specialization
6537/// is with a friend declaration, like so:
6538///
6539/// \code
6540/// template \<class T> void foo(T);
6541/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006542/// friend void foo<>(T);
6543/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006544/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006545///
6546/// There really isn't any useful analysis we can do here, so we
6547/// just store the information.
6548bool
6549Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6550 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6551 LookupResult &Previous) {
6552 // Remove anything from Previous that isn't a function template in
6553 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006554 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006555 LookupResult::Filter F = Previous.makeFilter();
6556 while (F.hasNext()) {
6557 NamedDecl *D = F.next()->getUnderlyingDecl();
6558 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006559 !FDLookupContext->InEnclosingNamespaceSetOf(
6560 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006561 F.erase();
6562 }
6563 F.done();
6564
6565 // Should this be diagnosed here?
6566 if (Previous.empty()) return true;
6567
6568 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6569 ExplicitTemplateArgs);
6570 return false;
6571}
6572
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006573/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006574/// specialization.
6575///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006576/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006577/// explicit function template specialization. On successful completion,
6578/// the function declaration \p FD will become a function template
6579/// specialization.
6580///
6581/// \param FD the function declaration, which will be updated to become a
6582/// function template specialization.
6583///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006584/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6585/// if any. Note that this may be valid info even when 0 arguments are
6586/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6587/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006588///
Francois Pichet3a44e432011-07-08 06:21:47 +00006589/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006590/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006591bool Sema::CheckFunctionTemplateSpecialization(
6592 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6593 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006594 // The set of function template specializations that could match this
6595 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006596 UnresolvedSet<8> Candidates;
Larisse Voufo98b20f12013-07-19 23:00:19 +00006597 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006598
Sebastian Redl50c68252010-08-31 00:36:30 +00006599 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006600 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6601 I != E; ++I) {
6602 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6603 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006604 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006605 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006606 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6607 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006608 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006609
Richard Smith574f4f62013-01-14 05:37:29 +00006610 // When matching a constexpr member function template specialization
6611 // against the primary template, we don't yet know whether the
6612 // specialization has an implicit 'const' (because we don't know whether
6613 // it will be a static member function until we know which template it
6614 // specializes), so adjust it now assuming it specializes this template.
6615 QualType FT = FD->getType();
6616 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006617 CXXMethodDecl *OldMD =
6618 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006619 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006620 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006621 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6622 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006623 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006624 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006625 }
6626 }
6627
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006628 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006629 // A trailing template-argument can be left unspecified in the
6630 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006631 // provided it can be deduced from the function argument type.
6632 // Perform template argument deduction to determine whether we may be
6633 // specializing this template.
6634 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006635 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006636 FunctionDecl *Specialization = 0;
Richard Smith32983682013-12-14 03:18:05 +00006637 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6638 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6639 ExplicitTemplateArgs, FT, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006640 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006641 // that we can provide nifty diagnostics.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006642 FailedCandidates.addCandidate()
6643 .set(FunTmpl->getTemplatedDecl(),
6644 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006645 (void)TDK;
6646 continue;
6647 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006648
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006649 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00006650 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006651 }
6652 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006653
Douglas Gregor5de279c2009-09-26 03:41:46 +00006654 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006655 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006656 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006657 FD->getLocation(),
6658 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6659 PDiag(diag::err_function_template_spec_ambiguous)
6660 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
6661 PDiag(diag::note_function_template_spec_matched));
6662
John McCall58cc69d2010-01-27 01:50:18 +00006663 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006664 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006665
6666 // Ignore access information; it doesn't figure into redeclaration checking.
6667 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006668
6669 FunctionTemplateSpecializationInfo *SpecInfo
6670 = Specialization->getTemplateSpecializationInfo();
6671 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006672
6673 // Note: do not overwrite location info if previous template
6674 // specialization kind was explicit.
6675 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006676 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006677 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006678 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6679 // function can differ from the template declaration with respect to
6680 // the constexpr specifier.
6681 Specialization->setConstexpr(FD->isConstexpr());
6682 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006683
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006684 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006685 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006686
6687 // If this is a friend declaration, then we're not really declaring
6688 // an explicit specialization.
6689 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006690
Douglas Gregor54888652009-10-07 00:13:32 +00006691 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006692 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006693 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006694 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006695 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006696 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006697 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006698
6699 // C++ [temp.expl.spec]p6:
6700 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006701 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006702 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006703 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006704 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006705 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006706 if (!isFriend &&
6707 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006708 TSK_ExplicitSpecialization,
6709 Specialization,
6710 SpecInfo->getTemplateSpecializationKind(),
6711 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006712 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006713 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006714
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006715 // Mark the prior declaration as an explicit specialization, so that later
6716 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006717 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00006718 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006719 MarkUnusedFileScopedDecl(Specialization);
6720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006721
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006722 // Turn the given function declaration into a function template
6723 // specialization, with the template arguments from the previous
6724 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006725 // Take copies of (semantic and syntactic) template argument lists.
6726 const TemplateArgumentList* TemplArgs = new (Context)
6727 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Douglas Gregord5058122010-02-11 01:19:42 +00006728 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006729 TemplArgs, /*InsertPos=*/0,
6730 SpecInfo->getTemplateSpecializationKind(),
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00006731 ExplicitTemplateArgs);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006732
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006733 // The "previous declaration" for this function template specialization is
6734 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00006735 Previous.clear();
6736 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006737 return false;
6738}
6739
Douglas Gregor86d142a2009-10-08 07:24:58 +00006740/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006741/// specialization.
6742///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006743/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006744/// explicit member function specialization. On successful completion,
6745/// the function declaration \p FD will become a member function
6746/// specialization.
6747///
Douglas Gregor86d142a2009-10-08 07:24:58 +00006748/// \param Member the member declaration, which will be updated to become a
6749/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006750///
John McCall1f82f242009-11-18 22:49:29 +00006751/// \param Previous the set of declarations, one of which may be specialized
6752/// by this function specialization; the set will be modified to contain the
6753/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006754bool
John McCall1f82f242009-11-18 22:49:29 +00006755Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006756 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00006757
Douglas Gregor86d142a2009-10-08 07:24:58 +00006758 // Try to find the member we are instantiating.
6759 NamedDecl *Instantiation = 0;
6760 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006761 MemberSpecializationInfo *MSInfo = 0;
6762
John McCall1f82f242009-11-18 22:49:29 +00006763 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006764 // Nowhere to look anyway.
6765 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006766 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6767 I != E; ++I) {
6768 NamedDecl *D = (*I)->getUnderlyingDecl();
6769 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00006770 QualType Adjusted = Function->getType();
6771 if (!hasExplicitCallingConv(Adjusted))
6772 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6773 if (Context.hasSameType(Adjusted, Method->getType())) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006774 Instantiation = Method;
6775 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006776 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006777 break;
6778 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006779 }
6780 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00006781 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006782 VarDecl *PrevVar;
6783 if (Previous.isSingleResult() &&
6784 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00006785 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00006786 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006787 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006788 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006789 }
6790 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006791 CXXRecordDecl *PrevRecord;
6792 if (Previous.isSingleResult() &&
6793 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6794 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006795 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006796 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006797 }
Richard Smith7d137e32012-03-23 03:33:32 +00006798 } else if (isa<EnumDecl>(Member)) {
6799 EnumDecl *PrevEnum;
6800 if (Previous.isSingleResult() &&
6801 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6802 Instantiation = PrevEnum;
6803 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6804 MSInfo = PrevEnum->getMemberSpecializationInfo();
6805 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006807
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006808 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006809 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006810 // specializations are always out-of-line, the caller will complain about
6811 // this mismatch later.
6812 return false;
6813 }
John McCalle820e5e2010-04-13 20:37:33 +00006814
6815 // If this is a friend, just bail out here before we start turning
6816 // things into explicit specializations.
6817 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6818 // Preserve instantiation information.
6819 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6820 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6821 cast<CXXMethodDecl>(InstantiatedFrom),
6822 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6823 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6824 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6825 cast<CXXRecordDecl>(InstantiatedFrom),
6826 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6827 }
6828
6829 Previous.clear();
6830 Previous.addDecl(Instantiation);
6831 return false;
6832 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006833
Douglas Gregor86d142a2009-10-08 07:24:58 +00006834 // Make sure that this is a specialization of a member.
6835 if (!InstantiatedFrom) {
6836 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6837 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006838 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6839 return true;
6840 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006841
Douglas Gregor06db9f52009-10-12 20:18:28 +00006842 // C++ [temp.expl.spec]p6:
6843 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00006844 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006845 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006846 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006847 // use occurs; no diagnostic is required.
6848 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00006849
Abramo Bagnara8075c852010-06-12 07:44:57 +00006850 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00006851 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
6852 TSK_ExplicitSpecialization,
6853 Instantiation,
6854 MSInfo->getTemplateSpecializationKind(),
6855 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006856 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006857 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006858
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006859 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006860 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00006861 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006862 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006863 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006864 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00006865
Douglas Gregor86d142a2009-10-08 07:24:58 +00006866 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006867 // the original declaration to note that it is an explicit specialization
6868 // (if it was previously an implicit instantiation). This latter step
6869 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00006870 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006871 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
6872 if (InstantiationFunction->getTemplateSpecializationKind() ==
6873 TSK_ImplicitInstantiation) {
6874 InstantiationFunction->setTemplateSpecializationKind(
6875 TSK_ExplicitSpecialization);
6876 InstantiationFunction->setLocation(Member->getLocation());
6877 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006878
Douglas Gregor86d142a2009-10-08 07:24:58 +00006879 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
6880 cast<CXXMethodDecl>(InstantiatedFrom),
6881 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006882 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00006883 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006884 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
6885 if (InstantiationVar->getTemplateSpecializationKind() ==
6886 TSK_ImplicitInstantiation) {
6887 InstantiationVar->setTemplateSpecializationKind(
6888 TSK_ExplicitSpecialization);
6889 InstantiationVar->setLocation(Member->getLocation());
6890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006891
Larisse Voufo39a1e502013-08-06 01:03:05 +00006892 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
6893 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006894 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00006895 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006896 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
6897 if (InstantiationClass->getTemplateSpecializationKind() ==
6898 TSK_ImplicitInstantiation) {
6899 InstantiationClass->setTemplateSpecializationKind(
6900 TSK_ExplicitSpecialization);
6901 InstantiationClass->setLocation(Member->getLocation());
6902 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006903
Douglas Gregor86d142a2009-10-08 07:24:58 +00006904 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006905 cast<CXXRecordDecl>(InstantiatedFrom),
6906 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00006907 } else {
6908 assert(isa<EnumDecl>(Member) && "Only member enums remain");
6909 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
6910 if (InstantiationEnum->getTemplateSpecializationKind() ==
6911 TSK_ImplicitInstantiation) {
6912 InstantiationEnum->setTemplateSpecializationKind(
6913 TSK_ExplicitSpecialization);
6914 InstantiationEnum->setLocation(Member->getLocation());
6915 }
6916
6917 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
6918 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00006919 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006920
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006921 // Save the caller the trouble of having to figure out which declaration
6922 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00006923 Previous.clear();
6924 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006925 return false;
6926}
6927
Douglas Gregore47f5a72009-10-14 23:41:34 +00006928/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00006929///
6930/// \returns true if a serious error occurs, false otherwise.
6931static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00006932 SourceLocation InstLoc,
6933 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006934 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
6935 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006936
Douglas Gregor6cc1df52010-07-13 00:10:04 +00006937 if (CurContext->isRecord()) {
6938 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
6939 << D;
6940 return true;
6941 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006942
Richard Smith050d2612011-10-18 02:28:33 +00006943 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006944 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00006945 // template. If the name declared in the explicit instantiation is an
6946 // unqualified name, the explicit instantiation shall appear in the
6947 // namespace where its template is declared or, if that namespace is inline
6948 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00006949 //
6950 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00006951 if (WasQualifiedName) {
6952 if (CurContext->Encloses(OrigContext))
6953 return false;
6954 } else {
6955 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
6956 return false;
6957 }
6958
6959 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
6960 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006961 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006962 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00006963 diag::err_explicit_instantiation_out_of_scope :
6964 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00006965 << D << NS;
6966 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006968 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00006969 diag::err_explicit_instantiation_unqualified_wrong_namespace :
6970 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
6971 << D << NS;
6972 } else
6973 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006974 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00006975 diag::err_explicit_instantiation_must_be_global :
6976 diag::warn_explicit_instantiation_must_be_global_0x)
6977 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00006978 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00006979 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00006980}
6981
6982/// \brief Determine whether the given scope specifier has a template-id in it.
6983static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
6984 if (!SS.isSet())
6985 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006986
Richard Smith050d2612011-10-18 02:28:33 +00006987 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006988 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00006989 // or a static data member of a class template specialization, the name of
6990 // the class template specialization in the qualified-id for the member
6991 // name shall be a simple-template-id.
6992 //
6993 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00006994 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
6995 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00006996 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00006997 if (isa<TemplateSpecializationType>(T))
6998 return true;
6999
7000 return false;
7001}
7002
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007003// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007004DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007005Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007006 SourceLocation ExternLoc,
7007 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007008 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007009 SourceLocation KWLoc,
7010 const CXXScopeSpec &SS,
7011 TemplateTy TemplateD,
7012 SourceLocation TemplateNameLoc,
7013 SourceLocation LAngleLoc,
7014 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007015 SourceLocation RAngleLoc,
7016 AttributeList *Attr) {
7017 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007018 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007019 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007020 // Check that the specialization uses the same tag kind as the
7021 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007022 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7023 assert(Kind != TTK_Enum &&
7024 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007025
7026 if (isa<TypeAliasTemplateDecl>(TD)) {
7027 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7028 Diag(TD->getTemplatedDecl()->getLocation(),
7029 diag::note_previous_use);
7030 return true;
7031 }
7032
7033 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7034
Douglas Gregord9034f02009-05-14 16:41:31 +00007035 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007036 Kind, /*isDefinition*/false, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00007037 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007038 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007039 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007040 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007041 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007042 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007043 diag::note_previous_use);
7044 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7045 }
7046
Douglas Gregore47f5a72009-10-14 23:41:34 +00007047 // C++0x [temp.explicit]p2:
7048 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007049 // definition and an explicit instantiation declaration. An explicit
7050 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00007051 TemplateSpecializationKind TSK
7052 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7053 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007054
Douglas Gregora1f49972009-05-13 00:25:59 +00007055 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007056 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007057 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007058
7059 // Check that the template argument list is well-formed for this
7060 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007061 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007062 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7063 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007064 return true;
7065
Douglas Gregora1f49972009-05-13 00:25:59 +00007066 // Find the class template specialization declaration that
7067 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00007068 void *InsertPos = 0;
7069 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007070 = ClassTemplate->findSpecialization(Converted.data(),
7071 Converted.size(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007072
Abramo Bagnara8075c852010-06-12 07:44:57 +00007073 TemplateSpecializationKind PrevDecl_TSK
7074 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7075
Douglas Gregor54888652009-10-07 00:13:32 +00007076 // C++0x [temp.explicit]p2:
7077 // [...] An explicit instantiation shall appear in an enclosing
7078 // namespace of its template. [...]
7079 //
7080 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007081 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7082 SS.isSet()))
7083 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007084
Douglas Gregora1f49972009-05-13 00:25:59 +00007085 ClassTemplateSpecializationDecl *Specialization = 0;
7086
Abramo Bagnara8075c852010-06-12 07:44:57 +00007087 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007088 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007089 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007090 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007091 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007092 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007093 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007094
Abramo Bagnara8075c852010-06-12 07:44:57 +00007095 // Even though HasNoEffect == true means that this explicit instantiation
7096 // has no effect on semantics, we go on to put its syntax in the AST.
7097
7098 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7099 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007100 // Since the only prior class template specialization with these
7101 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007102 // declaration node as our own, updating the source location
7103 // for the template name to reflect our new declaration.
7104 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007105 Specialization = PrevDecl;
7106 Specialization->setLocation(TemplateNameLoc);
7107 PrevDecl = 0;
7108 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007109 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007110
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007111 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007112 // Create a new class template specialization declaration node for
7113 // this explicit specialization.
7114 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007115 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007116 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007117 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007118 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007119 Converted.data(),
7120 Converted.size(),
7121 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007122 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007123
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007124 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007125 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007126 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007127 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007128 }
7129
7130 // Build the fully-sugared type for this explicit instantiation as
7131 // the user wrote in the explicit instantiation itself. This means
7132 // that we'll pretty-print the type retrieved from the
7133 // specialization's declaration the way that the user actually wrote
7134 // the explicit instantiation, rather than formatting the name based
7135 // on the "canonical" representation used to store the template
7136 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007137 TypeSourceInfo *WrittenTy
7138 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7139 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007140 Context.getTypeDeclType(Specialization));
7141 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007142
Abramo Bagnara8075c852010-06-12 07:44:57 +00007143 // Set source locations for keywords.
7144 Specialization->setExternLoc(ExternLoc);
7145 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007146 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007147
Rafael Espindola0b062072012-01-03 06:04:21 +00007148 if (Attr)
7149 ProcessDeclAttributeList(S, Specialization, Attr);
7150
Abramo Bagnara8075c852010-06-12 07:44:57 +00007151 // Add the explicit instantiation into its lexical context. However,
7152 // since explicit instantiations are never found by name lookup, we
7153 // just put it into the declaration context directly.
7154 Specialization->setLexicalDeclContext(CurContext);
7155 CurContext->addDecl(Specialization);
7156
7157 // Syntax is now OK, so return if it has no other effect on semantics.
7158 if (HasNoEffect) {
7159 // Set the template specialization kind.
7160 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007161 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007162 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007163
7164 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007165 // A definition of a class template or class member template
7166 // shall be in scope at the point of the explicit instantiation of
7167 // the class template or class member template.
7168 //
7169 // This check comes when we actually try to perform the
7170 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007171 ClassTemplateSpecializationDecl *Def
7172 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007173 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007174 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007175 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007176 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007177 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007178 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7179 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007180
Douglas Gregor1d957a32009-10-27 18:42:08 +00007181 // Instantiate the members of this class template specialization.
7182 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007183 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007184 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007185 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7186
7187 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7188 // TSK_ExplicitInstantiationDefinition
7189 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7190 TSK == TSK_ExplicitInstantiationDefinition)
7191 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007192
Douglas Gregor12e49d32009-10-15 22:53:21 +00007193 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007194 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007195
Abramo Bagnara8075c852010-06-12 07:44:57 +00007196 // Set the template specialization kind.
7197 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007198 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007199}
7200
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007201// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007202DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007203Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007204 SourceLocation ExternLoc,
7205 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007206 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007207 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007208 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007209 IdentifierInfo *Name,
7210 SourceLocation NameLoc,
7211 AttributeList *Attr) {
7212
Douglas Gregord6ab8742009-05-28 23:31:59 +00007213 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007214 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007215 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007216 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007217 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007218 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007219 SourceLocation(), false, TypeResult(),
7220 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007221 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7222
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007223 if (!TagD)
7224 return true;
7225
John McCall48871652010-08-21 09:40:31 +00007226 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007227 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007228
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007229 if (Tag->isInvalidDecl())
7230 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007231
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007232 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7233 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7234 if (!Pattern) {
7235 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7236 << Context.getTypeDeclType(Record);
7237 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7238 return true;
7239 }
7240
Douglas Gregore47f5a72009-10-14 23:41:34 +00007241 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007242 // If the explicit instantiation is for a class or member class, the
7243 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007244 // simple-template-id.
7245 //
7246 // C++98 has the same restriction, just worded differently.
7247 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007248 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007249 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007250
Douglas Gregore47f5a72009-10-14 23:41:34 +00007251 // C++0x [temp.explicit]p2:
7252 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007253 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007254 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007255 TemplateSpecializationKind TSK
7256 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7257 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007258
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007259 // C++0x [temp.explicit]p2:
7260 // [...] An explicit instantiation shall appear in an enclosing
7261 // namespace of its template. [...]
7262 //
7263 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007264 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007265
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007266 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007267 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007268 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007269 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007270 PrevDecl = Record;
7271 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007272 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007273 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007274 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007275 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007276 PrevDecl,
7277 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007278 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007279 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007280 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007281 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007282 return TagD;
7283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007284
Douglas Gregor12e49d32009-10-15 22:53:21 +00007285 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007286 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007287 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007288 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007289 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007290 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007291 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007292 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007293 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007294 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7295 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007296 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7297 << Pattern;
7298 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007299 } else {
7300 if (InstantiateClass(NameLoc, Record, Def,
7301 getTemplateInstantiationArgs(Record),
7302 TSK))
7303 return true;
7304
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007305 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007306 if (!RecordDef)
7307 return true;
7308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007309 }
7310
Douglas Gregor1d957a32009-10-27 18:42:08 +00007311 // Instantiate all of the members of the class.
7312 InstantiateClassMembers(NameLoc, RecordDef,
7313 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007314
Douglas Gregor88d292c2010-05-13 16:44:06 +00007315 if (TSK == TSK_ExplicitInstantiationDefinition)
7316 MarkVTableUsed(NameLoc, RecordDef, true);
7317
Mike Stump87c57ac2009-05-16 07:39:55 +00007318 // FIXME: We don't have any representation for explicit instantiations of
7319 // member classes. Such a representation is not needed for compilation, but it
7320 // should be available for clients that want to see all of the declarations in
7321 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007322 return TagD;
7323}
7324
John McCallfaf5fb42010-08-26 23:41:50 +00007325DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7326 SourceLocation ExternLoc,
7327 SourceLocation TemplateLoc,
7328 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007329 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007330 // TODO: check if/when DNInfo should replace Name.
7331 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7332 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007333 if (!Name) {
7334 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007335 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007336 diag::err_explicit_instantiation_requires_name)
7337 << D.getDeclSpec().getSourceRange()
7338 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007339
Douglas Gregor450f00842009-09-25 18:43:00 +00007340 return true;
7341 }
7342
7343 // The scope passed in may not be a decl scope. Zip up the scope tree until
7344 // we find one that is.
7345 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7346 (S->getFlags() & Scope::TemplateParamScope) != 0)
7347 S = S->getParent();
7348
7349 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007350 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7351 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007352 if (R.isNull())
7353 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007354
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007355 // C++ [dcl.stc]p1:
7356 // A storage-class-specifier shall not be specified in [...] an explicit
7357 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007358 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007359 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7360 << Name;
7361 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007362 } else if (D.getDeclSpec().getStorageClassSpec()
7363 != DeclSpec::SCS_unspecified) {
7364 // Complain about then remove the storage class specifier.
7365 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7366 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7367
7368 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007369 }
7370
Douglas Gregor3c74d412009-10-14 20:14:33 +00007371 // C++0x [temp.explicit]p1:
7372 // [...] An explicit instantiation of a function template shall not use the
7373 // inline or constexpr specifiers.
7374 // Presumably, this also applies to member functions of class templates as
7375 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007376 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007377 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007378 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007379 diag::err_explicit_instantiation_inline :
7380 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007381 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007382 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007383 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7384 // not already specified.
7385 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7386 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007387
Douglas Gregore47f5a72009-10-14 23:41:34 +00007388 // C++0x [temp.explicit]p2:
7389 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007390 // definition and an explicit instantiation declaration. An explicit
7391 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007392 TemplateSpecializationKind TSK
7393 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7394 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007395
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007396 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007397 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007398
7399 if (!R->isFunctionType()) {
7400 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007401 // A [...] static data member of a class template can be explicitly
7402 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007403 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007404 // C++1y [temp.explicit]p1:
7405 // A [...] variable [...] template specialization can be explicitly
7406 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007407 if (Previous.isAmbiguous())
7408 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007409
John McCall67c00872009-12-02 08:25:40 +00007410 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007411 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007412
Larisse Voufo39a1e502013-08-06 01:03:05 +00007413 if (!PrevTemplate) {
7414 if (!Prev || !Prev->isStaticDataMember()) {
7415 // We expect to see a data data member here.
7416 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7417 << Name;
7418 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7419 P != PEnd; ++P)
7420 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7421 return true;
7422 }
7423
7424 if (!Prev->getInstantiatedFromStaticDataMember()) {
7425 // FIXME: Check for explicit specialization?
7426 Diag(D.getIdentifierLoc(),
7427 diag::err_explicit_instantiation_data_member_not_instantiated)
7428 << Prev;
7429 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7430 // FIXME: Can we provide a note showing where this was declared?
7431 return true;
7432 }
7433 } else {
7434 // Explicitly instantiate a variable template.
7435
7436 // C++1y [dcl.spec.auto]p6:
7437 // ... A program that uses auto or decltype(auto) in a context not
7438 // explicitly allowed in this section is ill-formed.
7439 //
7440 // This includes auto-typed variable template instantiations.
7441 if (R->isUndeducedType()) {
7442 Diag(T->getTypeLoc().getLocStart(),
7443 diag::err_auto_not_allowed_var_inst);
7444 return true;
7445 }
7446
Richard Smithef985ac2013-09-18 02:10:12 +00007447 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7448 // C++1y [temp.explicit]p3:
7449 // If the explicit instantiation is for a variable, the unqualified-id
7450 // in the declaration shall be a template-id.
7451 Diag(D.getIdentifierLoc(),
7452 diag::err_explicit_instantiation_without_template_id)
7453 << PrevTemplate;
7454 Diag(PrevTemplate->getLocation(),
7455 diag::note_explicit_instantiation_here);
7456 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007457 }
7458
Richard Smithef985ac2013-09-18 02:10:12 +00007459 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007460 TemplateArgumentListInfo TemplateArgs =
7461 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007462
Larisse Voufo39a1e502013-08-06 01:03:05 +00007463 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7464 D.getIdentifierLoc(), TemplateArgs);
7465 if (Res.isInvalid())
7466 return true;
7467
7468 // Ignore access control bits, we don't need them for redeclaration
7469 // checking.
7470 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007472
Douglas Gregore47f5a72009-10-14 23:41:34 +00007473 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007474 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007475 // or a static data member of a class template specialization, the name of
7476 // the class template specialization in the qualified-id for the member
7477 // name shall be a simple-template-id.
7478 //
7479 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007480 //
Richard Smith5977d872013-09-18 21:55:14 +00007481 // This does not apply to variable template specializations, where the
7482 // template-id is in the unqualified-id instead.
7483 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007484 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007485 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007486 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007487
Douglas Gregore47f5a72009-10-14 23:41:34 +00007488 // Check the scope of this explicit instantiation.
7489 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007490
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007491 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007492 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7493 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007494 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007495 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007496 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007497 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007498
Larisse Voufo39a1e502013-08-06 01:03:05 +00007499 if (!HasNoEffect) {
7500 // Instantiate static data member or variable template.
7501
7502 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7503 if (PrevTemplate) {
7504 // Merge attributes.
7505 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7506 ProcessDeclAttributeList(S, Prev, Attr);
7507 }
7508 if (TSK == TSK_ExplicitInstantiationDefinition)
7509 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7510 }
7511
7512 // Check the new variable specialization against the parsed input.
7513 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7514 Diag(T->getTypeLoc().getLocStart(),
7515 diag::err_invalid_var_template_spec_type)
7516 << 0 << PrevTemplate << R << Prev->getType();
7517 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7518 << 2 << PrevTemplate->getDeclName();
7519 return true;
7520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007521
Douglas Gregor450f00842009-09-25 18:43:00 +00007522 // FIXME: Create an ExplicitInstantiation node?
John McCall48871652010-08-21 09:40:31 +00007523 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00007524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007525
7526 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007527 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007528 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007529 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007530 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007531 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007532 HasExplicitTemplateArgs = true;
7533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007534
Douglas Gregor450f00842009-09-25 18:43:00 +00007535 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007536 // A [...] function [...] can be explicitly instantiated from its template.
7537 // A member function [...] of a class template can be explicitly
7538 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007539 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007540 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007541 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007542 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7543 P != PEnd; ++P) {
7544 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007545 if (!HasExplicitTemplateArgs) {
7546 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007547 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7548 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007549 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007550
John McCall58cc69d2010-01-27 01:50:18 +00007551 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007552 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7553 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007554 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007555 }
7556 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007557
Douglas Gregor450f00842009-09-25 18:43:00 +00007558 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7559 if (!FunTmpl)
7560 continue;
7561
Larisse Voufo98b20f12013-07-19 23:00:19 +00007562 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor450f00842009-09-25 18:43:00 +00007563 FunctionDecl *Specialization = 0;
7564 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007565 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00007566 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00007567 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007568 // Keep track of almost-matches.
7569 FailedCandidates.addCandidate()
7570 .set(FunTmpl->getTemplatedDecl(),
7571 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007572 (void)TDK;
7573 continue;
7574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007575
John McCall58cc69d2010-01-27 01:50:18 +00007576 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007578
Douglas Gregor450f00842009-09-25 18:43:00 +00007579 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007580 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007581 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007582 D.getIdentifierLoc(),
7583 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7584 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7585 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007586
John McCall58cc69d2010-01-27 01:50:18 +00007587 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007588 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007589
7590 // Ignore access control bits, we don't need them for redeclaration checking.
7591 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007592
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007593 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007594 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007595 diag::err_explicit_instantiation_member_function_not_instantiated)
7596 << Specialization
7597 << (Specialization->getTemplateSpecializationKind() ==
7598 TSK_ExplicitSpecialization);
7599 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7600 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007601 }
7602
Douglas Gregorec9fd132012-01-14 16:38:05 +00007603 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00007604 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7605 PrevDecl = Specialization;
7606
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007607 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007608 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007609 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007610 PrevDecl,
7611 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007612 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007613 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007614 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007615
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007616 // FIXME: We may still want to build some representation of this
7617 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007618 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00007619 return (Decl*) 0;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007620 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00007621
7622 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00007623 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7624 if (Attr)
7625 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007626
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007627 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00007628 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007629
Douglas Gregore47f5a72009-10-14 23:41:34 +00007630 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007631 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007632 // or a static data member of a class template specialization, the name of
7633 // the class template specialization in the qualified-id for the member
7634 // name shall be a simple-template-id.
7635 //
7636 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007637 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00007638 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007639 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00007640 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007641 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007642 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007643 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007644
Douglas Gregore47f5a72009-10-14 23:41:34 +00007645 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007646 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00007647 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007648 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00007649 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007650
Douglas Gregor450f00842009-09-25 18:43:00 +00007651 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCall48871652010-08-21 09:40:31 +00007652 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00007653}
7654
John McCallfaf5fb42010-08-26 23:41:50 +00007655TypeResult
John McCall7f41d982009-09-11 04:59:25 +00007656Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7657 const CXXScopeSpec &SS, IdentifierInfo *Name,
7658 SourceLocation TagLoc, SourceLocation NameLoc) {
7659 // This has to hold, because SS is expected to be defined.
7660 assert(Name && "Expected a name in a dependent tag");
7661
Aaron Ballman4a979672014-01-03 13:56:08 +00007662 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00007663 if (!NNS)
7664 return true;
7665
Abramo Bagnara6150c882010-05-11 21:36:43 +00007666 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00007667
Douglas Gregorba41d012010-04-24 16:38:41 +00007668 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7669 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00007670 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00007671 return true;
7672 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00007673
Douglas Gregore7c20652011-03-02 00:47:37 +00007674 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007675 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00007676 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7677
7678 // Create type-source location information for this type.
7679 TypeLocBuilder TLB;
7680 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007681 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00007682 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7683 TL.setNameLoc(NameLoc);
7684 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00007685}
7686
John McCallfaf5fb42010-08-26 23:41:50 +00007687TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007688Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7689 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00007690 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007691 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00007692 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007693
Richard Smith0bf8a4922011-10-18 20:49:44 +00007694 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7695 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007696 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007697 diag::warn_cxx98_compat_typename_outside_of_template :
7698 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007699 << FixItHint::CreateRemoval(TypenameLoc);
7700
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007701 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00007702 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7703 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00007704 if (T.isNull())
7705 return true;
John McCall99b2fe52010-04-29 23:50:39 +00007706
7707 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7708 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00007709 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007710 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007711 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00007712 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007713 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00007714 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007715 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007716 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00007717 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007718 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007719
John McCallba7bf592010-08-24 05:47:05 +00007720 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00007721}
7722
John McCallfaf5fb42010-08-26 23:41:50 +00007723TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007724Sema::ActOnTypenameType(Scope *S,
7725 SourceLocation TypenameLoc,
7726 const CXXScopeSpec &SS,
7727 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00007728 TemplateTy TemplateIn,
7729 SourceLocation TemplateNameLoc,
7730 SourceLocation LAngleLoc,
7731 ASTTemplateArgsPtr TemplateArgsIn,
7732 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00007733 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7734 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007735 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007736 diag::warn_cxx98_compat_typename_outside_of_template :
7737 diag::ext_typename_outside_of_template)
7738 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007739
7740 // Translate the parser's template argument list in our AST format.
7741 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7742 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7743
7744 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007745 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7746 // Construct a dependent template specialization type.
7747 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00007748 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007749 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7750 DTN->getQualifier(),
7751 DTN->getIdentifier(),
7752 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007753
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007754 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00007755 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007756 DependentTemplateSpecializationTypeLoc SpecTL
7757 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007758 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7759 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00007760 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007761 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007762 SpecTL.setLAngleLoc(LAngleLoc);
7763 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007764 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7765 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007766 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00007767 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00007768
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007769 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7770 if (T.isNull())
7771 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00007772
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007773 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00007774 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007775 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007776 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007777 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7778 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007779 SpecTL.setLAngleLoc(LAngleLoc);
7780 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007781 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7782 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7783
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007784 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
7785 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007786 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007787 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7788
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007789 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
7790 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00007791}
7792
Douglas Gregorb09518c2011-02-27 22:46:49 +00007793
Richard Smith6f8d2c62012-05-09 05:17:00 +00007794/// Determine whether this failed name lookup should be treated as being
7795/// disabled by a usage of std::enable_if.
7796static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
7797 SourceRange &CondRange) {
7798 // We must be looking for a ::type...
7799 if (!II.isStr("type"))
7800 return false;
7801
7802 // ... within an explicitly-written template specialization...
7803 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
7804 return false;
7805 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007806 TemplateSpecializationTypeLoc EnableIfTSTLoc =
7807 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
7808 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00007809 return false;
7810 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00007811 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00007812
7813 // ... which names a complete class template declaration...
7814 const TemplateDecl *EnableIfDecl =
7815 EnableIfTST->getTemplateName().getAsTemplateDecl();
7816 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
7817 return false;
7818
7819 // ... called "enable_if".
7820 const IdentifierInfo *EnableIfII =
7821 EnableIfDecl->getDeclName().getAsIdentifierInfo();
7822 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
7823 return false;
7824
7825 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00007826 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00007827 return true;
7828}
7829
Douglas Gregor333489b2009-03-27 23:10:48 +00007830/// \brief Build the type that describes a C++ typename specifier,
7831/// e.g., "typename T::type".
7832QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007833Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
7834 SourceLocation KeywordLoc,
7835 NestedNameSpecifierLoc QualifierLoc,
7836 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00007837 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00007838 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007839 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00007840
John McCall0b66eb32010-05-01 00:40:08 +00007841 DeclContext *Ctx = computeDeclContext(SS);
7842 if (!Ctx) {
7843 // If the nested-name-specifier is dependent and couldn't be
7844 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007845 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
7846 return Context.getDependentNameType(Keyword,
7847 QualifierLoc.getNestedNameSpecifier(),
7848 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007849 }
Douglas Gregor333489b2009-03-27 23:10:48 +00007850
John McCall0b66eb32010-05-01 00:40:08 +00007851 // If the nested-name-specifier refers to the current instantiation,
7852 // the "typename" keyword itself is superfluous. In C++03, the
7853 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
7854 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00007855 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007856
John McCall0b66eb32010-05-01 00:40:08 +00007857 if (RequireCompleteDeclContext(SS, Ctx))
7858 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00007859
7860 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00007861 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007862 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00007863 unsigned DiagID = 0;
7864 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00007865 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00007866 case LookupResult::NotFound: {
7867 // If we're looking up 'type' within a template named 'enable_if', produce
7868 // a more specific diagnostic.
7869 SourceRange CondRange;
7870 if (isEnableIf(QualifierLoc, II, CondRange)) {
7871 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
7872 << Ctx << CondRange;
7873 return QualType();
7874 }
7875
Douglas Gregore40876a2009-10-13 21:16:44 +00007876 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00007877 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00007878 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00007879
7880 case LookupResult::FoundUnresolvedValue: {
7881 // We found a using declaration that is a value. Most likely, the using
7882 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007883 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00007884 IILoc);
7885 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
7886 << Name << Ctx << FullRange;
7887 if (UnresolvedUsingValueDecl *Using
7888 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007889 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00007890 Diag(Loc, diag::note_using_value_decl_missing_typename)
7891 << FixItHint::CreateInsertion(Loc, "typename ");
7892 }
7893 }
7894 // Fall through to create a dependent typename type, from which we can recover
7895 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007896
Douglas Gregord0d2ee02010-01-15 01:44:47 +00007897 case LookupResult::NotFoundInCurrentInstantiation:
7898 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007899 return Context.getDependentNameType(Keyword,
7900 QualifierLoc.getNestedNameSpecifier(),
7901 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00007902
7903 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007904 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00007905 // We found a type. Build an ElaboratedType, since the
7906 // typename-specifier was just sugar.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007907 return Context.getElaboratedType(ETK_Typename,
7908 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00007909 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00007910 }
7911
7912 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00007913 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00007914 break;
7915
7916 case LookupResult::FoundOverloaded:
7917 DiagID = diag::err_typename_nested_not_type;
7918 Referenced = *Result.begin();
7919 break;
7920
John McCall6538c932009-10-10 05:48:19 +00007921 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00007922 return QualType();
7923 }
7924
7925 // If we get here, it's because name lookup did not find a
7926 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007927 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00007928 IILoc);
7929 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00007930 if (Referenced)
7931 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
7932 << Name;
7933 return QualType();
7934}
Douglas Gregor15acfb92009-08-06 16:20:37 +00007935
7936namespace {
7937 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00007938 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00007939 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00007940 SourceLocation Loc;
7941 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00007942
Douglas Gregor15acfb92009-08-06 16:20:37 +00007943 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00007944 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007945
Mike Stump11289f42009-09-09 15:08:12 +00007946 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00007947 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00007948 DeclarationName Entity)
7949 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00007950 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00007951
7952 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00007953 /// transformed.
7954 ///
7955 /// For the purposes of type reconstruction, a type has already been
7956 /// transformed if it is NULL or if it is not dependent.
7957 bool AlreadyTransformed(QualType T) {
7958 return T.isNull() || !T->isDependentType();
7959 }
Mike Stump11289f42009-09-09 15:08:12 +00007960
7961 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00007962 /// rebuilt.
7963 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00007964
Douglas Gregor15acfb92009-08-06 16:20:37 +00007965 /// \brief Returns the name of the entity whose type is being rebuilt.
7966 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00007967
Douglas Gregoref6ab412009-10-27 06:26:26 +00007968 /// \brief Sets the "base" location and entity when that
7969 /// information is known based on another transformation.
7970 void setBase(SourceLocation Loc, DeclarationName Entity) {
7971 this->Loc = Loc;
7972 this->Entity = Entity;
7973 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00007974
7975 ExprResult TransformLambdaExpr(LambdaExpr *E) {
7976 // Lambdas never need to be transformed.
7977 return E;
7978 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00007979 };
7980}
7981
Douglas Gregor15acfb92009-08-06 16:20:37 +00007982/// \brief Rebuilds a type within the context of the current instantiation.
7983///
Mike Stump11289f42009-09-09 15:08:12 +00007984/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00007985/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00007986/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00007987/// partial specialization thereof). This routine will rebuild that type now
7988/// that we have entered the declarator's scope, which may produce different
7989/// canonical types, e.g.,
7990///
7991/// \code
7992/// template<typename T>
7993/// struct X {
7994/// typedef T* pointer;
7995/// pointer data();
7996/// };
7997///
7998/// template<typename T>
7999/// typename X<T>::pointer X<T>::data() { ... }
8000/// \endcode
8001///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008002/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008003/// since we do not know that we can look into X<T> when we parsed the type.
8004/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008005/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008006/// as the canonical type of T*, allowing the return types of the out-of-line
8007/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008008TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8009 SourceLocation Loc,
8010 DeclarationName Name) {
8011 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008012 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008013
Douglas Gregor15acfb92009-08-06 16:20:37 +00008014 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8015 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008016}
Douglas Gregorbe999392009-09-15 16:23:51 +00008017
John McCalldadc5752010-08-24 06:29:42 +00008018ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008019 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8020 DeclarationName());
8021 return Rebuilder.TransformExpr(E);
8022}
8023
John McCall99b2fe52010-04-29 23:50:39 +00008024bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008025 if (SS.isInvalid())
8026 return true;
John McCall2408e322010-04-27 00:57:59 +00008027
Douglas Gregor10176412011-02-25 16:07:42 +00008028 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008029 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8030 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008031 NestedNameSpecifierLoc Rebuilt
8032 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8033 if (!Rebuilt)
8034 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008035
Douglas Gregor10176412011-02-25 16:07:42 +00008036 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008037 return false;
John McCall2408e322010-04-27 00:57:59 +00008038}
8039
Douglas Gregor041b0842011-10-14 15:31:12 +00008040/// \brief Rebuild the template parameters now that we know we're in a current
8041/// instantiation.
8042bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8043 TemplateParameterList *Params) {
8044 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8045 Decl *Param = Params->getParam(I);
8046
8047 // There is nothing to rebuild in a type parameter.
8048 if (isa<TemplateTypeParmDecl>(Param))
8049 continue;
8050
8051 // Rebuild the template parameter list of a template template parameter.
8052 if (TemplateTemplateParmDecl *TTP
8053 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8054 if (RebuildTemplateParamsInCurrentInstantiation(
8055 TTP->getTemplateParameters()))
8056 return true;
8057
8058 continue;
8059 }
8060
8061 // Rebuild the type of a non-type template parameter.
8062 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8063 TypeSourceInfo *NewTSI
8064 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8065 NTTP->getLocation(),
8066 NTTP->getDeclName());
8067 if (!NewTSI)
8068 return true;
8069
8070 if (NewTSI != NTTP->getTypeSourceInfo()) {
8071 NTTP->setTypeSourceInfo(NewTSI);
8072 NTTP->setType(NewTSI->getType());
8073 }
8074 }
8075
8076 return false;
8077}
8078
Douglas Gregorbe999392009-09-15 16:23:51 +00008079/// \brief Produces a formatted string that describes the binding of
8080/// template parameters to template arguments.
8081std::string
8082Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8083 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008084 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008085}
8086
8087std::string
8088Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8089 const TemplateArgument *Args,
8090 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008091 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008092 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008093
Douglas Gregore62e6a02009-11-11 19:13:48 +00008094 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008095 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008096
Douglas Gregorbe999392009-09-15 16:23:51 +00008097 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008098 if (I >= NumArgs)
8099 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008100
Douglas Gregorbe999392009-09-15 16:23:51 +00008101 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008102 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008103 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008104 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008105
Douglas Gregorbe999392009-09-15 16:23:51 +00008106 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008107 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008108 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008109 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008111
Douglas Gregor0192c232010-12-20 16:52:59 +00008112 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008113 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008114 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008115
8116 Out << ']';
8117 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008118}
Francois Pichet1c229c02011-04-22 22:18:13 +00008119
Richard Smithe40f2ba2013-08-07 21:41:30 +00008120void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8121 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008122 if (!FD)
8123 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008124
8125 LateParsedTemplate *LPT = new LateParsedTemplate;
8126
8127 // Take tokens to avoid allocations
8128 LPT->Toks.swap(Toks);
8129 LPT->D = FnD;
8130 LateParsedTemplateMap[FD] = LPT;
8131
8132 FD->setLateTemplateParsed(true);
8133}
8134
8135void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8136 if (!FD)
8137 return;
8138 FD->setLateTemplateParsed(false);
8139}
Francois Pichet1c229c02011-04-22 22:18:13 +00008140
8141bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8142 DeclContext *DC = CurContext;
8143
8144 while (DC) {
8145 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8146 const FunctionDecl *FD = RD->isLocalClass();
8147 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8148 } else if (DC->isTranslationUnit() || DC->isNamespace())
8149 return false;
8150
8151 DC = DC->getParent();
8152 }
8153 return false;
8154}