blob: 254e78fa017b0b043d39c61d08bfaa466a5187f8 [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))
Craig Topperc3ec1492014-05-26 06:22:03 +000055 return nullptr;
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
Craig Topperc3ec1492014-05-26 06:22:03 +000082 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000083 }
Mike Stump11289f42009-09-09 15:08:12 +000084
Craig Topperc3ec1492014-05-26 06:22:03 +000085 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000086}
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))
David Blaikie82e95a32014-11-19 07:49:47 +0000110 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000111 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;
Craig Topperc3ec1492014-05-26 06:22:03 +0000253 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000254 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
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000321 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
322 FilterCCC->WantTypeSpecifiers = false;
323 FilterCCC->WantExpressionKeywords = false;
324 FilterCCC->WantRemainingKeywords = false;
325 FilterCCC->WantCXXNamedCasts = true;
326 if (TypoCorrection Corrected = CorrectTypo(
327 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
328 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000329 Found.setLookupName(Corrected.getCorrection());
330 if (Corrected.getCorrectionDecl())
331 Found.addDecl(Corrected.getCorrectionDecl());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000332 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000333 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000334 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000335 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
336 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000337 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000338 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
339 << Name << LookupCtx << DroppedSpecifier
340 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000341 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000342 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000343 }
John McCalle9cccd82010-06-16 08:42:20 +0000344 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000345 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000346 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000347 }
348 }
349
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000350 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000351 if (Found.empty()) {
352 if (isDependent)
353 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000354 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000355 }
John McCalle66edc12009-11-24 19:00:30 +0000356
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000357 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000358 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000359 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000360 // [...] If the lookup in the class of the object expression finds a
361 // template, the name is also looked up in the context of the entire
362 // postfix-expression and [...]
363 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000364 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000365 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
366 LookupOrdinaryName);
367 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000368 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000369
John McCalle66edc12009-11-24 19:00:30 +0000370 if (FoundOuter.empty()) {
371 // - if the name is not found, the name found in the class of the
372 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000373 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
374 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000375 // - if the name is found in the context of the entire
376 // postfix-expression and does not name a class template, the name
377 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000378 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000379 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000380 // - if the name found is a class template, it must refer to the same
381 // entity as the one found in the class of the object expression,
382 // otherwise the program is ill-formed.
383 if (!Found.isSingleResult() ||
384 Found.getFoundDecl()->getCanonicalDecl()
385 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000386 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000387 diag::ext_nested_name_member_ref_lookup_ambiguous)
388 << Found.getLookupName()
389 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000390 Diag(Found.getRepresentativeDecl()->getLocation(),
391 diag::note_ambig_member_ref_object_type)
392 << ObjectType;
393 Diag(FoundOuter.getFoundDecl()->getLocation(),
394 diag::note_ambig_member_ref_scope);
395
396 // Recover by taking the template that we found in the object
397 // expression's type.
398 }
399 }
400 }
401}
402
John McCallcd4b4772009-12-02 03:53:29 +0000403/// ActOnDependentIdExpression - Handle a dependent id-expression that
404/// was just parsed. This is only possible with an explicit scope
405/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000406ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000407Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000408 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000409 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000410 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000411 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000412 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000413
John McCallcd4b4772009-12-02 03:53:29 +0000414 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000415 isa<CXXMethodDecl>(DC) &&
416 cast<CXXMethodDecl>(DC)->isInstance()) {
417 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000418
John McCalle66edc12009-11-24 19:00:30 +0000419 // Since the 'this' expression is synthesized, we don't need to
420 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000421 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000422
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000423 return CXXDependentScopeMemberExpr::Create(
424 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
425 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
426 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000427 }
428
Abramo Bagnara7945c982012-01-27 09:46:47 +0000429 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000430}
431
John McCalldadc5752010-08-24 06:29:42 +0000432ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000433Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000434 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000435 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000436 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000437 return DependentScopeDeclRefExpr::Create(
438 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
439 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000440}
441
Douglas Gregor5101c242008-12-05 18:15:24 +0000442/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
443/// that the template parameter 'PrevDecl' is being shadowed by a new
444/// declaration at location Loc. Returns true to indicate that this is
445/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000446void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000447 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000448
449 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000450 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000451 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000452
453 // C++ [temp.local]p4:
454 // A template-parameter shall not be redeclared within its
455 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000456 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000457 << cast<NamedDecl>(PrevDecl)->getDeclName();
458 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000459 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000460}
461
Douglas Gregor463421d2009-03-03 04:44:36 +0000462/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000463/// the parameter D to reference the templated declaration and return a pointer
464/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000465TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
466 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
467 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000468 return Temp;
469 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000470 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000471}
472
Douglas Gregoreb29d182011-01-05 17:40:24 +0000473ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
474 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000475 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000476 "Only template template arguments can be pack expansions here");
477 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
478 "Template template argument pack expansion without packs");
479 ParsedTemplateArgument Result(*this);
480 Result.EllipsisLoc = EllipsisLoc;
481 return Result;
482}
483
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000484static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
485 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000486
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000487 switch (Arg.getKind()) {
488 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000489 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000490 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000491 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000492 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000493 return TemplateArgumentLoc(TemplateArgument(T), DI);
494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000495
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000496 case ParsedTemplateArgument::NonType: {
497 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
498 return TemplateArgumentLoc(TemplateArgument(E), E);
499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000501 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000502 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000503 TemplateArgument TArg;
504 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000505 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000506 else
507 TArg = Template;
508 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000509 Arg.getScopeSpec().getWithLocInContext(
510 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000511 Arg.getLocation(),
512 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000513 }
514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000515
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000516 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000517}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000518
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000519/// \brief Translates template arguments as provided by the parser
520/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000521void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
522 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000523 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000524 TemplateArgs.addArgument(translateTemplateArgument(*this,
525 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000526}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527
Richard Smithb80d5402013-06-25 22:21:36 +0000528static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
529 SourceLocation Loc,
530 IdentifierInfo *Name) {
531 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
532 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
533 if (PrevDecl && PrevDecl->isTemplateParameter())
534 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
535}
536
Douglas Gregor5101c242008-12-05 18:15:24 +0000537/// ActOnTypeParameter - Called when a C++ template type parameter
538/// (e.g., "typename T") has been parsed. Typename specifies whether
539/// the keyword "typename" was used to declare the type parameter
540/// (otherwise, "class" was used), and KeyLoc is the location of the
541/// "class" or "typename" keyword. ParamName is the name of the
542/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000543/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000544/// If the type parameter has a default argument, it will be added
545/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000546Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000547 SourceLocation EllipsisLoc,
548 SourceLocation KeyLoc,
549 IdentifierInfo *ParamName,
550 SourceLocation ParamNameLoc,
551 unsigned Depth, unsigned Position,
552 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000553 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000554 assert(S->isTemplateParamScope() &&
555 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000556 bool Invalid = false;
557
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000558 SourceLocation Loc = ParamNameLoc;
559 if (!ParamName)
560 Loc = KeyLoc;
561
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000562 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000563 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000564 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000565 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000566 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000567 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000568 if (Invalid)
569 Param->setInvalidDecl();
570
571 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000572 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
573
Douglas Gregor5101c242008-12-05 18:15:24 +0000574 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000575 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000576 IdResolver.AddDecl(Param);
577 }
578
Douglas Gregorf5500772011-01-05 15:48:55 +0000579 // C++0x [temp.param]p9:
580 // A default template-argument may be specified for any kind of
581 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000582 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000583 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
584 DefaultArg = ParsedType();
585 }
586
Douglas Gregordc13ded2010-07-01 00:00:45 +0000587 // Handle the default argument, if provided.
588 if (DefaultArg) {
589 TypeSourceInfo *DefaultTInfo;
590 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
Douglas Gregordc13ded2010-07-01 00:00:45 +0000592 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000594 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000596 UPPC_DefaultArgument))
597 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
Douglas Gregordc13ded2010-07-01 00:00:45 +0000599 // Check the template argument itself.
600 if (CheckTemplateArgument(Param, DefaultTInfo)) {
601 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000602 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604
Douglas Gregordc13ded2010-07-01 00:00:45 +0000605 Param->setDefaultArgument(DefaultTInfo, false);
606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
John McCall48871652010-08-21 09:40:31 +0000608 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000609}
610
Douglas Gregor463421d2009-03-03 04:44:36 +0000611/// \brief Check that the type of a non-type template parameter is
612/// well-formed.
613///
614/// \returns the (possibly-promoted) parameter type if valid;
615/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000616QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000617Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000618 // We don't allow variably-modified types as the type of non-type template
619 // parameters.
620 if (T->isVariablyModifiedType()) {
621 Diag(Loc, diag::err_variably_modified_nontype_template_param)
622 << T;
623 return QualType();
624 }
625
Douglas Gregor463421d2009-03-03 04:44:36 +0000626 // C++ [temp.param]p4:
627 //
628 // A non-type template-parameter shall have one of the following
629 // (optionally cv-qualified) types:
630 //
631 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000632 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000633 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000634 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000635 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000636 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000637 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000639 // -- std::nullptr_t.
640 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000641 // If T is a dependent type, we can't do the check now, so we
642 // assume that it is well-formed.
Richard Smithd0e1c952012-03-13 07:21:50 +0000643 T->isDependentType()) {
644 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
645 // are ignored when determining its type.
646 return T.getUnqualifiedType();
647 }
648
Douglas Gregor463421d2009-03-03 04:44:36 +0000649 // C++ [temp.param]p8:
650 //
651 // A non-type template-parameter of type "array of T" or
652 // "function returning T" is adjusted to be of type "pointer to
653 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000654 else if (T->isArrayType() || T->isFunctionType())
655 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor463421d2009-03-03 04:44:36 +0000657 Diag(Loc, diag::err_template_nontype_parm_bad_type)
658 << T;
659
660 return QualType();
661}
662
John McCall48871652010-08-21 09:40:31 +0000663Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
664 unsigned Depth,
665 unsigned Position,
666 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000667 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000668 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
669 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000670
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000671 assert(S->isTemplateParamScope() &&
672 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000673 bool Invalid = false;
674
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000675 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
676 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000677 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000678 Invalid = true;
679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000680
Richard Smithb80d5402013-06-25 22:21:36 +0000681 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000682 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000683 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000684 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000685 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000686 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000687 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000688 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000689 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000690
Douglas Gregor5101c242008-12-05 18:15:24 +0000691 if (Invalid)
692 Param->setInvalidDecl();
693
Richard Smithb80d5402013-06-25 22:21:36 +0000694 if (ParamName) {
695 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
696 ParamName);
697
Douglas Gregor5101c242008-12-05 18:15:24 +0000698 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000699 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000700 IdResolver.AddDecl(Param);
701 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000702
Douglas Gregorf5500772011-01-05 15:48:55 +0000703 // C++0x [temp.param]p9:
704 // A default template-argument may be specified for any kind of
705 // template-parameter that is not a template parameter pack.
706 if (Default && IsParameterPack) {
707 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000708 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000709 }
710
Douglas Gregordc13ded2010-07-01 00:00:45 +0000711 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000712 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000713 // Check for unexpanded parameter packs.
714 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
715 return Param;
716
Douglas Gregordc13ded2010-07-01 00:00:45 +0000717 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000718 ExprResult DefaultRes =
719 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000720 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000721 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000722 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000723 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000724 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725
John McCallb268a282010-08-23 23:25:46 +0000726 Param->setDefaultArgument(Default, false);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
John McCall48871652010-08-21 09:40:31 +0000729 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000730}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000731
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000732/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000733/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000734/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000735Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
736 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000737 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000738 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000739 IdentifierInfo *Name,
740 SourceLocation NameLoc,
741 unsigned Depth,
742 unsigned Position,
743 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000744 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000745 assert(S->isTemplateParamScope() &&
746 "Template template parameter not in template parameter scope!");
747
748 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000749 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000750 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000751 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000752 NameLoc.isInvalid()? TmpLoc : NameLoc,
753 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000754 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000755 Param->setAccess(AS_public);
756
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000757 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000758 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000759 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000760 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
761
John McCall48871652010-08-21 09:40:31 +0000762 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000763 IdResolver.AddDecl(Param);
764 }
765
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000766 if (Params->size() == 0) {
767 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
768 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
769 Param->setInvalidDecl();
770 }
771
Douglas Gregorf5500772011-01-05 15:48:55 +0000772 // C++0x [temp.param]p9:
773 // A default template-argument may be specified for any kind of
774 // template-parameter that is not a template parameter pack.
775 if (IsParameterPack && !Default.isInvalid()) {
776 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
777 Default = ParsedTemplateArgument();
778 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000779
Douglas Gregordc13ded2010-07-01 00:00:45 +0000780 if (!Default.isInvalid()) {
781 // Check only that we have a template template argument. We don't want to
782 // try to check well-formedness now, because our template template parameter
783 // might have dependent types in its template parameters, which we wouldn't
784 // be able to match now.
785 //
786 // If none of the template template parameter's template arguments mention
787 // other template parameters, we could actually perform more checking here.
788 // However, it isn't worth doing.
789 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
790 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
791 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
792 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000793 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000794 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000795
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000796 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000798 DefaultArg.getArgument().getAsTemplate(),
799 UPPC_DefaultArgument))
800 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801
Douglas Gregordc13ded2010-07-01 00:00:45 +0000802 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000804
John McCall48871652010-08-21 09:40:31 +0000805 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000806}
807
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000808/// ActOnTemplateParameterList - Builds a TemplateParameterList that
809/// contains the template parameters in Params/NumParams.
Richard Trieu9becef62011-09-09 03:18:59 +0000810TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000811Sema::ActOnTemplateParameterList(unsigned Depth,
812 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000813 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000814 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000815 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000816 SourceLocation RAngleLoc) {
817 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000818 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000819
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000820 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000821 (NamedDecl**)Params, NumParams,
Douglas Gregorbe999392009-09-15 16:23:51 +0000822 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000823}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000824
John McCall3e11ebe2010-03-15 10:12:16 +0000825static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
826 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000827 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000828}
829
John McCallfaf5fb42010-08-26 23:41:50 +0000830DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000831Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000832 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000833 IdentifierInfo *Name, SourceLocation NameLoc,
834 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000835 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000836 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000837 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000838 unsigned NumOuterTemplateParamLists,
839 TemplateParameterList** OuterTemplateParamLists) {
Mike Stump11289f42009-09-09 15:08:12 +0000840 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000841 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000842 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000843 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000844
845 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000846 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000847 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000848
Abramo Bagnara6150c882010-05-11 21:36:43 +0000849 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
850 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000851
852 // There is no such thing as an unnamed class template.
853 if (!Name) {
854 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000855 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000856 }
857
Richard Smith6483d222012-04-21 01:27:54 +0000858 // Find any previous declaration with this name. For a friend with no
859 // scope explicitly specified, we only look for tag declarations (per
860 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000861 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000862 LookupResult Previous(*this, Name, NameLoc,
863 (SS.isEmpty() && TUK == TUK_Friend)
864 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000865 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000866 if (SS.isNotEmpty() && !SS.isInvalid()) {
867 SemanticContext = computeDeclContext(SS, true);
868 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000869 // FIXME: Horrible, horrible hack! We can't currently represent this
870 // in the AST, and historically we have just ignored such friend
871 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000872 Diag(NameLoc, TUK == TUK_Friend
873 ? diag::warn_template_qualified_friend_ignored
874 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000875 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000876 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000877 }
Mike Stump11289f42009-09-09 15:08:12 +0000878
John McCall0b66eb32010-05-01 00:40:08 +0000879 if (RequireCompleteDeclContext(SS, SemanticContext))
880 return true;
881
Douglas Gregor041b0842011-10-14 15:31:12 +0000882 // If we're adding a template to a dependent context, we may need to
883 // rebuilding some of the types used within the template parameter list,
884 // now that we know what the current instantiation is.
885 if (SemanticContext->isDependentContext()) {
886 ContextRAII SavedContext(*this, SemanticContext);
887 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
888 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000889 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
890 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000891
John McCall27b18f82009-11-17 02:14:36 +0000892 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000893 } else {
894 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000895 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000896 }
Mike Stump11289f42009-09-09 15:08:12 +0000897
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000898 if (Previous.isAmbiguous())
899 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000900
Craig Topperc3ec1492014-05-26 06:22:03 +0000901 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000902 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000903 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000904
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000905 // If there is a previous declaration with the same name, check
906 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000907 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000908 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000909
910 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000911 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000912 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000913 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000914 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
915 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000917 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
918 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
919 PrevClassTemplate
920 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
921 ->getSpecializedTemplate();
922 }
923 }
924
John McCalld43784f2009-12-18 11:25:59 +0000925 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000926 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000927 // [...] When looking for a prior declaration of a class or a function
928 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000929 // function is neither a qualified name nor a template-id, scopes outside
930 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000931 if (!SS.isSet()) {
932 DeclContext *OutermostContext = CurContext;
933 while (!OutermostContext->isFileContext())
934 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000935
Richard Smith61e582f2012-04-20 07:12:26 +0000936 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000937 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
938 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
939 SemanticContext = PrevDecl->getDeclContext();
940 } else {
941 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000942 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000943 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +0000944 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +0000945 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000946
947 // Check that the chosen semantic context doesn't already contain a
948 // declaration of this name as a non-tag type.
949 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
950 ForRedeclaration);
951 DeclContext *LookupContext = SemanticContext;
952 while (LookupContext->isTransparentContext())
953 LookupContext = LookupContext->getLookupParent();
954 LookupQualifiedName(Previous, LookupContext);
955
956 if (Previous.isAmbiguous())
957 return true;
958
959 if (Previous.begin() != Previous.end())
960 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000961 }
John McCall90d3bb92009-12-17 23:21:11 +0000962 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000963 } else if (PrevDecl &&
964 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000965 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000966
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000967 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +0000968 // Ensure that the template parameter lists are compatible. Skip this check
969 // for a friend in a dependent context: the template parameter list itself
970 // could be dependent.
971 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
972 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000973 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000974 /*Complain=*/true,
975 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000976 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000977
978 // C++ [temp.class]p4:
979 // In a redeclaration, partial specialization, explicit
980 // specialization or explicit instantiation of a class template,
981 // the class-key shall agree in kind with the original class
982 // template declaration (7.1.5.3).
983 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +0000984 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
985 TUK == TUK_Definition, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000986 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000987 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000988 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000989 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000990 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000991 }
992
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000993 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000994 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000995 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000996 Diag(NameLoc, diag::err_redefinition) << Name;
997 Diag(Def->getLocation(), diag::note_previous_definition);
998 // FIXME: Would it make sense to try to "forget" the previous
999 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001000 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001001 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001002 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001003 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1004 // Maybe we will complain about the shadowed template parameter.
1005 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1006 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001007 PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001008 } else if (PrevDecl) {
1009 // C++ [temp]p5:
1010 // A class template shall not have the same name as any other
1011 // template, class, function, object, enumeration, enumerator,
1012 // namespace, or type in the same scope (3.3), except as specified
1013 // in (14.5.4).
1014 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1015 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001016 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001017 }
1018
Douglas Gregordba32632009-02-10 19:49:53 +00001019 // Check the template parameter list of this declaration, possibly
1020 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001021 // template declaration. Skip this check for a friend in a dependent
1022 // context, because the template parameter list might be dependent.
1023 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001024 CheckTemplateParameterList(
1025 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001026 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1027 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001028 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1029 SemanticContext->isDependentContext())
1030 ? TPC_ClassTemplateMember
1031 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1032 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001033 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001034
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001035 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001037 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001038 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1039 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001040 : diag::err_member_decl_does_not_match)
1041 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001042 Invalid = true;
1043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044 }
1045
Mike Stump11289f42009-09-09 15:08:12 +00001046 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001047 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001048 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001049 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001050 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001051 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001052 if (NumOuterTemplateParamLists > 0)
1053 NewClass->setTemplateParameterListsInfo(Context,
1054 NumOuterTemplateParamLists,
1055 OuterTemplateParamLists);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001056
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001057 // Add alignment attributes if necessary; these attributes are checked when
1058 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001059 if (TUK == TUK_Definition) {
1060 AddAlignmentAttributesForRecord(NewClass);
1061 AddMsStructLayoutForRecord(NewClass);
1062 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001063
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001064 ClassTemplateDecl *NewTemplate
1065 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1066 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001067 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001068 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001069
Douglas Gregor21823bf2011-12-20 18:11:52 +00001070 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001071 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001072
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001073 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001074 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001075 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001076 assert(T->isDependentType() && "Class template type is not dependent?");
1077 (void)T;
1078
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001079 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001080 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001081 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001082 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1083 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001084
Anders Carlsson137108d2009-03-26 01:24:28 +00001085 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001086 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001087 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001088
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001089 // Set the lexical context of these templates
1090 NewClass->setLexicalDeclContext(CurContext);
1091 NewTemplate->setLexicalDeclContext(CurContext);
1092
John McCall9bb74a52009-07-31 02:45:11 +00001093 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001094 NewClass->startDefinition();
1095
1096 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001097 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001098
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001099 if (PrevClassTemplate)
1100 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1101
Rafael Espindola385c0422012-07-13 18:04:45 +00001102 AddPushedVisibilityAttribute(NewClass);
1103
Richard Smith234ff472014-08-23 00:49:01 +00001104 if (TUK != TUK_Friend) {
1105 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1106 Scope *Outer = S;
1107 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1108 Outer = Outer->getParent();
1109 PushOnScopeChains(NewTemplate, Outer);
1110 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001111 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001112 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001113 NewClass->setAccess(PrevClassTemplate->getAccess());
1114 }
John McCall27b5c252009-09-14 21:59:20 +00001115
Richard Smith64017682013-07-17 23:53:16 +00001116 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001117
John McCall27b5c252009-09-14 21:59:20 +00001118 // Friend templates are visible in fairly strange ways.
1119 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001120 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001121 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001122 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1123 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001124 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001125 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001126
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001127 FriendDecl *Friend = FriendDecl::Create(
1128 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001129 Friend->setAccess(AS_public);
1130 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001131 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001132
Douglas Gregordba32632009-02-10 19:49:53 +00001133 if (Invalid) {
1134 NewTemplate->setInvalidDecl();
1135 NewClass->setInvalidDecl();
1136 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001137
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001138 ActOnDocumentableDecl(NewTemplate);
1139
John McCall48871652010-08-21 09:40:31 +00001140 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001141}
1142
Douglas Gregored5731f2009-11-25 17:50:39 +00001143/// \brief Diagnose the presence of a default template argument on a
1144/// template parameter, which is ill-formed in certain contexts.
1145///
1146/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001147static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001148 Sema::TemplateParamListContext TPC,
1149 SourceLocation ParamLoc,
1150 SourceRange DefArgRange) {
1151 switch (TPC) {
1152 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001153 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001154 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001155 return false;
1156
1157 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001158 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001159 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001160 // A default template-argument shall not be specified in a
1161 // function template declaration or a function template
1162 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001163 // If a friend function template declaration specifies a default
1164 // template-argument, that declaration shall be a definition and shall be
1165 // the only declaration of the function template in the translation unit.
1166 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001167 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001168 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1169 : diag::ext_template_parameter_default_in_function_template)
1170 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001171 return false;
1172
1173 case Sema::TPC_ClassTemplateMember:
1174 // C++0x [temp.param]p9:
1175 // A default template-argument shall not be specified in the
1176 // template-parameter-lists of the definition of a member of a
1177 // class template that appears outside of the member's class.
1178 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1179 << DefArgRange;
1180 return true;
1181
David Majnemerba8f17a2013-06-25 22:08:55 +00001182 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001183 case Sema::TPC_FriendFunctionTemplate:
1184 // C++ [temp.param]p9:
1185 // A default template-argument shall not be specified in a
1186 // friend template declaration.
1187 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1188 << DefArgRange;
1189 return true;
1190
1191 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1192 // for friend function templates if there is only a single
1193 // declaration (and it is a definition). Strange!
1194 }
1195
David Blaikie8a40f702012-01-17 06:56:22 +00001196 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001197}
1198
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001199/// \brief Check for unexpanded parameter packs within the template parameters
1200/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001201static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1202 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001203 // A template template parameter which is a parameter pack is also a pack
1204 // expansion.
1205 if (TTP->isParameterPack())
1206 return false;
1207
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001208 TemplateParameterList *Params = TTP->getTemplateParameters();
1209 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1210 NamedDecl *P = Params->getParam(I);
1211 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001212 if (!NTTP->isParameterPack() &&
1213 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001214 NTTP->getTypeSourceInfo(),
1215 Sema::UPPC_NonTypeTemplateParameterType))
1216 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001217
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001218 continue;
1219 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001220
1221 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001222 = dyn_cast<TemplateTemplateParmDecl>(P))
1223 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1224 return true;
1225 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001226
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001227 return false;
1228}
1229
Douglas Gregordba32632009-02-10 19:49:53 +00001230/// \brief Checks the validity of a template parameter list, possibly
1231/// considering the template parameter list from a previous
1232/// declaration.
1233///
1234/// If an "old" template parameter list is provided, it must be
1235/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1236/// template parameter list.
1237///
1238/// \param NewParams Template parameter list for a new template
1239/// declaration. This template parameter list will be updated with any
1240/// default arguments that are carried through from the previous
1241/// template parameter list.
1242///
1243/// \param OldParams If provided, template parameter list from a
1244/// previous declaration of the same template. Default template
1245/// arguments will be merged from the old template parameter list to
1246/// the new template parameter list.
1247///
Douglas Gregored5731f2009-11-25 17:50:39 +00001248/// \param TPC Describes the context in which we are checking the given
1249/// template parameter list.
1250///
Douglas Gregordba32632009-02-10 19:49:53 +00001251/// \returns true if an error occurred, false otherwise.
1252bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001253 TemplateParameterList *OldParams,
1254 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001255 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001256
Douglas Gregordba32632009-02-10 19:49:53 +00001257 // C++ [temp.param]p10:
1258 // The set of default template-arguments available for use with a
1259 // template declaration or definition is obtained by merging the
1260 // default arguments from the definition (if in scope) and all
1261 // declarations in scope in the same way default function
1262 // arguments are (8.3.6).
1263 bool SawDefaultArgument = false;
1264 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001265
Mike Stumpc89c8e32009-02-11 23:03:27 +00001266 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001267 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001268 if (OldParams)
1269 OldParam = OldParams->begin();
1270
Douglas Gregor0693def2011-01-27 01:40:17 +00001271 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001272 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1273 NewParamEnd = NewParams->end();
1274 NewParam != NewParamEnd; ++NewParam) {
1275 // Variables used to diagnose redundant default arguments
1276 bool RedundantDefaultArg = false;
1277 SourceLocation OldDefaultLoc;
1278 SourceLocation NewDefaultLoc;
1279
David Blaikie651c73c2011-10-19 05:19:50 +00001280 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001281 bool MissingDefaultArg = false;
1282
David Blaikie651c73c2011-10-19 05:19:50 +00001283 // Variable used to diagnose non-final parameter packs
1284 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001285
Douglas Gregordba32632009-02-10 19:49:53 +00001286 if (TemplateTypeParmDecl *NewTypeParm
1287 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001288 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001289 if (NewTypeParm->hasDefaultArgument() &&
1290 DiagnoseDefaultTemplateArgument(*this, TPC,
1291 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001292 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001293 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001294 NewTypeParm->removeDefaultArgument();
1295
1296 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001297 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001298 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001299
Anders Carlsson327865d2009-06-12 23:20:15 +00001300 if (NewTypeParm->isParameterPack()) {
1301 assert(!NewTypeParm->hasDefaultArgument() &&
1302 "Parameter packs can't have a default argument!");
1303 SawParameterPack = true;
Mike Stump11289f42009-09-09 15:08:12 +00001304 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001305 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001306 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1307 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1308 SawDefaultArgument = true;
1309 RedundantDefaultArg = true;
1310 PreviousDefaultArgLoc = NewDefaultLoc;
1311 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1312 // Merge the default argument from the old declaration to the
1313 // new declaration.
John McCall0ad16662009-10-29 08:12:44 +00001314 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001315 true);
1316 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1317 } else if (NewTypeParm->hasDefaultArgument()) {
1318 SawDefaultArgument = true;
1319 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1320 } else if (SawDefaultArgument)
1321 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001322 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001323 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001324 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001325 if (!NewNonTypeParm->isParameterPack() &&
1326 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001327 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001328 UPPC_NonTypeTemplateParameterType)) {
1329 Invalid = true;
1330 continue;
1331 }
1332
Douglas Gregored5731f2009-11-25 17:50:39 +00001333 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001334 if (NewNonTypeParm->hasDefaultArgument() &&
1335 DiagnoseDefaultTemplateArgument(*this, TPC,
1336 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001337 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001338 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001339 }
1340
Mike Stump12b8ce12009-08-04 21:02:39 +00001341 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001342 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001343 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001344 if (NewNonTypeParm->isParameterPack()) {
1345 assert(!NewNonTypeParm->hasDefaultArgument() &&
1346 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001347 if (!NewNonTypeParm->isPackExpansion())
1348 SawParameterPack = true;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001349 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Richard Smith35828f12013-07-22 03:31:14 +00001350 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001351 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1352 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1353 SawDefaultArgument = true;
1354 RedundantDefaultArg = true;
1355 PreviousDefaultArgLoc = NewDefaultLoc;
1356 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1357 // Merge the default argument from the old declaration to the
1358 // new declaration.
Douglas Gregordba32632009-02-10 19:49:53 +00001359 // FIXME: We need to create a new kind of "default argument"
Douglas Gregorf5500772011-01-05 15:48:55 +00001360 // expression that points to a previous non-type template
Douglas Gregordba32632009-02-10 19:49:53 +00001361 // parameter.
1362 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001363 OldNonTypeParm->getDefaultArgument(),
1364 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001365 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1366 } else if (NewNonTypeParm->hasDefaultArgument()) {
1367 SawDefaultArgument = true;
1368 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1369 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001370 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001371 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001372 TemplateTemplateParmDecl *NewTemplateParm
1373 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001374
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001375 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001376 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001377 Invalid = true;
1378 continue;
1379 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001380
David Blaikie651c73c2011-10-19 05:19:50 +00001381 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001382 if (NewTemplateParm->hasDefaultArgument() &&
1383 DiagnoseDefaultTemplateArgument(*this, TPC,
1384 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001385 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001386 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001387
1388 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001389 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001390 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001391 if (NewTemplateParm->isParameterPack()) {
1392 assert(!NewTemplateParm->hasDefaultArgument() &&
1393 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001394 if (!NewTemplateParm->isPackExpansion())
1395 SawParameterPack = true;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001396 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001397 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001398 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1399 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001400 SawDefaultArgument = true;
1401 RedundantDefaultArg = true;
1402 PreviousDefaultArgLoc = NewDefaultLoc;
1403 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1404 // Merge the default argument from the old declaration to the
1405 // new declaration.
Mike Stump87c57ac2009-05-16 07:39:55 +00001406 // FIXME: We need to create a new kind of "default argument" expression
1407 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001408 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001409 OldTemplateParm->getDefaultArgument(),
1410 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001411 PreviousDefaultArgLoc
1412 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001413 } else if (NewTemplateParm->hasDefaultArgument()) {
1414 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001415 PreviousDefaultArgLoc
1416 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001417 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001418 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001419 }
1420
Richard Smith1fde8ec2012-09-07 02:06:42 +00001421 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001422 // If a template parameter of a primary class template or alias template
1423 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001424 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001425 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1426 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001427 Diag((*NewParam)->getLocation(),
1428 diag::err_template_param_pack_must_be_last_template_parameter);
1429 Invalid = true;
1430 }
1431
Douglas Gregordba32632009-02-10 19:49:53 +00001432 if (RedundantDefaultArg) {
1433 // C++ [temp.param]p12:
1434 // A template-parameter shall not be given default arguments
1435 // by two different declarations in the same scope.
1436 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1437 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1438 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001439 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001440 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001441 // If a template-parameter of a class template has a default
1442 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001443 // have a default template-argument supplied or be a template parameter
1444 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001445 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001446 diag::err_template_param_default_arg_missing);
1447 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1448 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001449 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001450 }
1451
1452 // If we have an old template parameter list that we're merging
1453 // in, move on to the next parameter.
1454 if (OldParams)
1455 ++OldParam;
1456 }
1457
Douglas Gregor0693def2011-01-27 01:40:17 +00001458 // We were missing some default arguments at the end of the list, so remove
1459 // all of the default arguments.
1460 if (RemoveDefaultArguments) {
1461 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1462 NewParamEnd = NewParams->end();
1463 NewParam != NewParamEnd; ++NewParam) {
1464 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1465 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001466 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001467 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1468 NTTP->removeDefaultArgument();
1469 else
1470 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1471 }
1472 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001473
Douglas Gregordba32632009-02-10 19:49:53 +00001474 return Invalid;
1475}
Douglas Gregord32e0282009-02-09 23:23:08 +00001476
John McCalla020a012010-10-20 05:44:58 +00001477namespace {
1478
1479/// A class which looks for a use of a certain level of template
1480/// parameter.
1481struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1482 typedef RecursiveASTVisitor<DependencyChecker> super;
1483
1484 unsigned Depth;
1485 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001486 SourceLocation MatchLoc;
1487
1488 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001489
1490 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1491 NamedDecl *ND = Params->getParam(0);
1492 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1493 Depth = PD->getDepth();
1494 } else if (NonTypeTemplateParmDecl *PD =
1495 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1496 Depth = PD->getDepth();
1497 } else {
1498 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1499 }
1500 }
1501
Richard Smith6056d5e2014-02-09 00:54:43 +00001502 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001503 if (ParmDepth >= Depth) {
1504 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001505 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001506 return true;
1507 }
1508 return false;
1509 }
1510
Richard Smith6056d5e2014-02-09 00:54:43 +00001511 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1512 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1513 }
1514
John McCalla020a012010-10-20 05:44:58 +00001515 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1516 return !Matches(T->getDepth());
1517 }
1518
1519 bool TraverseTemplateName(TemplateName N) {
1520 if (TemplateTemplateParmDecl *PD =
1521 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001522 if (Matches(PD->getDepth()))
1523 return false;
John McCalla020a012010-10-20 05:44:58 +00001524 return super::TraverseTemplateName(N);
1525 }
1526
1527 bool VisitDeclRefExpr(DeclRefExpr *E) {
1528 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001529 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1530 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001531 return false;
John McCalla020a012010-10-20 05:44:58 +00001532 return super::VisitDeclRefExpr(E);
1533 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001534
1535 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1536 return TraverseType(T->getReplacementType());
1537 }
1538
1539 bool
1540 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1541 return TraverseTemplateArgument(T->getArgumentPack());
1542 }
1543
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001544 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1545 return TraverseType(T->getInjectedSpecializationType());
1546 }
John McCalla020a012010-10-20 05:44:58 +00001547};
1548}
1549
Douglas Gregor972fe532011-05-10 18:27:06 +00001550/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001551/// list.
1552static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001553DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001554 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001555 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001556 return Checker.Match;
1557}
1558
Douglas Gregor972fe532011-05-10 18:27:06 +00001559// Find the source range corresponding to the named type in the given
1560// nested-name-specifier, if any.
1561static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1562 QualType T,
1563 const CXXScopeSpec &SS) {
1564 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1565 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1566 if (const Type *CurType = NNS->getAsType()) {
1567 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1568 return NNSLoc.getTypeLoc().getSourceRange();
1569 } else
1570 break;
1571
1572 NNSLoc = NNSLoc.getPrefix();
1573 }
1574
1575 return SourceRange();
1576}
1577
Mike Stump11289f42009-09-09 15:08:12 +00001578/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001579/// specifier, returning the template parameter list that applies to the
1580/// name.
1581///
1582/// \param DeclStartLoc the start of the declaration that has a scope
1583/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001584///
Douglas Gregor972fe532011-05-10 18:27:06 +00001585/// \param DeclLoc The location of the declaration itself.
1586///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001587/// \param SS the scope specifier that will be matched to the given template
1588/// parameter lists. This scope specifier precedes a qualified name that is
1589/// being declared.
1590///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001591/// \param TemplateId The template-id following the scope specifier, if there
1592/// is one. Used to check for a missing 'template<>'.
1593///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001594/// \param ParamLists the template parameter lists, from the outermost to the
1595/// innermost template parameter lists.
1596///
John McCalle820e5e2010-04-13 20:37:33 +00001597/// \param IsFriend Whether to apply the slightly different rules for
1598/// matching template parameters to scope specifiers in friend
1599/// declarations.
1600///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001601/// \param IsExplicitSpecialization will be set true if the entity being
1602/// declared is an explicit specialization, false otherwise.
1603///
Mike Stump11289f42009-09-09 15:08:12 +00001604/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001605/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001606/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001607/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001608/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001609/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001610TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1611 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001612 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001613 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1614 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001615 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001616 Invalid = false;
1617
1618 // The sequence of nested types to which we will match up the template
1619 // parameter lists. We first build this list by starting with the type named
1620 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001621 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001622 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001623 if (SS.getScopeRep()) {
1624 if (CXXRecordDecl *Record
1625 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1626 T = Context.getTypeDeclType(Record);
1627 else
1628 T = QualType(SS.getScopeRep()->getAsType(), 0);
1629 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001630
1631 // If we found an explicit specialization that prevents us from needing
1632 // 'template<>' headers, this will be set to the location of that
1633 // explicit specialization.
1634 SourceLocation ExplicitSpecLoc;
1635
1636 while (!T.isNull()) {
1637 NestedTypes.push_back(T);
1638
1639 // Retrieve the parent of a record type.
1640 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1641 // If this type is an explicit specialization, we're done.
1642 if (ClassTemplateSpecializationDecl *Spec
1643 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1644 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1645 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1646 ExplicitSpecLoc = Spec->getLocation();
1647 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001648 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001649 } else if (Record->getTemplateSpecializationKind()
1650 == TSK_ExplicitSpecialization) {
1651 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001652 break;
1653 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001654
1655 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1656 T = Context.getTypeDeclType(Parent);
1657 else
1658 T = QualType();
1659 continue;
1660 }
1661
1662 if (const TemplateSpecializationType *TST
1663 = T->getAs<TemplateSpecializationType>()) {
1664 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1665 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1666 T = Context.getTypeDeclType(Parent);
1667 else
1668 T = QualType();
1669 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001670 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001671 }
1672
1673 // Look one step prior in a dependent template specialization type.
1674 if (const DependentTemplateSpecializationType *DependentTST
1675 = T->getAs<DependentTemplateSpecializationType>()) {
1676 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1677 T = QualType(NNS->getAsType(), 0);
1678 else
1679 T = QualType();
1680 continue;
1681 }
1682
1683 // Look one step prior in a dependent name type.
1684 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1685 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1686 T = QualType(NNS->getAsType(), 0);
1687 else
1688 T = QualType();
1689 continue;
1690 }
1691
1692 // Retrieve the parent of an enumeration type.
1693 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1694 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1695 // check here.
1696 EnumDecl *Enum = EnumT->getDecl();
1697
1698 // Get to the parent type.
1699 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1700 T = Context.getTypeDeclType(Parent);
1701 else
1702 T = QualType();
1703 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001704 }
Mike Stump11289f42009-09-09 15:08:12 +00001705
Douglas Gregor972fe532011-05-10 18:27:06 +00001706 T = QualType();
1707 }
1708 // Reverse the nested types list, since we want to traverse from the outermost
1709 // to the innermost while checking template-parameter-lists.
1710 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001711
Douglas Gregor972fe532011-05-10 18:27:06 +00001712 // C++0x [temp.expl.spec]p17:
1713 // A member or a member template may be nested within many
1714 // enclosing class templates. In an explicit specialization for
1715 // such a member, the member declaration shall be preceded by a
1716 // template<> for each enclosing class template that is
1717 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001718 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001719
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001720 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001721 if (SawNonEmptyTemplateParameterList) {
1722 Diag(DeclLoc, diag::err_specialize_member_of_template)
1723 << !Recovery << Range;
1724 Invalid = true;
1725 IsExplicitSpecialization = false;
1726 return true;
1727 }
1728
1729 return false;
1730 };
1731
1732 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1733 // Check that we can have an explicit specialization here.
1734 if (CheckExplicitSpecialization(Range, true))
1735 return true;
1736
1737 // We don't have a template header, but we should.
1738 SourceLocation ExpectedTemplateLoc;
1739 if (!ParamLists.empty())
1740 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1741 else
1742 ExpectedTemplateLoc = DeclStartLoc;
1743
1744 Diag(DeclLoc, diag::err_template_spec_needs_header)
1745 << Range
1746 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1747 return false;
1748 };
1749
Douglas Gregor972fe532011-05-10 18:27:06 +00001750 unsigned ParamIdx = 0;
1751 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1752 ++TypeIdx) {
1753 T = NestedTypes[TypeIdx];
1754
1755 // Whether we expect a 'template<>' header.
1756 bool NeedEmptyTemplateHeader = false;
1757
1758 // Whether we expect a template header with parameters.
1759 bool NeedNonemptyTemplateHeader = false;
1760
1761 // For a dependent type, the set of template parameters that we
1762 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001763 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001764
Douglas Gregor373af9b2011-05-11 23:26:17 +00001765 // C++0x [temp.expl.spec]p15:
1766 // A member or a member template may be nested within many enclosing
1767 // class templates. In an explicit specialization for such a member, the
1768 // member declaration shall be preceded by a template<> for each
1769 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001770 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1771 if (ClassTemplatePartialSpecializationDecl *Partial
1772 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1773 ExpectedTemplateParams = Partial->getTemplateParameters();
1774 NeedNonemptyTemplateHeader = true;
1775 } else if (Record->isDependentType()) {
1776 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001777 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001778 ->getTemplateParameters();
1779 NeedNonemptyTemplateHeader = true;
1780 }
1781 } else if (ClassTemplateSpecializationDecl *Spec
1782 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1783 // C++0x [temp.expl.spec]p4:
1784 // Members of an explicitly specialized class template are defined
1785 // in the same manner as members of normal classes, and not using
1786 // the template<> syntax.
1787 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1788 NeedEmptyTemplateHeader = true;
1789 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001790 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001791 } else if (Record->getTemplateSpecializationKind()) {
1792 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001793 != TSK_ExplicitSpecialization &&
1794 TypeIdx == NumTypes - 1)
1795 IsExplicitSpecialization = true;
1796
1797 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001798 }
1799 } else if (const TemplateSpecializationType *TST
1800 = T->getAs<TemplateSpecializationType>()) {
1801 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1802 ExpectedTemplateParams = Template->getTemplateParameters();
1803 NeedNonemptyTemplateHeader = true;
1804 }
1805 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1806 // FIXME: We actually could/should check the template arguments here
1807 // against the corresponding template parameter list.
1808 NeedNonemptyTemplateHeader = false;
1809 }
1810
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001811 // C++ [temp.expl.spec]p16:
1812 // In an explicit specialization declaration for a member of a class
1813 // template or a member template that ap- pears in namespace scope, the
1814 // member template and some of its enclosing class templates may remain
1815 // unspecialized, except that the declaration shall not explicitly
1816 // specialize a class member template if its en- closing class templates
1817 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001818 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001819 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001820 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1821 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001822 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001823 } else
1824 SawNonEmptyTemplateParameterList = true;
1825 }
1826
Douglas Gregor972fe532011-05-10 18:27:06 +00001827 if (NeedEmptyTemplateHeader) {
1828 // If we're on the last of the types, and we need a 'template<>' header
1829 // here, then it's an explicit specialization.
1830 if (TypeIdx == NumTypes - 1)
1831 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001832
1833 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001834 if (ParamLists[ParamIdx]->size() > 0) {
1835 // The header has template parameters when it shouldn't. Complain.
1836 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1837 diag::err_template_param_list_matches_nontemplate)
1838 << T
1839 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1840 ParamLists[ParamIdx]->getRAngleLoc())
1841 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1842 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001843 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001844 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001845
Douglas Gregor972fe532011-05-10 18:27:06 +00001846 // Consume this template header.
1847 ++ParamIdx;
1848 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001849 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001850
1851 if (!IsFriend)
1852 if (DiagnoseMissingExplicitSpecialization(
1853 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001854 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001855
Douglas Gregor972fe532011-05-10 18:27:06 +00001856 continue;
1857 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001858
Douglas Gregor972fe532011-05-10 18:27:06 +00001859 if (NeedNonemptyTemplateHeader) {
1860 // In friend declarations we can have template-ids which don't
1861 // depend on the corresponding template parameter lists. But
1862 // assume that empty parameter lists are supposed to match this
1863 // template-id.
1864 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001865 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001866 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001867 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001868 else
1869 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001870 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001871
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001872 if (ParamIdx < ParamLists.size()) {
1873 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001874 if (ExpectedTemplateParams &&
1875 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1876 ExpectedTemplateParams,
1877 true, TPL_TemplateMatch))
1878 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001879
Douglas Gregor972fe532011-05-10 18:27:06 +00001880 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001881 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001882 TPC_ClassTemplateMember))
1883 Invalid = true;
1884
1885 ++ParamIdx;
1886 continue;
1887 }
1888
1889 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1890 << T
1891 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1892 Invalid = true;
1893 continue;
1894 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001895 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001896
Douglas Gregord8d297c2009-07-21 23:53:31 +00001897 // If there were at least as many template-ids as there were template
1898 // parameter lists, then there are no template parameter lists remaining for
1899 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001900 if (ParamIdx >= ParamLists.size()) {
1901 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001902 // We don't have a template header for the declaration itself, but we
1903 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001904 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001905 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1906 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001907
1908 // Fabricate an empty template parameter list for the invented header.
1909 return TemplateParameterList::Create(Context, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001910 SourceLocation(), nullptr, 0,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001911 SourceLocation());
1912 }
1913
Craig Topperc3ec1492014-05-26 06:22:03 +00001914 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001915 }
Mike Stump11289f42009-09-09 15:08:12 +00001916
Douglas Gregord8d297c2009-07-21 23:53:31 +00001917 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001918 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001919 bool HasAnyExplicitSpecHeader = false;
1920 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001921 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001922 if (ParamLists[I]->size() == 0)
1923 HasAnyExplicitSpecHeader = true;
1924 else
1925 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001926 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001927
Douglas Gregor972fe532011-05-10 18:27:06 +00001928 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001929 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1930 : diag::err_template_spec_extra_headers)
1931 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1932 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001933
1934 // If there was a specialization somewhere, such that 'template<>' is
1935 // not required, and there were any 'template<>' headers, note where the
1936 // specialization occurred.
1937 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1938 Diag(ExplicitSpecLoc,
1939 diag::note_explicit_template_spec_does_not_need_header)
1940 << NestedTypes.back();
1941
1942 // We have a template parameter list with no corresponding scope, which
1943 // means that the resulting template declaration can't be instantiated
1944 // properly (we'll end up with dependent nodes when we shouldn't).
1945 if (!AllExplicitSpecHeaders)
1946 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001947 }
Mike Stump11289f42009-09-09 15:08:12 +00001948
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001949 // C++ [temp.expl.spec]p16:
1950 // In an explicit specialization declaration for a member of a class
1951 // template or a member template that ap- pears in namespace scope, the
1952 // member template and some of its enclosing class templates may remain
1953 // unspecialized, except that the declaration shall not explicitly
1954 // specialize a class member template if its en- closing class templates
1955 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00001956 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001957 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1958 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001959 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001960
Douglas Gregord8d297c2009-07-21 23:53:31 +00001961 // Return the last template parameter list, which corresponds to the
1962 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001963 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001964}
1965
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001966void Sema::NoteAllFoundTemplates(TemplateName Name) {
1967 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1968 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00001969 << (isa<FunctionTemplateDecl>(Template)
1970 ? 0
1971 : isa<ClassTemplateDecl>(Template)
1972 ? 1
1973 : isa<VarTemplateDecl>(Template)
1974 ? 2
1975 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1976 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001977 return;
1978 }
1979
1980 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1981 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1982 IEnd = OST->end();
1983 I != IEnd; ++I)
1984 Diag((*I)->getLocation(), diag::note_template_declared_here)
1985 << 0 << (*I)->getDeclName();
1986
1987 return;
1988 }
1989}
1990
Douglas Gregordc572a32009-03-30 22:58:21 +00001991QualType Sema::CheckTemplateIdType(TemplateName Name,
1992 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00001993 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00001994 DependentTemplateName *DTN
1995 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001996 if (DTN && DTN->isIdentifier())
1997 // When building a template-id where the template-name is dependent,
1998 // assume the template is a type template. Either our assumption is
1999 // correct, or the code is ill-formed and will be diagnosed when the
2000 // dependent name is substituted.
2001 return Context.getDependentTemplateSpecializationType(ETK_None,
2002 DTN->getQualifier(),
2003 DTN->getIdentifier(),
2004 TemplateArgs);
2005
Douglas Gregordc572a32009-03-30 22:58:21 +00002006 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002007 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2008 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002009 // We might have a substituted template template parameter pack. If so,
2010 // build a template specialization type for it.
2011 if (Name.getAsSubstTemplateTemplateParmPack())
2012 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002013
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002014 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2015 << Name;
2016 NoteAllFoundTemplates(Name);
2017 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002018 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002019
Douglas Gregorc40290e2009-03-09 23:48:35 +00002020 // Check that the template argument list is well-formed for this
2021 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002022 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002023 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002024 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002025 return QualType();
2026
Douglas Gregorc40290e2009-03-09 23:48:35 +00002027 QualType CanonType;
2028
Douglas Gregor678d76c2011-07-01 01:22:09 +00002029 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002030 if (TypeAliasTemplateDecl *AliasTemplate =
2031 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002032 // Find the canonical type for this type alias template specialization.
2033 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2034 if (Pattern->isInvalidDecl())
2035 return QualType();
2036
2037 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2038 Converted.data(), Converted.size());
2039
2040 // Only substitute for the innermost template argument list.
2041 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002042 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002043 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2044 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002045 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002046
Richard Smith802c4b72012-08-23 06:16:52 +00002047 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002048 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002049 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002050 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002051
Richard Smith3f1b5d02011-05-05 21:57:07 +00002052 CanonType = SubstType(Pattern->getUnderlyingType(),
2053 TemplateArgLists, AliasTemplate->getLocation(),
2054 AliasTemplate->getDeclName());
2055 if (CanonType.isNull())
2056 return QualType();
2057 } else if (Name.isDependent() ||
2058 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002059 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002060 // This class template specialization is a dependent
2061 // type. Therefore, its canonical type is another class template
2062 // specialization type that contains all of the converted
2063 // arguments in canonical form. This ensures that, e.g., A<T> and
2064 // A<T, T> have identical types when A is declared as:
2065 //
2066 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002067 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002068 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002069 Converted.data(),
2070 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002071
Douglas Gregora8e02e72009-07-28 23:00:59 +00002072 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002073 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002074 // In the future, we need to teach getTemplateSpecializationType to only
2075 // build the canonical type and return that to us.
2076 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002077
2078 // This might work out to be a current instantiation, in which
2079 // case the canonical type needs to be the InjectedClassNameType.
2080 //
2081 // TODO: in theory this could be a simple hashtable lookup; most
2082 // changes to CurContext don't change the set of current
2083 // instantiations.
2084 if (isa<ClassTemplateDecl>(Template)) {
2085 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2086 // If we get out to a namespace, we're done.
2087 if (Ctx->isFileContext()) break;
2088
2089 // If this isn't a record, keep looking.
2090 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2091 if (!Record) continue;
2092
2093 // Look for one of the two cases with InjectedClassNameTypes
2094 // and check whether it's the same template.
2095 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2096 !Record->getDescribedClassTemplate())
2097 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002098
John McCall2408e322010-04-27 00:57:59 +00002099 // Fetch the injected class name type and check whether its
2100 // injected type is equal to the type we just built.
2101 QualType ICNT = Context.getTypeDeclType(Record);
2102 QualType Injected = cast<InjectedClassNameType>(ICNT)
2103 ->getInjectedSpecializationType();
2104
2105 if (CanonType != Injected->getCanonicalTypeInternal())
2106 continue;
2107
2108 // If so, the canonical type of this TST is the injected
2109 // class name type of the record we just found.
2110 assert(ICNT.isCanonical());
2111 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002112 break;
2113 }
2114 }
Mike Stump11289f42009-09-09 15:08:12 +00002115 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002116 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002117 // Find the class template specialization declaration that
2118 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002119 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002120 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002121 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002122 if (!Decl) {
2123 // This is the first time we have referenced this class template
2124 // specialization. Create the canonical declaration and add it to
2125 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002126 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002127 ClassTemplate->getTemplatedDecl()->getTagKind(),
2128 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002129 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002130 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002131 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002132 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002133 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002134 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002135 if (ClassTemplate->isOutOfLine())
2136 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002137 }
2138
Chandler Carruth2acfb222013-09-27 22:14:40 +00002139 // Diagnose uses of this specialization.
2140 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2141
Douglas Gregorc40290e2009-03-09 23:48:35 +00002142 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002143 assert(isa<RecordType>(CanonType) &&
2144 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00002145 }
Mike Stump11289f42009-09-09 15:08:12 +00002146
Douglas Gregorc40290e2009-03-09 23:48:35 +00002147 // Build the fully-sugared type for this class template
2148 // specialization, which refers back to the class template
2149 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002150 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002151}
2152
John McCallfaf5fb42010-08-26 23:41:50 +00002153TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002154Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002155 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002156 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002157 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002158 SourceLocation RAngleLoc,
2159 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002160 if (SS.isInvalid())
2161 return true;
2162
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002163 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002164
Douglas Gregorc40290e2009-03-09 23:48:35 +00002165 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002166 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002167 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002168
Douglas Gregor5a064722011-02-28 17:23:35 +00002169 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002170 QualType T
2171 = Context.getDependentTemplateSpecializationType(ETK_None,
2172 DTN->getQualifier(),
2173 DTN->getIdentifier(),
2174 TemplateArgs);
2175 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002176 TypeLocBuilder TLB;
2177 DependentTemplateSpecializationTypeLoc SpecTL
2178 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002179 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2180 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002181 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002182 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002183 SpecTL.setLAngleLoc(LAngleLoc);
2184 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002185 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2186 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2187 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2188 }
2189
John McCall6b51f282009-11-23 01:53:49 +00002190 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002191
2192 if (Result.isNull())
2193 return true;
2194
Douglas Gregore7c20652011-03-02 00:47:37 +00002195 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002196 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002197 TemplateSpecializationTypeLoc SpecTL
2198 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002199 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002200 SpecTL.setTemplateNameLoc(TemplateLoc);
2201 SpecTL.setLAngleLoc(LAngleLoc);
2202 SpecTL.setRAngleLoc(RAngleLoc);
2203 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2204 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002205
Abramo Bagnara4244b432012-01-27 08:46:19 +00002206 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2207 // constructor or destructor name (in such a case, the scope specifier
2208 // will be attached to the enclosing Decl or Expr node).
2209 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002210 // Create an elaborated-type-specifier containing the nested-name-specifier.
2211 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2212 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002213 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002214 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2215 }
2216
2217 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002218}
John McCall06f6fe8d2009-09-04 01:14:41 +00002219
Douglas Gregore7c20652011-03-02 00:47:37 +00002220TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002221 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002222 SourceLocation TagLoc,
2223 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002224 SourceLocation TemplateKWLoc,
2225 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002226 SourceLocation TemplateLoc,
2227 SourceLocation LAngleLoc,
2228 ASTTemplateArgsPtr TemplateArgsIn,
2229 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002230 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002231
2232 // Translate the parser's template argument list in our AST format.
2233 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2234 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2235
2236 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002237 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002238 ElaboratedTypeKeyword Keyword
2239 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002240
Douglas Gregore7c20652011-03-02 00:47:37 +00002241 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2242 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2243 DTN->getQualifier(),
2244 DTN->getIdentifier(),
2245 TemplateArgs);
2246
2247 // Build type-source information.
2248 TypeLocBuilder TLB;
2249 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002250 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2251 SpecTL.setElaboratedKeywordLoc(TagLoc);
2252 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002253 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002254 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002255 SpecTL.setLAngleLoc(LAngleLoc);
2256 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002257 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2258 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2259 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2260 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002261
2262 if (TypeAliasTemplateDecl *TAT =
2263 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2264 // C++0x [dcl.type.elab]p2:
2265 // If the identifier resolves to a typedef-name or the simple-template-id
2266 // resolves to an alias template specialization, the
2267 // elaborated-type-specifier is ill-formed.
2268 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2269 Diag(TAT->getLocation(), diag::note_declared_at);
2270 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002271
2272 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2273 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002274 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002275
2276 // Check the tag kind
2277 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002278 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002279
John McCalld8fe9af2009-09-08 17:47:29 +00002280 IdentifierInfo *Id = D->getIdentifier();
2281 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002282
Richard Trieucaa33d32011-06-10 03:11:26 +00002283 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2284 TagLoc, *Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002285 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002286 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002287 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002288 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002289 }
2290 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002291
Douglas Gregore7c20652011-03-02 00:47:37 +00002292 // Provide source-location information for the template specialization.
2293 TypeLocBuilder TLB;
2294 TemplateSpecializationTypeLoc SpecTL
2295 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002296 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002297 SpecTL.setTemplateNameLoc(TemplateLoc);
2298 SpecTL.setLAngleLoc(LAngleLoc);
2299 SpecTL.setRAngleLoc(RAngleLoc);
2300 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2301 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002302
Douglas Gregore7c20652011-03-02 00:47:37 +00002303 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002304 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002305 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2306 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002307 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002308 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2309 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002310}
2311
Larisse Voufo39a1e502013-08-06 01:03:05 +00002312static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002313 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2314 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002315
2316static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2317 NamedDecl *PrevDecl,
2318 SourceLocation Loc,
2319 bool IsPartialSpecialization);
2320
2321static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002322
Richard Smith300e0c32013-09-24 04:49:23 +00002323static bool isTemplateArgumentTemplateParameter(
2324 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2325 switch (Arg.getKind()) {
2326 case TemplateArgument::Null:
2327 case TemplateArgument::NullPtr:
2328 case TemplateArgument::Integral:
2329 case TemplateArgument::Declaration:
2330 case TemplateArgument::Pack:
2331 case TemplateArgument::TemplateExpansion:
2332 return false;
2333
2334 case TemplateArgument::Type: {
2335 QualType Type = Arg.getAsType();
2336 const TemplateTypeParmType *TPT =
2337 Arg.getAsType()->getAs<TemplateTypeParmType>();
2338 return TPT && !Type.hasQualifiers() &&
2339 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2340 }
2341
2342 case TemplateArgument::Expression: {
2343 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2344 if (!DRE || !DRE->getDecl())
2345 return false;
2346 const NonTypeTemplateParmDecl *NTTP =
2347 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2348 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2349 }
2350
2351 case TemplateArgument::Template:
2352 const TemplateTemplateParmDecl *TTP =
2353 dyn_cast_or_null<TemplateTemplateParmDecl>(
2354 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2355 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2356 }
2357 llvm_unreachable("unexpected kind of template argument");
2358}
2359
2360static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2361 ArrayRef<TemplateArgument> Args) {
2362 if (Params->size() != Args.size())
2363 return false;
2364
2365 unsigned Depth = Params->getDepth();
2366
2367 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2368 TemplateArgument Arg = Args[I];
2369
2370 // If the parameter is a pack expansion, the argument must be a pack
2371 // whose only element is a pack expansion.
2372 if (Params->getParam(I)->isParameterPack()) {
2373 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2374 !Arg.pack_begin()->isPackExpansion())
2375 return false;
2376 Arg = Arg.pack_begin()->getPackExpansionPattern();
2377 }
2378
2379 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2380 return false;
2381 }
2382
2383 return true;
2384}
2385
Richard Smith4b55a9c2014-04-17 03:29:33 +00002386/// Convert the parser's template argument list representation into our form.
2387static TemplateArgumentListInfo
2388makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2389 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2390 TemplateId.RAngleLoc);
2391 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2392 TemplateId.NumArgs);
2393 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2394 return TemplateArgs;
2395}
2396
Larisse Voufo39a1e502013-08-06 01:03:05 +00002397DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002398 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002399 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002400 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002401 // D must be variable template id.
2402 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2403 "Variable template specialization is declared with a template it.");
2404
2405 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002406 TemplateArgumentListInfo TemplateArgs =
2407 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002408 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2409 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2410 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002411
Richard Smithbeef3452014-01-16 23:39:20 +00002412 TemplateName Name = TemplateId->Template.get();
2413
2414 // The template-id must name a variable template.
2415 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002416 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2417 if (!VarTemplate) {
2418 NamedDecl *FnTemplate;
2419 if (auto *OTS = Name.getAsOverloadedTemplate())
2420 FnTemplate = *OTS->begin();
2421 else
2422 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2423 if (FnTemplate)
2424 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2425 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002426 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2427 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002428 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002429
2430 // Check for unexpanded parameter packs in any of the template arguments.
2431 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2432 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2433 UPPC_PartialSpecialization))
2434 return true;
2435
2436 // Check that the template argument list is well-formed for this
2437 // template.
2438 SmallVector<TemplateArgument, 4> Converted;
2439 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2440 false, Converted))
2441 return true;
2442
2443 // Check that the type of this variable template specialization
2444 // matches the expected type.
2445 TypeSourceInfo *ExpectedDI;
2446 {
2447 // Do substitution on the type of the declaration
2448 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2449 Converted.data(), Converted.size());
2450 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002451 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002452 return true;
2453 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2454 ExpectedDI =
2455 SubstType(Templated->getTypeSourceInfo(),
2456 MultiLevelTemplateArgumentList(TemplateArgList),
2457 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2458 }
2459 if (!ExpectedDI)
2460 return true;
2461
Larisse Voufo39a1e502013-08-06 01:03:05 +00002462 // Find the variable template (partial) specialization declaration that
2463 // corresponds to these arguments.
2464 if (IsPartialSpecialization) {
2465 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002466 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2467 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002468 return true;
2469
2470 bool InstantiationDependent;
2471 if (!Name.isDependent() &&
2472 !TemplateSpecializationType::anyDependentTemplateArguments(
2473 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2474 InstantiationDependent)) {
2475 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2476 << VarTemplate->getDeclName();
2477 IsPartialSpecialization = false;
2478 }
Richard Smith300e0c32013-09-24 04:49:23 +00002479
2480 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2481 Converted)) {
2482 // C++ [temp.class.spec]p9b3:
2483 //
2484 // -- The argument list of the specialization shall not be identical
2485 // to the implicit argument list of the primary template.
2486 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2487 << /*variable template*/ 1
2488 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2489 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2490 // FIXME: Recover from this by treating the declaration as a redeclaration
2491 // of the primary template.
2492 return true;
2493 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002494 }
2495
Craig Topperc3ec1492014-05-26 06:22:03 +00002496 void *InsertPos = nullptr;
2497 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002498
2499 if (IsPartialSpecialization)
2500 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002501 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002502 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002503 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002504
Craig Topperc3ec1492014-05-26 06:22:03 +00002505 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002506
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);
Craig Topperc3ec1492014-05-26 06:22:03 +00002521 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002522 } 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.
Craig Topperc3ec1492014-05-26 06:22:03 +00002666 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002667 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00002668 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002669 // 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,
Craig Topperc3ec1492014-05-26 06:22:03 +00002819 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002820}
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
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002862 return 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))
Reid Kleckner034531d2014-12-18 18:17:42 +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);
Craig Topperc3ec1492014-05-26 06:22:03 +00002881 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002882 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()
Reid Kleckner32506ed2014-06-12 23:03:48 +00002896 << NameInfo.getName().getAsString() << 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
Craig Topperc3ec1492014-05-26 06:22:03 +00002925 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00002926 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,
Reid Kleckner377c1592014-06-10 23:29:48 +00002998 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();
Reid Kleckner377c1592014-06-10 23:29:48 +00003001 QualType ArgType;
3002 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003003
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003004 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003005 switch(Arg.getKind()) {
3006 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003007 // C++ [temp.arg.type]p1:
3008 // A template-argument for a template-parameter which is a
3009 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003010 ArgType = Arg.getAsType();
3011 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003012 break;
3013 case TemplateArgument::Template: {
3014 // We have a template type parameter but the template argument
3015 // is a template without any arguments.
3016 SourceRange SR = AL.getSourceRange();
3017 TemplateName Name = Arg.getAsTemplate();
3018 Diag(SR.getBegin(), diag::err_template_missing_args)
3019 << Name << SR;
3020 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3021 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003022
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003023 return true;
3024 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003025 case TemplateArgument::Expression: {
3026 // We have a template type parameter but the template argument is an
3027 // expression; see if maybe it is missing the "typename" keyword.
3028 CXXScopeSpec SS;
3029 DeclarationNameInfo NameInfo;
3030
3031 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3032 SS.Adopt(ArgExpr->getQualifierLoc());
3033 NameInfo = ArgExpr->getNameInfo();
3034 } else if (DependentScopeDeclRefExpr *ArgExpr =
3035 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3036 SS.Adopt(ArgExpr->getQualifierLoc());
3037 NameInfo = ArgExpr->getNameInfo();
3038 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3039 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003040 if (ArgExpr->isImplicitAccess()) {
3041 SS.Adopt(ArgExpr->getQualifierLoc());
3042 NameInfo = ArgExpr->getMemberNameInfo();
3043 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003044 }
3045
Reid Kleckner377c1592014-06-10 23:29:48 +00003046 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003047 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3048 LookupParsedName(Result, CurScope, &SS);
3049
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003050 if (Result.getAsSingle<TypeDecl>() ||
3051 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003052 LookupResult::NotFoundInCurrentInstantiation) {
3053 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003054 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003055 Diag(Loc, getLangOpts().MSVCCompat
3056 ? diag::ext_ms_template_type_arg_missing_typename
3057 : diag::err_template_arg_must_be_type_suggest)
3058 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003059 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003060
3061 // Recover by synthesizing a type using the location information that we
3062 // already have.
3063 ArgType =
3064 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3065 TypeLocBuilder TLB;
3066 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3067 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3068 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3069 TL.setNameLoc(NameInfo.getLoc());
3070 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3071
3072 // Overwrite our input TemplateArgumentLoc so that we can recover
3073 // properly.
3074 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3075 TemplateArgumentLocInfo(TSI));
3076
3077 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003078 }
3079 }
3080 // fallthrough
3081 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003082 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003083 // We have a template type parameter but the template argument
3084 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003085 SourceRange SR = AL.getSourceRange();
3086 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003087 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003088
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003089 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003090 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003091 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003092
Reid Kleckner377c1592014-06-10 23:29:48 +00003093 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003094 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003095
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003096 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003097 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003098
3099 // Objective-C ARC:
3100 // If an explicitly-specified template argument type is a lifetime type
3101 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003102 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003103 ArgType->isObjCLifetimeType() &&
3104 !ArgType.getObjCLifetime()) {
3105 Qualifiers Qs;
3106 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3107 ArgType = Context.getQualifiedType(ArgType, Qs);
3108 }
3109
3110 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003111 return false;
3112}
3113
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003114/// \brief Substitute template arguments into the default template argument for
3115/// the given template type parameter.
3116///
3117/// \param SemaRef the semantic analysis object for which we are performing
3118/// the substitution.
3119///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003120/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003121/// for.
3122///
3123/// \param TemplateLoc the location of the template name that started the
3124/// template-id we are checking.
3125///
3126/// \param RAngleLoc the location of the right angle bracket ('>') that
3127/// terminates the template-id.
3128///
3129/// \param Param the template template parameter whose default we are
3130/// substituting into.
3131///
3132/// \param Converted the list of template arguments provided for template
3133/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003134/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003135static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003136SubstDefaultTemplateArgument(Sema &SemaRef,
3137 TemplateDecl *Template,
3138 SourceLocation TemplateLoc,
3139 SourceLocation RAngleLoc,
3140 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003141 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003142 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003143
3144 // If the argument type is dependent, instantiate it now based
3145 // on the previously-computed template arguments.
3146 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003147 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003148 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003149 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003150 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003151 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003152
David Majnemer89189202013-08-28 23:48:32 +00003153 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3154 Converted.data(), Converted.size());
3155
3156 // Only substitute for the innermost template argument list.
3157 MultiLevelTemplateArgumentList TemplateArgLists;
3158 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3159 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3160 TemplateArgLists.addOuterTemplateArguments(None);
3161
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003162 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003163 ArgType =
3164 SemaRef.SubstType(ArgType, TemplateArgLists,
3165 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003166 }
3167
3168 return ArgType;
3169}
3170
3171/// \brief Substitute template arguments into the default template argument for
3172/// the given non-type template parameter.
3173///
3174/// \param SemaRef the semantic analysis object for which we are performing
3175/// the substitution.
3176///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003177/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003178/// for.
3179///
3180/// \param TemplateLoc the location of the template name that started the
3181/// template-id we are checking.
3182///
3183/// \param RAngleLoc the location of the right angle bracket ('>') that
3184/// terminates the template-id.
3185///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003186/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003187/// substituting into.
3188///
3189/// \param Converted the list of template arguments provided for template
3190/// parameters that precede \p Param in the template parameter list.
3191///
3192/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003193static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003194SubstDefaultTemplateArgument(Sema &SemaRef,
3195 TemplateDecl *Template,
3196 SourceLocation TemplateLoc,
3197 SourceLocation RAngleLoc,
3198 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003199 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003200 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003201 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003202 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003203 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003204 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003205
David Majnemer89189202013-08-28 23:48:32 +00003206 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3207 Converted.data(), Converted.size());
3208
3209 // Only substitute for the innermost template argument list.
3210 MultiLevelTemplateArgumentList TemplateArgLists;
3211 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3212 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3213 TemplateArgLists.addOuterTemplateArguments(None);
3214
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003215 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
Eli Friedmanc25372b2012-04-26 22:43:24 +00003216 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
David Majnemer89189202013-08-28 23:48:32 +00003217 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003218}
3219
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003220/// \brief Substitute template arguments into the default template argument for
3221/// the given template template parameter.
3222///
3223/// \param SemaRef the semantic analysis object for which we are performing
3224/// the substitution.
3225///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003226/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003227/// for.
3228///
3229/// \param TemplateLoc the location of the template name that started the
3230/// template-id we are checking.
3231///
3232/// \param RAngleLoc the location of the right angle bracket ('>') that
3233/// terminates the template-id.
3234///
3235/// \param Param the template template parameter whose default we are
3236/// substituting into.
3237///
3238/// \param Converted the list of template arguments provided for template
3239/// parameters that precede \p Param in the template parameter list.
3240///
Douglas Gregordf846d12011-03-02 18:46:51 +00003241/// \param QualifierLoc Will be set to the nested-name-specifier (with
3242/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003243///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003244/// \returns the substituted template argument, or NULL if an error occurred.
3245static TemplateName
3246SubstDefaultTemplateArgument(Sema &SemaRef,
3247 TemplateDecl *Template,
3248 SourceLocation TemplateLoc,
3249 SourceLocation RAngleLoc,
3250 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003251 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003252 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003253 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003254 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003255 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003256 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003257
David Majnemer89189202013-08-28 23:48:32 +00003258 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3259 Converted.data(), Converted.size());
3260
3261 // Only substitute for the innermost template argument list.
3262 MultiLevelTemplateArgumentList TemplateArgLists;
3263 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3264 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3265 TemplateArgLists.addOuterTemplateArguments(None);
3266
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003267 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003268 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003269 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003270 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003271 QualifierLoc =
3272 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003273 if (!QualifierLoc)
3274 return TemplateName();
3275 }
David Majnemer89189202013-08-28 23:48:32 +00003276
3277 return SemaRef.SubstTemplateName(
3278 QualifierLoc,
3279 Param->getDefaultArgument().getArgument().getAsTemplate(),
3280 Param->getDefaultArgument().getTemplateNameLoc(),
3281 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003282}
3283
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003284/// \brief If the given template parameter has a default template
3285/// argument, substitute into that default template argument and
3286/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003287TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003288Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3289 SourceLocation TemplateLoc,
3290 SourceLocation RAngleLoc,
3291 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003292 SmallVectorImpl<TemplateArgument>
3293 &Converted,
3294 bool &HasDefaultArg) {
3295 HasDefaultArg = false;
3296
3297 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003298 if (!TypeParm->hasDefaultArgument())
3299 return TemplateArgumentLoc();
3300
Richard Smithc87b9382013-07-04 01:01:24 +00003301 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003302 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003303 TemplateLoc,
3304 RAngleLoc,
3305 TypeParm,
3306 Converted);
3307 if (DI)
3308 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3309
3310 return TemplateArgumentLoc();
3311 }
3312
3313 if (NonTypeTemplateParmDecl *NonTypeParm
3314 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3315 if (!NonTypeParm->hasDefaultArgument())
3316 return TemplateArgumentLoc();
3317
Richard Smithc87b9382013-07-04 01:01:24 +00003318 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003319 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003320 TemplateLoc,
3321 RAngleLoc,
3322 NonTypeParm,
3323 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003324 if (Arg.isInvalid())
3325 return TemplateArgumentLoc();
3326
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003327 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003328 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3329 }
3330
3331 TemplateTemplateParmDecl *TempTempParm
3332 = cast<TemplateTemplateParmDecl>(Param);
3333 if (!TempTempParm->hasDefaultArgument())
3334 return TemplateArgumentLoc();
3335
Richard Smithc87b9382013-07-04 01:01:24 +00003336 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003337 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003338 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003339 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003340 RAngleLoc,
3341 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003342 Converted,
3343 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003344 if (TName.isNull())
3345 return TemplateArgumentLoc();
3346
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003347 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003348 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003349 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3350}
3351
Douglas Gregorda0fb532009-11-11 19:31:23 +00003352/// \brief Check that the given template argument corresponds to the given
3353/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003354///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003355/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003356/// checked.
3357///
3358/// \param Arg The template argument.
3359///
3360/// \param Template The template in which the template argument resides.
3361///
3362/// \param TemplateLoc The location of the template name for the template
3363/// whose argument list we're matching.
3364///
3365/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3366/// the template argument list.
3367///
3368/// \param ArgumentPackIndex The index into the argument pack where this
3369/// argument will be placed. Only valid if the parameter is a parameter pack.
3370///
3371/// \param Converted The checked, converted argument will be added to the
3372/// end of this small vector.
3373///
3374/// \param CTAK Describes how we arrived at this particular template argument:
3375/// explicitly written, deduced, etc.
3376///
3377/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003378bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003379 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003380 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003381 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003382 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003383 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003384 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003385 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003386 // Check template type parameters.
3387 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003388 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003389
Douglas Gregoreebed722009-11-11 19:41:09 +00003390 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003391 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003392 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003393 // with the template arguments we've seen thus far. But if the
3394 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003395 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003396 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3397 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003398
Peter Collingbourne01687632010-12-10 17:08:53 +00003399 if (NTTPType->isDependentType() &&
3400 !isa<TemplateTemplateParmDecl>(Template) &&
3401 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003402 // Do substitution on the type of the non-type template parameter.
3403 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003404 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003405 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003406 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003407 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408
3409 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003410 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003411 NTTPType = SubstType(NTTPType,
3412 MultiLevelTemplateArgumentList(TemplateArgs),
3413 NTTP->getLocation(),
3414 NTTP->getDeclName());
3415 // If that worked, check the non-type template parameter type
3416 // for validity.
3417 if (!NTTPType.isNull())
3418 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3419 NTTP->getLocation());
3420 if (NTTPType.isNull())
3421 return true;
3422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003423
Douglas Gregorda0fb532009-11-11 19:31:23 +00003424 switch (Arg.getArgument().getKind()) {
3425 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003426 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427
Douglas Gregorda0fb532009-11-11 19:31:23 +00003428 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003429 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003430 ExprResult Res =
3431 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3432 Result, CTAK);
3433 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003434 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003436 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003437 break;
3438 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439
Douglas Gregorda0fb532009-11-11 19:31:23 +00003440 case TemplateArgument::Declaration:
3441 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003442 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003443 // We've already checked this template argument, so just copy
3444 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003445 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003446 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003447
Douglas Gregorda0fb532009-11-11 19:31:23 +00003448 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003449 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003450 // We were given a template template argument. It may not be ill-formed;
3451 // see below.
3452 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003453 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3454 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003455 // We have a template argument such as \c T::template X, which we
3456 // parsed as a template template argument. However, since we now
3457 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003458 // template name into an expression.
3459
3460 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3461 Arg.getTemplateNameLoc());
3462
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003463 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003464 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003465 // FIXME: the template-template arg was a DependentTemplateName,
3466 // so it was provided with a template keyword. However, its source
3467 // location is not stored in the template argument structure.
3468 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003469 ExprResult E = DependentScopeDeclRefExpr::Create(
3470 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3471 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003472
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003473 // If we parsed the template argument as a pack expansion, create a
3474 // pack expansion expression.
3475 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003476 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003477 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003478 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003480
Douglas Gregorda0fb532009-11-11 19:31:23 +00003481 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003482 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003483 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003484 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003485
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003486 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003487 break;
3488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489
Douglas Gregorda0fb532009-11-11 19:31:23 +00003490 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003491 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003492 // therefore cannot be a non-type template argument.
3493 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3494 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003495
Douglas Gregorda0fb532009-11-11 19:31:23 +00003496 Diag(Param->getLocation(), diag::note_template_param_here);
3497 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003498
Douglas Gregorda0fb532009-11-11 19:31:23 +00003499 case TemplateArgument::Type: {
3500 // We have a non-type template parameter but the template
3501 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502
Douglas Gregorda0fb532009-11-11 19:31:23 +00003503 // C++ [temp.arg]p2:
3504 // In a template-argument, an ambiguity between a type-id and
3505 // an expression is resolved to a type-id, regardless of the
3506 // form of the corresponding template-parameter.
3507 //
3508 // We warn specifically about this case, since it can be rather
3509 // confusing for users.
3510 QualType T = Arg.getArgument().getAsType();
3511 SourceRange SR = Arg.getSourceRange();
3512 if (T->isFunctionType())
3513 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3514 else
3515 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3516 Diag(Param->getLocation(), diag::note_template_param_here);
3517 return true;
3518 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003519
Douglas Gregorda0fb532009-11-11 19:31:23 +00003520 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003521 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003523
Douglas Gregorda0fb532009-11-11 19:31:23 +00003524 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525 }
3526
3527
Douglas Gregorda0fb532009-11-11 19:31:23 +00003528 // Check template template parameters.
3529 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003530
Douglas Gregorda0fb532009-11-11 19:31:23 +00003531 // Substitute into the template parameter list of the template
3532 // template parameter, since previously-supplied template arguments
3533 // may appear within the template template parameter.
3534 {
3535 // Set up a template instantiation context.
3536 LocalInstantiationScope Scope(*this);
3537 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003538 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003539 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003540 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003541 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003542
3543 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003544 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003545 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003546 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003547 MultiLevelTemplateArgumentList(TemplateArgs)));
3548 if (!TempParm)
3549 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003550 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003551
Douglas Gregorda0fb532009-11-11 19:31:23 +00003552 switch (Arg.getArgument().getKind()) {
3553 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003554 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003555
Douglas Gregorda0fb532009-11-11 19:31:23 +00003556 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003557 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003558 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003559 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003560
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003561 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003562 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003563
Douglas Gregorda0fb532009-11-11 19:31:23 +00003564 case TemplateArgument::Expression:
3565 case TemplateArgument::Type:
3566 // We have a template template parameter but the template
3567 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003568 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003569 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003570 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571
Douglas Gregorda0fb532009-11-11 19:31:23 +00003572 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003573 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003574 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003575 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003576 case TemplateArgument::NullPtr:
3577 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003578
Douglas Gregorda0fb532009-11-11 19:31:23 +00003579 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003580 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003581 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003582
Douglas Gregorda0fb532009-11-11 19:31:23 +00003583 return false;
3584}
3585
Douglas Gregor8e072612012-02-03 07:34:46 +00003586/// \brief Diagnose an arity mismatch in the
3587static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3588 SourceLocation TemplateLoc,
3589 TemplateArgumentListInfo &TemplateArgs) {
3590 TemplateParameterList *Params = Template->getTemplateParameters();
3591 unsigned NumParams = Params->size();
3592 unsigned NumArgs = TemplateArgs.size();
3593
3594 SourceRange Range;
3595 if (NumArgs > NumParams)
3596 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3597 TemplateArgs.getRAngleLoc());
3598 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3599 << (NumArgs > NumParams)
3600 << (isa<ClassTemplateDecl>(Template)? 0 :
3601 isa<FunctionTemplateDecl>(Template)? 1 :
3602 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3603 << Template << Range;
3604 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3605 << Params->getSourceRange();
3606 return true;
3607}
3608
Richard Smith1fde8ec2012-09-07 02:06:42 +00003609/// \brief Check whether the template parameter is a pack expansion, and if so,
3610/// determine the number of parameters produced by that expansion. For instance:
3611///
3612/// \code
3613/// template<typename ...Ts> struct A {
3614/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3615/// };
3616/// \endcode
3617///
3618/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3619/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003620static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003621 if (NonTypeTemplateParmDecl *NTTP
3622 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3623 if (NTTP->isExpandedParameterPack())
3624 return NTTP->getNumExpansionTypes();
3625 }
3626
3627 if (TemplateTemplateParmDecl *TTP
3628 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3629 if (TTP->isExpandedParameterPack())
3630 return TTP->getNumExpansionTemplateParameters();
3631 }
3632
David Blaikie7a30dc52013-02-21 01:47:18 +00003633 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003634}
3635
Douglas Gregord32e0282009-02-09 23:23:08 +00003636/// \brief Check that the given template argument list is well-formed
3637/// for specializing the given template.
3638bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3639 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003640 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003641 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003642 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00003643 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003644
John McCall6b51f282009-11-23 01:53:49 +00003645 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
3646
Mike Stump11289f42009-09-09 15:08:12 +00003647 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003648 // [...] The type and form of each template-argument specified in
3649 // a template-id shall match the type and form specified for the
3650 // corresponding parameter declared by the template in its
3651 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003652 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003653 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003654 unsigned ArgIdx = 0, NumArgs = TemplateArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003655 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003656 for (TemplateParameterList::iterator Param = Params->begin(),
3657 ParamEnd = Params->end();
3658 Param != ParamEnd; /* increment in loop */) {
3659 // If we have an expanded parameter pack, make sure we don't have too
3660 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003661 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003662 if (*Expansions == ArgumentPack.size()) {
3663 // We're done with this parameter pack. Pack up its arguments and add
3664 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003665 Converted.push_back(
3666 TemplateArgument::CreatePackCopy(Context,
3667 ArgumentPack.data(),
3668 ArgumentPack.size()));
3669 ArgumentPack.clear();
3670
Richard Smith1fde8ec2012-09-07 02:06:42 +00003671 // This argument is assigned to the next parameter.
3672 ++Param;
3673 continue;
3674 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3675 // Not enough arguments for this parameter pack.
3676 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3677 << false
3678 << (isa<ClassTemplateDecl>(Template)? 0 :
3679 isa<FunctionTemplateDecl>(Template)? 1 :
3680 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3681 << Template;
3682 Diag(Template->getLocation(), diag::note_template_decl_here)
3683 << Params->getSourceRange();
3684 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003685 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003686 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003687
Richard Smith1fde8ec2012-09-07 02:06:42 +00003688 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003689 // Check the template argument we were given.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003690 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
3691 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003692 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003693 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003694
Richard Smith96d71c32014-11-12 23:38:38 +00003695 bool PackExpansionIntoNonPack =
3696 TemplateArgs[ArgIdx].getArgument().isPackExpansion() &&
3697 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3698 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003699 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003700 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003701 // can't be canonicalized, so reject it now.
3702 Diag(TemplateArgs[ArgIdx].getLocation(),
3703 diag::err_alias_template_expansion_into_fixed_list)
3704 << TemplateArgs[ArgIdx].getSourceRange();
3705 Diag((*Param)->getLocation(), diag::note_template_param_here);
3706 return true;
3707 }
3708
Richard Smith1fde8ec2012-09-07 02:06:42 +00003709 // We're now done with this argument.
3710 ++ArgIdx;
3711
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003712 if ((*Param)->isTemplateParameterPack()) {
3713 // The template parameter was a template parameter pack, so take the
3714 // deduced argument and place it on the argument pack. Note that we
3715 // stay on the same template parameter so that we can deduce more
3716 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003717 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003718 } else {
3719 // Move to the next template parameter.
3720 ++Param;
3721 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003722
Richard Smith96d71c32014-11-12 23:38:38 +00003723 // If we just saw a pack expansion into a non-pack, then directly convert
3724 // the remaining arguments, because we don't know what parameters they'll
3725 // match up with.
3726 if (PackExpansionIntoNonPack) {
3727 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003728 // If we were part way through filling in an expanded parameter pack,
3729 // fall back to just producing individual arguments.
3730 Converted.insert(Converted.end(),
3731 ArgumentPack.begin(), ArgumentPack.end());
3732 ArgumentPack.clear();
3733 }
3734
3735 while (ArgIdx < NumArgs) {
Richard Smith96d71c32014-11-12 23:38:38 +00003736 Converted.push_back(TemplateArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003737 ++ArgIdx;
3738 }
3739
Richard Smith1fde8ec2012-09-07 02:06:42 +00003740 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003741 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003742
Douglas Gregor84d49a22009-11-11 21:54:23 +00003743 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745
Douglas Gregor2f157c92011-06-03 02:59:40 +00003746 // If we're checking a partial template argument list, we're done.
3747 if (PartialTemplateArgs) {
3748 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3749 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3750 ArgumentPack.data(),
3751 ArgumentPack.size()));
3752
Richard Smith1fde8ec2012-09-07 02:06:42 +00003753 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003754 }
3755
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003757 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003758 if ((*Param)->isTemplateParameterPack()) {
3759 assert(!getExpandedPackSize(*Param) &&
3760 "Should have dealt with this already");
3761
3762 // A non-expanded parameter pack before the end of the parameter list
3763 // only occurs for an ill-formed template parameter list, unless we've
3764 // got a partial argument list for a function template, so just bail out.
3765 if (Param + 1 != ParamEnd)
3766 return true;
3767
Eli Friedmanb826a002012-09-26 02:36:12 +00003768 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3769 ArgumentPack.data(),
3770 ArgumentPack.size()));
3771 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003772
3773 ++Param;
3774 continue;
3775 }
3776
Douglas Gregor8e072612012-02-03 07:34:46 +00003777 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003778 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003779
Douglas Gregor84d49a22009-11-11 21:54:23 +00003780 // Retrieve the default template argument from the template
3781 // parameter. For each kind of template parameter, we substitute the
3782 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003783 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003784 // the default argument.
3785 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Douglas Gregor8e072612012-02-03 07:34:46 +00003786 if (!TTP->hasDefaultArgument())
3787 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3788 TemplateArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003789
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003790 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003791 Template,
3792 TemplateLoc,
3793 RAngleLoc,
3794 TTP,
3795 Converted);
3796 if (!ArgType)
3797 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003798
Douglas Gregor84d49a22009-11-11 21:54:23 +00003799 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3800 ArgType);
3801 } else if (NonTypeTemplateParmDecl *NTTP
3802 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Douglas Gregor8e072612012-02-03 07:34:46 +00003803 if (!NTTP->hasDefaultArgument())
3804 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3805 TemplateArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003806
John McCalldadc5752010-08-24 06:29:42 +00003807 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003808 TemplateLoc,
3809 RAngleLoc,
3810 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003811 Converted);
3812 if (E.isInvalid())
3813 return true;
3814
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003815 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00003816 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3817 } else {
3818 TemplateTemplateParmDecl *TempParm
3819 = cast<TemplateTemplateParmDecl>(*Param);
3820
Douglas Gregor8e072612012-02-03 07:34:46 +00003821 if (!TempParm->hasDefaultArgument())
3822 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3823 TemplateArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003824
Douglas Gregordf846d12011-03-02 18:46:51 +00003825 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003826 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003827 TemplateLoc,
3828 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003829 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003830 Converted,
3831 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003832 if (Name.isNull())
3833 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003834
Douglas Gregor9d802122011-03-02 17:09:35 +00003835 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3836 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003838
Douglas Gregor84d49a22009-11-11 21:54:23 +00003839 // Introduce an instantiation record that describes where we are using
3840 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003841 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3842 SourceRange(TemplateLoc, RAngleLoc));
3843 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003844 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003845
Douglas Gregor84d49a22009-11-11 21:54:23 +00003846 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003847 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003848 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003849 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003850
Douglas Gregor739b107a2011-03-03 02:41:12 +00003851 // Core issue 150 (assumed resolution): if this is a template template
3852 // parameter, keep track of the default template arguments from the
3853 // template definition.
3854 if (isTemplateTemplateParameter)
3855 TemplateArgs.addArgument(Arg);
3856
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003857 // Move to the next template parameter and argument.
3858 ++Param;
3859 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003860 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003861
Richard Smith07f79912014-06-06 16:00:50 +00003862 // If we're performing a partial argument substitution, allow any trailing
3863 // pack expansions; they might be empty. This can happen even if
3864 // PartialTemplateArgs is false (the list of arguments is complete but
3865 // still dependent).
3866 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3867 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
3868 while (ArgIdx < NumArgs &&
3869 TemplateArgs[ArgIdx].getArgument().isPackExpansion())
3870 Converted.push_back(TemplateArgs[ArgIdx++].getArgument());
3871 }
3872
Douglas Gregor8e072612012-02-03 07:34:46 +00003873 // If we have any leftover arguments, then there were too many arguments.
3874 // Complain and fail.
3875 if (ArgIdx < NumArgs)
3876 return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003877
Richard Smith1fde8ec2012-09-07 02:06:42 +00003878 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00003879}
3880
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003881namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003882 class UnnamedLocalNoLinkageFinder
3883 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003884 {
3885 Sema &S;
3886 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003887
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003888 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003889
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003890 public:
3891 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3892
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893 bool Visit(QualType T) {
3894 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003895 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003896
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003897#define TYPE(Class, Parent) \
3898 bool Visit##Class##Type(const Class##Type *);
3899#define ABSTRACT_TYPE(Class, Parent) \
3900 bool Visit##Class##Type(const Class##Type *) { return false; }
3901#define NON_CANONICAL_TYPE(Class, Parent) \
3902 bool Visit##Class##Type(const Class##Type *) { return false; }
3903#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003904
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003905 bool VisitTagDecl(const TagDecl *Tag);
3906 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3907 };
3908}
3909
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003910bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003911 return false;
3912}
3913
3914bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3915 return Visit(T->getElementType());
3916}
3917
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003918bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003919 return Visit(T->getPointeeType());
3920}
3921
3922bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003923 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003924 return Visit(T->getPointeeType());
3925}
3926
3927bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003928 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003929 return Visit(T->getPointeeType());
3930}
3931
3932bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003933 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003934 return Visit(T->getPointeeType());
3935}
3936
3937bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003938 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003939 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3940}
3941
3942bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003944 return Visit(T->getElementType());
3945}
3946
3947bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003948 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003949 return Visit(T->getElementType());
3950}
3951
3952bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003953 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003954 return Visit(T->getElementType());
3955}
3956
3957bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003958 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003959 return Visit(T->getElementType());
3960}
3961
3962bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003963 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003964 return Visit(T->getElementType());
3965}
3966
3967bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3968 return Visit(T->getElementType());
3969}
3970
3971bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3972 return Visit(T->getElementType());
3973}
3974
3975bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3976 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003977 for (const auto &A : T->param_types()) {
3978 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003979 return true;
3980 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003981
Alp Toker314cc812014-01-25 16:55:45 +00003982 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003983}
3984
3985bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3986 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00003987 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003988}
3989
3990bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3991 const UnresolvedUsingType*) {
3992 return false;
3993}
3994
3995bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3996 return false;
3997}
3998
3999bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4000 return Visit(T->getUnderlyingType());
4001}
4002
4003bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4004 return false;
4005}
4006
Alexis Hunte852b102011-05-24 22:41:36 +00004007bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4008 const UnaryTransformType*) {
4009 return false;
4010}
4011
Richard Smith30482bc2011-02-20 03:19:35 +00004012bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4013 return Visit(T->getDeducedType());
4014}
4015
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004016bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4017 return VisitTagDecl(T->getDecl());
4018}
4019
4020bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4021 return VisitTagDecl(T->getDecl());
4022}
4023
4024bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4025 const TemplateTypeParmType*) {
4026 return false;
4027}
4028
Douglas Gregorada4b792011-01-14 02:55:32 +00004029bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4030 const SubstTemplateTypeParmPackType *) {
4031 return false;
4032}
4033
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004034bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4035 const TemplateSpecializationType*) {
4036 return false;
4037}
4038
4039bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4040 const InjectedClassNameType* T) {
4041 return VisitTagDecl(T->getDecl());
4042}
4043
4044bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4045 const DependentNameType* T) {
4046 return VisitNestedNameSpecifier(T->getQualifier());
4047}
4048
4049bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4050 const DependentTemplateSpecializationType* T) {
4051 return VisitNestedNameSpecifier(T->getQualifier());
4052}
4053
Douglas Gregord2fa7662010-12-20 02:24:11 +00004054bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4055 const PackExpansionType* T) {
4056 return Visit(T->getPattern());
4057}
4058
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004059bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4060 return false;
4061}
4062
4063bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4064 const ObjCInterfaceType *) {
4065 return false;
4066}
4067
4068bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4069 const ObjCObjectPointerType *) {
4070 return false;
4071}
4072
Eli Friedman0dfb8892011-10-06 23:00:33 +00004073bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4074 return Visit(T->getValueType());
4075}
4076
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004077bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4078 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004079 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004080 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004081 diag::warn_cxx98_compat_template_arg_local_type :
4082 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004083 << S.Context.getTypeDeclType(Tag) << SR;
4084 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004085 }
4086
John McCall5ea95772013-03-09 00:54:27 +00004087 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004088 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004089 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004090 diag::warn_cxx98_compat_template_arg_unnamed_type :
4091 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004092 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4093 return true;
4094 }
4095
4096 return false;
4097}
4098
4099bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4100 NestedNameSpecifier *NNS) {
4101 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4102 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004104 switch (NNS->getKind()) {
4105 case NestedNameSpecifier::Identifier:
4106 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004107 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004108 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004109 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004110 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004111
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004112 case NestedNameSpecifier::TypeSpec:
4113 case NestedNameSpecifier::TypeSpecWithTemplate:
4114 return Visit(QualType(NNS->getAsType(), 0));
4115 }
David Blaikie8a40f702012-01-17 06:56:22 +00004116 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004117}
4118
4119
Douglas Gregord32e0282009-02-09 23:23:08 +00004120/// \brief Check a template argument against its corresponding
4121/// template type parameter.
4122///
4123/// This routine implements the semantics of C++ [temp.arg.type]. It
4124/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004125bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004126 TypeSourceInfo *ArgInfo) {
4127 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004128 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004129 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004130
4131 if (Arg->isVariablyModifiedType()) {
4132 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004133 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004134 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004135 }
4136
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004137 // C++03 [temp.arg.type]p2:
4138 // A local type, a type with no linkage, an unnamed type or a type
4139 // compounded from any of these types shall not be used as a
4140 // template-argument for a template type-parameter.
4141 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004142 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004143 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004144 bool NeedsCheck;
4145 if (LangOpts.CPlusPlus11)
4146 NeedsCheck =
4147 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4148 SR.getBegin()) ||
4149 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4150 SR.getBegin());
4151 else
4152 NeedsCheck = Arg->hasUnnamedOrLocalType();
4153
4154 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004155 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4156 (void)Finder.Visit(Context.getCanonicalType(Arg));
4157 }
4158
Douglas Gregord32e0282009-02-09 23:23:08 +00004159 return false;
4160}
4161
Douglas Gregor20fdef32012-04-10 17:08:25 +00004162enum NullPointerValueKind {
4163 NPV_NotNullPointer,
4164 NPV_NullPointer,
4165 NPV_Error
4166};
4167
4168/// \brief Determine whether the given template argument is a null pointer
4169/// value of the appropriate type.
4170static NullPointerValueKind
4171isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4172 QualType ParamType, Expr *Arg) {
4173 if (Arg->isValueDependent() || Arg->isTypeDependent())
4174 return NPV_NotNullPointer;
4175
David Majnemer5c734ad2014-08-14 00:49:23 +00004176 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004177 return NPV_NotNullPointer;
4178
4179 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004180 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4181 if (ArgRV.isInvalid())
4182 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004183 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004184
Douglas Gregor20fdef32012-04-10 17:08:25 +00004185 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004186 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004187 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004188 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004189 EvalResult.HasSideEffects) {
4190 SourceLocation DiagLoc = Arg->getExprLoc();
4191
4192 // If our only note is the usual "invalid subexpression" note, just point
4193 // the caret at its location rather than producing an essentially
4194 // redundant note.
4195 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4196 diag::note_invalid_subexpr_in_const_expr) {
4197 DiagLoc = Notes[0].first;
4198 Notes.clear();
4199 }
4200
4201 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4202 << Arg->getType() << Arg->getSourceRange();
4203 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4204 S.Diag(Notes[I].first, Notes[I].second);
4205
4206 S.Diag(Param->getLocation(), diag::note_template_param_here);
4207 return NPV_Error;
4208 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004209
4210 // C++11 [temp.arg.nontype]p1:
4211 // - an address constant expression of type std::nullptr_t
4212 if (Arg->getType()->isNullPtrType())
4213 return NPV_NullPointer;
4214
4215 // - a constant expression that evaluates to a null pointer value (4.10); or
4216 // - a constant expression that evaluates to a null member pointer value
4217 // (4.11); or
4218 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4219 (EvalResult.Val.isMemberPointer() &&
4220 !EvalResult.Val.getMemberPointerDecl())) {
4221 // If our expression has an appropriate type, we've succeeded.
4222 bool ObjCLifetimeConversion;
4223 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4224 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4225 ObjCLifetimeConversion))
4226 return NPV_NullPointer;
4227
4228 // The types didn't match, but we know we got a null pointer; complain,
4229 // then recover as if the types were correct.
4230 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4231 << Arg->getType() << ParamType << Arg->getSourceRange();
4232 S.Diag(Param->getLocation(), diag::note_template_param_here);
4233 return NPV_NullPointer;
4234 }
4235
4236 // If we don't have a null pointer value, but we do have a NULL pointer
4237 // constant, suggest a cast to the appropriate type.
4238 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4239 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4240 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004241 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4242 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4243 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004244 S.Diag(Param->getLocation(), diag::note_template_param_here);
4245 return NPV_NullPointer;
4246 }
4247
4248 // FIXME: If we ever want to support general, address-constant expressions
4249 // as non-type template arguments, we should return the ExprResult here to
4250 // be interpreted by the caller.
4251 return NPV_NotNullPointer;
4252}
4253
David Majnemer61c39a12013-08-23 05:39:39 +00004254/// \brief Checks whether the given template argument is compatible with its
4255/// template parameter.
4256static bool CheckTemplateArgumentIsCompatibleWithParameter(
4257 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4258 Expr *Arg, QualType ArgType) {
4259 bool ObjCLifetimeConversion;
4260 if (ParamType->isPointerType() &&
4261 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4262 S.IsQualificationConversion(ArgType, ParamType, false,
4263 ObjCLifetimeConversion)) {
4264 // For pointer-to-object types, qualification conversions are
4265 // permitted.
4266 } else {
4267 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4268 if (!ParamRef->getPointeeType()->isFunctionType()) {
4269 // C++ [temp.arg.nontype]p5b3:
4270 // For a non-type template-parameter of type reference to
4271 // object, no conversions apply. The type referred to by the
4272 // reference may be more cv-qualified than the (otherwise
4273 // identical) type of the template- argument. The
4274 // template-parameter is bound directly to the
4275 // template-argument, which shall be an lvalue.
4276
4277 // FIXME: Other qualifiers?
4278 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4279 unsigned ArgQuals = ArgType.getCVRQualifiers();
4280
4281 if ((ParamQuals | ArgQuals) != ParamQuals) {
4282 S.Diag(Arg->getLocStart(),
4283 diag::err_template_arg_ref_bind_ignores_quals)
4284 << ParamType << Arg->getType() << Arg->getSourceRange();
4285 S.Diag(Param->getLocation(), diag::note_template_param_here);
4286 return true;
4287 }
4288 }
4289 }
4290
4291 // At this point, the template argument refers to an object or
4292 // function with external linkage. We now need to check whether the
4293 // argument and parameter types are compatible.
4294 if (!S.Context.hasSameUnqualifiedType(ArgType,
4295 ParamType.getNonReferenceType())) {
4296 // We can't perform this conversion or binding.
4297 if (ParamType->isReferenceType())
4298 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4299 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4300 else
4301 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4302 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4303 S.Diag(Param->getLocation(), diag::note_template_param_here);
4304 return true;
4305 }
4306 }
4307
4308 return false;
4309}
4310
Douglas Gregorccb07762009-02-11 19:52:55 +00004311/// \brief Checks whether the given template argument is the address
4312/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004314CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4315 NonTypeTemplateParmDecl *Param,
4316 QualType ParamType,
4317 Expr *ArgIn,
4318 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004319 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004320 Expr *Arg = ArgIn;
4321 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004322
Douglas Gregorb242683d2010-04-01 18:32:35 +00004323 bool AddressTaken = false;
4324 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004325 if (S.getLangOpts().MicrosoftExt) {
4326 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4327 // dereference and address-of operators.
4328 Arg = Arg->IgnoreParenCasts();
4329
4330 bool ExtWarnMSTemplateArg = false;
4331 UnaryOperatorKind FirstOpKind;
4332 SourceLocation FirstOpLoc;
4333 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4334 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4335 if (UnOpKind == UO_Deref)
4336 ExtWarnMSTemplateArg = true;
4337 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4338 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4339 if (!AddrOpLoc.isValid()) {
4340 FirstOpKind = UnOpKind;
4341 FirstOpLoc = UnOp->getOperatorLoc();
4342 }
4343 } else
4344 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004345 }
David Majnemer61c39a12013-08-23 05:39:39 +00004346 if (FirstOpLoc.isValid()) {
4347 if (ExtWarnMSTemplateArg)
4348 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4349 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004350
David Majnemer61c39a12013-08-23 05:39:39 +00004351 if (FirstOpKind == UO_AddrOf)
4352 AddressTaken = true;
4353 else if (Arg->getType()->isPointerType()) {
4354 // We cannot let pointers get dereferenced here, that is obviously not a
4355 // constant expression.
4356 assert(FirstOpKind == UO_Deref);
4357 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4358 << Arg->getSourceRange();
4359 }
4360 }
4361 } else {
4362 // See through any implicit casts we added to fix the type.
4363 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004364
David Majnemer61c39a12013-08-23 05:39:39 +00004365 // C++ [temp.arg.nontype]p1:
4366 //
4367 // A template-argument for a non-type, non-template
4368 // template-parameter shall be one of: [...]
4369 //
4370 // -- the address of an object or function with external
4371 // linkage, including function templates and function
4372 // template-ids but excluding non-static class members,
4373 // expressed as & id-expression where the & is optional if
4374 // the name refers to a function or array, or if the
4375 // corresponding template-parameter is a reference; or
4376
4377 // In C++98/03 mode, give an extension warning on any extra parentheses.
4378 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4379 bool ExtraParens = false;
4380 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4381 if (!Invalid && !ExtraParens) {
4382 S.Diag(Arg->getLocStart(),
4383 S.getLangOpts().CPlusPlus11
4384 ? diag::warn_cxx98_compat_template_arg_extra_parens
4385 : diag::ext_template_arg_extra_parens)
4386 << Arg->getSourceRange();
4387 ExtraParens = true;
4388 }
4389
4390 Arg = Parens->getSubExpr();
4391 }
4392
4393 while (SubstNonTypeTemplateParmExpr *subst =
4394 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4395 Arg = subst->getReplacement()->IgnoreImpCasts();
4396
4397 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4398 if (UnOp->getOpcode() == UO_AddrOf) {
4399 Arg = UnOp->getSubExpr();
4400 AddressTaken = true;
4401 AddrOpLoc = UnOp->getOperatorLoc();
4402 }
4403 }
4404
4405 while (SubstNonTypeTemplateParmExpr *subst =
4406 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4407 Arg = subst->getReplacement()->IgnoreImpCasts();
4408 }
John McCall7c454bb2011-07-15 05:09:51 +00004409
David Majnemer07910d62014-06-26 07:48:46 +00004410 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4411 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4412
4413 // If our parameter has pointer type, check for a null template value.
4414 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4415 NullPointerValueKind NPV;
4416 // dllimport'd entities aren't constant but are available inside of template
4417 // arguments.
4418 if (Entity && Entity->hasAttr<DLLImportAttr>())
4419 NPV = NPV_NotNullPointer;
4420 else
4421 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4422 switch (NPV) {
4423 case NPV_NullPointer:
4424 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004425 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4426 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004427 return false;
4428
4429 case NPV_Error:
4430 return true;
4431
4432 case NPV_NotNullPointer:
4433 break;
4434 }
4435 }
4436
Chandler Carruth724a8a12010-01-31 10:01:20 +00004437 // Stop checking the precise nature of the argument if it is value dependent,
4438 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004439 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004440 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004441 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004442 }
David Majnemer61c39a12013-08-23 05:39:39 +00004443
4444 if (isa<CXXUuidofExpr>(Arg)) {
4445 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4446 ArgIn, Arg, ArgType))
4447 return true;
4448
4449 Converted = TemplateArgument(ArgIn);
4450 return false;
4451 }
4452
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004453 if (!DRE) {
4454 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4455 << Arg->getSourceRange();
4456 S.Diag(Param->getLocation(), diag::note_template_param_here);
4457 return true;
4458 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004459
Douglas Gregorccb07762009-02-11 19:52:55 +00004460 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004461 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004462 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004463 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004464 S.Diag(Param->getLocation(), diag::note_template_param_here);
4465 return true;
4466 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004467
4468 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004469 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004470 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004471 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004472 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004473 S.Diag(Param->getLocation(), diag::note_template_param_here);
4474 return true;
4475 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004476 }
Mike Stump11289f42009-09-09 15:08:12 +00004477
Richard Smith9380e0e2012-04-04 21:11:30 +00004478 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4479 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004480
Richard Smith9380e0e2012-04-04 21:11:30 +00004481 // A non-type template argument must refer to an object or function.
4482 if (!Func && !Var) {
4483 // We found something, but we don't know specifically what it is.
4484 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4485 << Arg->getSourceRange();
4486 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4487 return true;
4488 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004489
Richard Smith9380e0e2012-04-04 21:11:30 +00004490 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004491 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004492 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004493 diag::warn_cxx98_compat_template_arg_object_internal :
4494 diag::ext_template_arg_object_internal)
4495 << !Func << Entity << Arg->getSourceRange();
4496 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4497 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004498 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004499 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4500 << !Func << Entity << Arg->getSourceRange();
4501 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4502 << !Func;
4503 return true;
4504 }
4505
4506 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004507 // If the template parameter has pointer type, the function decays.
4508 if (ParamType->isPointerType() && !AddressTaken)
4509 ArgType = S.Context.getPointerType(Func->getType());
4510 else if (AddressTaken && ParamType->isReferenceType()) {
4511 // If we originally had an address-of operator, but the
4512 // parameter has reference type, complain and (if things look
4513 // like they will work) drop the address-of operator.
4514 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4515 ParamType.getNonReferenceType())) {
4516 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4517 << ParamType;
4518 S.Diag(Param->getLocation(), diag::note_template_param_here);
4519 return true;
4520 }
4521
4522 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4523 << ParamType
4524 << FixItHint::CreateRemoval(AddrOpLoc);
4525 S.Diag(Param->getLocation(), diag::note_template_param_here);
4526
4527 ArgType = Func->getType();
4528 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004529 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004530 // A value of reference type is not an object.
4531 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004532 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004533 diag::err_template_arg_reference_var)
4534 << Var->getType() << Arg->getSourceRange();
4535 S.Diag(Param->getLocation(), diag::note_template_param_here);
4536 return true;
4537 }
4538
Richard Smith9380e0e2012-04-04 21:11:30 +00004539 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004540 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004541 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4542 << Arg->getSourceRange();
4543 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4544 return true;
4545 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004546
4547 // If the template parameter has pointer type, we must have taken
4548 // the address of this object.
4549 if (ParamType->isReferenceType()) {
4550 if (AddressTaken) {
4551 // If we originally had an address-of operator, but the
4552 // parameter has reference type, complain and (if things look
4553 // like they will work) drop the address-of operator.
4554 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4555 ParamType.getNonReferenceType())) {
4556 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4557 << ParamType;
4558 S.Diag(Param->getLocation(), diag::note_template_param_here);
4559 return true;
4560 }
4561
4562 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4563 << ParamType
4564 << FixItHint::CreateRemoval(AddrOpLoc);
4565 S.Diag(Param->getLocation(), diag::note_template_param_here);
4566
4567 ArgType = Var->getType();
4568 }
4569 } else if (!AddressTaken && ParamType->isPointerType()) {
4570 if (Var->getType()->isArrayType()) {
4571 // Array-to-pointer decay.
4572 ArgType = S.Context.getArrayDecayedType(Var->getType());
4573 } else {
4574 // If the template parameter has pointer type but the address of
4575 // this object was not taken, complain and (possibly) recover by
4576 // taking the address of the entity.
4577 ArgType = S.Context.getPointerType(Var->getType());
4578 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4579 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4580 << ParamType;
4581 S.Diag(Param->getLocation(), diag::note_template_param_here);
4582 return true;
4583 }
4584
4585 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4586 << ParamType
4587 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4588
4589 S.Diag(Param->getLocation(), diag::note_template_param_here);
4590 }
4591 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004592 }
Mike Stump11289f42009-09-09 15:08:12 +00004593
David Majnemer61c39a12013-08-23 05:39:39 +00004594 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4595 Arg, ArgType))
4596 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004597
4598 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004599 Converted =
4600 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004601 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004602 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004603}
4604
4605/// \brief Checks whether the given template argument is a pointer to
4606/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004607static bool CheckTemplateArgumentPointerToMember(Sema &S,
4608 NonTypeTemplateParmDecl *Param,
4609 QualType ParamType,
4610 Expr *&ResultArg,
4611 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004612 bool Invalid = false;
4613
Douglas Gregor20fdef32012-04-10 17:08:25 +00004614 // Check for a null pointer value.
4615 Expr *Arg = ResultArg;
4616 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4617 case NPV_Error:
4618 return true;
4619 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004620 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004621 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4622 /*isNullPtr*/true);
David Majnemer763584d2014-02-06 10:59:19 +00004623 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4624 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004625 return false;
4626 case NPV_NotNullPointer:
4627 break;
4628 }
4629
4630 bool ObjCLifetimeConversion;
4631 if (S.IsQualificationConversion(Arg->getType(),
4632 ParamType.getNonReferenceType(),
4633 false, ObjCLifetimeConversion)) {
4634 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004635 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004636 ResultArg = Arg;
4637 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4638 ParamType.getNonReferenceType())) {
4639 // We can't perform this conversion.
4640 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4641 << Arg->getType() << ParamType << Arg->getSourceRange();
4642 S.Diag(Param->getLocation(), diag::note_template_param_here);
4643 return true;
4644 }
4645
Douglas Gregorccb07762009-02-11 19:52:55 +00004646 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004647 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004648 Arg = Cast->getSubExpr();
4649
4650 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004651 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004652 // A template-argument for a non-type, non-template
4653 // template-parameter shall be one of: [...]
4654 //
4655 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004656 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004657
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004658 // In C++98/03 mode, give an extension warning on any extra parentheses.
4659 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4660 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004661 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004662 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004663 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004664 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004665 diag::warn_cxx98_compat_template_arg_extra_parens :
4666 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004667 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004668 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004669 }
4670
4671 Arg = Parens->getSubExpr();
4672 }
4673
John McCall7c454bb2011-07-15 05:09:51 +00004674 while (SubstNonTypeTemplateParmExpr *subst =
4675 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4676 Arg = subst->getReplacement()->IgnoreImpCasts();
4677
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004678 // A pointer-to-member constant written &Class::member.
4679 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004680 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004681 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4682 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004683 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004684 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004685 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004686 // A constant of pointer-to-member type.
4687 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4688 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4689 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004690 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004691 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004692 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004693 } else {
4694 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004695 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004696 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004697 return Invalid;
4698 }
4699 }
4700 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004701
Craig Topperc3ec1492014-05-26 06:22:03 +00004702 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004703 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004704
Douglas Gregorccb07762009-02-11 19:52:55 +00004705 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004706 return S.Diag(Arg->getLocStart(),
4707 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004708 << Arg->getSourceRange();
4709
David Majnemer3ac84e62013-10-22 21:56:38 +00004710 if (isa<FieldDecl>(DRE->getDecl()) ||
4711 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4712 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004713 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004714 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004715 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4716 "Only non-static member pointers can make it here");
4717
4718 // Okay: this is the address of a non-static member, and therefore
4719 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004720 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004721 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004722 } else {
4723 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004724 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004725 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004726 return Invalid;
4727 }
4728
4729 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004730 S.Diag(Arg->getLocStart(),
4731 diag::err_template_arg_not_pointer_to_member_form)
4732 << Arg->getSourceRange();
4733 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004734 return true;
4735}
4736
Douglas Gregord32e0282009-02-09 23:23:08 +00004737/// \brief Check a template argument against its corresponding
4738/// non-type template parameter.
4739///
Douglas Gregor463421d2009-03-03 04:44:36 +00004740/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004741/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004742/// returns the converted template argument. \p ParamType is the
4743/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004744ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004745 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004746 TemplateArgument &Converted,
4747 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004748 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004749
Douglas Gregor86560402009-02-10 23:36:10 +00004750 // If either the parameter has a dependent type or the argument is
4751 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004752 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004753 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004754 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004755 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004756 }
Douglas Gregor86560402009-02-10 23:36:10 +00004757
Richard Smithd663fdd2014-12-17 20:42:37 +00004758 // We should have already dropped all cv-qualifiers by now.
4759 assert(!ParamType.hasQualifiers() &&
4760 "non-type template parameter type cannot be qualified");
4761
4762 if (CTAK == CTAK_Deduced &&
4763 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4764 // C++ [temp.deduct.type]p17:
4765 // If, in the declaration of a function template with a non-type
4766 // template-parameter, the non-type template-parameter is used
4767 // in an expression in the function parameter-list and, if the
4768 // corresponding template-argument is deduced, the
4769 // template-argument type shall match the type of the
4770 // template-parameter exactly, except that a template-argument
4771 // deduced from an array bound may be of any integral type.
4772 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4773 << Arg->getType().getUnqualifiedType()
4774 << ParamType.getUnqualifiedType();
4775 Diag(Param->getLocation(), diag::note_template_param_here);
4776 return ExprError();
4777 }
4778
Richard Smith410cc892014-11-26 03:26:53 +00004779 if (getLangOpts().CPlusPlus1z) {
4780 // FIXME: We can do some limited checking for a value-dependent but not
4781 // type-dependent argument.
4782 if (Arg->isValueDependent()) {
4783 Converted = TemplateArgument(Arg);
4784 return Arg;
4785 }
4786
4787 // C++1z [temp.arg.nontype]p1:
4788 // A template-argument for a non-type template parameter shall be
4789 // a converted constant expression of the type of the template-parameter.
4790 APValue Value;
4791 ExprResult ArgResult = CheckConvertedConstantExpression(
4792 Arg, ParamType, Value, CCEK_TemplateArg);
4793 if (ArgResult.isInvalid())
4794 return ExprError();
4795
Richard Smithd663fdd2014-12-17 20:42:37 +00004796 QualType CanonParamType = Context.getCanonicalType(ParamType);
4797
Richard Smith410cc892014-11-26 03:26:53 +00004798 // Convert the APValue to a TemplateArgument.
4799 switch (Value.getKind()) {
4800 case APValue::Uninitialized:
4801 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004802 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004803 break;
4804 case APValue::Int:
4805 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004806 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00004807 break;
4808 case APValue::MemberPointer: {
4809 assert(ParamType->isMemberPointerType());
4810
4811 // FIXME: We need TemplateArgument representation and mangling for these.
4812 if (!Value.getMemberPointerPath().empty()) {
4813 Diag(Arg->getLocStart(),
4814 diag::err_template_arg_member_ptr_base_derived_not_supported)
4815 << Value.getMemberPointerDecl() << ParamType
4816 << Arg->getSourceRange();
4817 return ExprError();
4818 }
4819
4820 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00004821 Converted = VD ? TemplateArgument(VD, CanonParamType)
4822 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004823 break;
4824 }
4825 case APValue::LValue: {
4826 // For a non-type template-parameter of pointer or reference type,
4827 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00004828 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4829 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00004830 // -- a temporary object
4831 // -- a string literal
4832 // -- the result of a typeid expression, or
4833 // -- a predefind __func__ variable
4834 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4835 if (isa<CXXUuidofExpr>(E)) {
4836 Converted = TemplateArgument(const_cast<Expr*>(E));
4837 break;
4838 }
4839 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4840 << Arg->getSourceRange();
4841 return ExprError();
4842 }
4843 auto *VD = const_cast<ValueDecl *>(
4844 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4845 // -- a subobject
4846 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4847 VD && VD->getType()->isArrayType() &&
4848 Value.getLValuePath()[0].ArrayIndex == 0 &&
4849 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4850 // Per defect report (no number yet):
4851 // ... other than a pointer to the first element of a complete array
4852 // object.
4853 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4854 Value.isLValueOnePastTheEnd()) {
4855 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4856 << Value.getAsString(Context, ParamType);
4857 return ExprError();
4858 }
Richard Smithd663fdd2014-12-17 20:42:37 +00004859 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00004860 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00004861 assert((!VD || !ParamType->isNullPtrType()) &&
4862 "non-null value of type nullptr_t?");
4863 Converted = VD ? TemplateArgument(VD, CanonParamType)
4864 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004865 break;
4866 }
4867 case APValue::AddrLabelDiff:
4868 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4869 case APValue::Float:
4870 case APValue::ComplexInt:
4871 case APValue::ComplexFloat:
4872 case APValue::Vector:
4873 case APValue::Array:
4874 case APValue::Struct:
4875 case APValue::Union:
4876 llvm_unreachable("invalid kind for template argument");
4877 }
4878
4879 return ArgResult.get();
4880 }
4881
Douglas Gregor86560402009-02-10 23:36:10 +00004882 // C++ [temp.arg.nontype]p5:
4883 // The following conversions are performed on each expression used
4884 // as a non-type template-argument. If a non-type
4885 // template-argument cannot be converted to the type of the
4886 // corresponding template-parameter then the program is
4887 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00004888 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00004889 // C++11:
4890 // -- for a non-type template-parameter of integral or
4891 // enumeration type, conversions permitted in a converted
4892 // constant expression are applied.
4893 //
4894 // C++98:
4895 // -- for a non-type template-parameter of integral or
4896 // enumeration type, integral promotions (4.5) and integral
4897 // conversions (4.7) are applied.
4898
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004899 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00004900 // We can't check arbitrary value-dependent arguments.
4901 // FIXME: If there's no viable conversion to the template parameter type,
4902 // we should be able to diagnose that prior to instantiation.
4903 if (Arg->isValueDependent()) {
4904 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004905 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00004906 }
4907
4908 // C++ [temp.arg.nontype]p1:
4909 // A template-argument for a non-type, non-template template-parameter
4910 // shall be one of:
4911 //
4912 // -- for a non-type template-parameter of integral or enumeration
4913 // type, a converted constant expression of the type of the
4914 // template-parameter; or
4915 llvm::APSInt Value;
4916 ExprResult ArgResult =
4917 CheckConvertedConstantExpression(Arg, ParamType, Value,
4918 CCEK_TemplateArg);
4919 if (ArgResult.isInvalid())
4920 return ExprError();
4921
4922 // Widen the argument value to sizeof(parameter type). This is almost
4923 // always a no-op, except when the parameter type is bool. In
4924 // that case, this may extend the argument from 1 bit to 8 bits.
4925 QualType IntegerType = ParamType;
4926 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4927 IntegerType = Enum->getDecl()->getIntegerType();
4928 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4929
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004930 Converted = TemplateArgument(Context, Value,
4931 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00004932 return ArgResult;
4933 }
4934
Richard Smith08b12f12011-10-27 22:11:44 +00004935 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4936 if (ArgResult.isInvalid())
4937 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004938 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00004939
4940 QualType ArgType = Arg->getType();
4941
Douglas Gregor86560402009-02-10 23:36:10 +00004942 // C++ [temp.arg.nontype]p1:
4943 // A template-argument for a non-type, non-template
4944 // template-parameter shall be one of:
4945 //
4946 // -- an integral constant-expression of integral or enumeration
4947 // type; or
4948 // -- the name of a non-type template-parameter; or
4949 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004950 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00004951 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004952 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00004953 diag::err_template_arg_not_integral_or_enumeral)
4954 << ArgType << Arg->getSourceRange();
4955 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00004956 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00004957 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00004958 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4959 QualType T;
4960
4961 public:
4962 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00004963
4964 void diagnoseNotICE(Sema &S, SourceLocation Loc,
4965 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00004966 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
4967 }
4968 } Diagnoser(ArgType);
4969
4970 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004971 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00004972 if (!Arg)
4973 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00004974 }
4975
Richard Smithd663fdd2014-12-17 20:42:37 +00004976 // From here on out, all we care about is the unqualified form
4977 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004978 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00004979
4980 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00004981 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00004982 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00004983 } else if (ParamType->isBooleanType()) {
4984 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004985 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00004986 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
4987 !ParamType->isEnumeralType()) {
4988 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004989 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00004990 } else {
4991 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004992 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00004993 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00004994 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00004995 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00004996 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00004997 }
4998
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004999 // Add the value of this argument to the list of converted
5000 // arguments. We use the bitwidth and signedness of the template
5001 // parameter.
5002 if (Arg->isValueDependent()) {
5003 // The argument is value-dependent. Create a new
5004 // TemplateArgument with the converted expression.
5005 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005006 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005007 }
5008
Douglas Gregor52aba872009-03-14 00:20:21 +00005009 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005010 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005011 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005012
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005013 if (ParamType->isBooleanType()) {
5014 // Value must be zero or one.
5015 Value = Value != 0;
5016 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5017 if (Value.getBitWidth() != AllowedBits)
5018 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005019 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005020 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005021 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005022
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005023 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005024 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005025 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005026 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005027 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005028 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005029
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005030 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005031 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005032 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005033 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005034 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5035 << Arg->getSourceRange();
5036 Diag(Param->getLocation(), diag::note_template_param_here);
5037 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005038
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005039 // Complain if we overflowed the template parameter's type.
5040 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005041 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005042 RequiredBits = OldValue.getActiveBits();
5043 else if (OldValue.isUnsigned())
5044 RequiredBits = OldValue.getActiveBits() + 1;
5045 else
5046 RequiredBits = OldValue.getMinSignedBits();
5047 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005048 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005049 diag::warn_template_arg_too_large)
5050 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5051 << Arg->getSourceRange();
5052 Diag(Param->getLocation(), diag::note_template_param_here);
5053 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005054 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005055
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005056 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005057 ParamType->isEnumeralType()
5058 ? Context.getCanonicalType(ParamType)
5059 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005060 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005061 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005062
Richard Smith08b12f12011-10-27 22:11:44 +00005063 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005064 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5065
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005066 // Handle pointer-to-function, reference-to-function, and
5067 // pointer-to-member-function all in (roughly) the same way.
5068 if (// -- For a non-type template-parameter of type pointer to
5069 // function, only the function-to-pointer conversion (4.3) is
5070 // applied. If the template-argument represents a set of
5071 // overloaded functions (or a pointer to such), the matching
5072 // function is selected from the set (13.4).
5073 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005074 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005075 // -- For a non-type template-parameter of type reference to
5076 // function, no conversions apply. If the template-argument
5077 // represents a set of overloaded functions, the matching
5078 // function is selected from the set (13.4).
5079 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005080 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005081 // -- For a non-type template-parameter of type pointer to
5082 // member function, no conversions apply. If the
5083 // template-argument represents a set of overloaded member
5084 // functions, the matching member function is selected from
5085 // the set (13.4).
5086 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005087 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005088 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005089
Douglas Gregor064fdb22010-04-14 23:11:21 +00005090 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005091 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005092 true,
5093 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005094 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005095 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005096
5097 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5098 ArgType = Arg->getType();
5099 } else
John Wiegley01296292011-04-08 18:41:53 +00005100 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005102
John Wiegley01296292011-04-08 18:41:53 +00005103 if (!ParamType->isMemberPointerType()) {
5104 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5105 ParamType,
5106 Arg, Converted))
5107 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005108 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005109 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005110
Douglas Gregor20fdef32012-04-10 17:08:25 +00005111 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5112 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005113 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005114 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005115 }
5116
Chris Lattner696197c2009-02-20 21:37:53 +00005117 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005118 // -- for a non-type template-parameter of type pointer to
5119 // object, qualification conversions (4.4) and the
5120 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005121 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005122 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005123 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005124
John Wiegley01296292011-04-08 18:41:53 +00005125 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5126 ParamType,
5127 Arg, Converted))
5128 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005129 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005130 }
Mike Stump11289f42009-09-09 15:08:12 +00005131
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005132 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005133 // -- For a non-type template-parameter of type reference to
5134 // object, no conversions apply. The type referred to by the
5135 // reference may be more cv-qualified than the (otherwise
5136 // identical) type of the template-argument. The
5137 // template-parameter is bound directly to the
5138 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005139 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005140 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005141
Douglas Gregor064fdb22010-04-14 23:11:21 +00005142 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005143 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5144 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005145 true,
5146 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005147 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005148 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005149
5150 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5151 ArgType = Arg->getType();
5152 } else
John Wiegley01296292011-04-08 18:41:53 +00005153 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005154 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005155
John Wiegley01296292011-04-08 18:41:53 +00005156 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5157 ParamType,
5158 Arg, Converted))
5159 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005160 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005161 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005162
Douglas Gregor20fdef32012-04-10 17:08:25 +00005163 // Deal with parameters of type std::nullptr_t.
5164 if (ParamType->isNullPtrType()) {
5165 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5166 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005167 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005168 }
5169
5170 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5171 case NPV_NotNullPointer:
5172 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5173 << Arg->getType() << ParamType;
5174 Diag(Param->getLocation(), diag::note_template_param_here);
5175 return ExprError();
5176
5177 case NPV_Error:
5178 return ExprError();
5179
5180 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005181 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005182 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5183 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005184 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005185 }
5186 }
5187
Douglas Gregor0e558532009-02-11 16:16:59 +00005188 // -- For a non-type template-parameter of type pointer to data
5189 // member, qualification conversions (4.4) are applied.
5190 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5191
Douglas Gregor20fdef32012-04-10 17:08:25 +00005192 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5193 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005194 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005195 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005196}
5197
5198/// \brief Check a template argument against its corresponding
5199/// template template parameter.
5200///
5201/// This routine implements the semantics of C++ [temp.arg.template].
5202/// It returns true if an error occurred, and false otherwise.
5203bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005204 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005205 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005206 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005207 TemplateDecl *Template = Name.getAsTemplateDecl();
5208 if (!Template) {
5209 // Any dependent template name is fine.
5210 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5211 return false;
5212 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005213
Richard Smith3f1b5d02011-05-05 21:57:07 +00005214 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005215 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005216 // the name of a class template or an alias template, expressed as an
5217 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005218 // primary class templates are considered when matching the
5219 // template template argument with the corresponding parameter;
5220 // partial specializations are not considered even if their
5221 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005222 //
5223 // Note that we also allow template template parameters here, which
5224 // will happen when we are dealing with, e.g., class template
5225 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005226 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005227 !isa<TemplateTemplateParmDecl>(Template) &&
5228 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005229 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005230 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005231 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005232 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005233 << Template;
5234 }
5235
Richard Smith1fde8ec2012-09-07 02:06:42 +00005236 TemplateParameterList *Params = Param->getTemplateParameters();
5237 if (Param->isExpandedParameterPack())
5238 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5239
Douglas Gregor85e0f662009-02-10 00:24:35 +00005240 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005241 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005242 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005243 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005244 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005245}
5246
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005247/// \brief Given a non-type template argument that refers to a
5248/// declaration and the type of its corresponding non-type template
5249/// parameter, produce an expression that properly refers to that
5250/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005251ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005252Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5253 QualType ParamType,
5254 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005255 // C++ [temp.param]p8:
5256 //
5257 // A non-type template-parameter of type "array of T" or
5258 // "function returning T" is adjusted to be of type "pointer to
5259 // T" or "pointer to function returning T", respectively.
5260 if (ParamType->isArrayType())
5261 ParamType = Context.getArrayDecayedType(ParamType);
5262 else if (ParamType->isFunctionType())
5263 ParamType = Context.getPointerType(ParamType);
5264
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005265 // For a NULL non-type template argument, return nullptr casted to the
5266 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005267 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005268 return ImpCastExprToType(
5269 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5270 ParamType,
5271 ParamType->getAs<MemberPointerType>()
5272 ? CK_NullToMemberPointer
5273 : CK_NullToPointer);
5274 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005275 assert(Arg.getKind() == TemplateArgument::Declaration &&
5276 "Only declaration template arguments permitted here");
5277
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005278 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5279
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005280 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005281 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5282 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005283 // If the value is a class member, we might have a pointer-to-member.
5284 // Determine whether the non-type template template parameter is of
5285 // pointer-to-member type. If so, we need to build an appropriate
5286 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5287 // would refer to the member itself.
5288 if (ParamType->isMemberPointerType()) {
5289 QualType ClassType
5290 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5291 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005292 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005293 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005294 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005295 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005296
5297 // The actual value-ness of this is unimportant, but for
5298 // internal consistency's sake, references to instance methods
5299 // are r-values.
5300 ExprValueKind VK = VK_LValue;
5301 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5302 VK = VK_RValue;
5303
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005304 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005305 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005306 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005307 Loc,
5308 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005309 if (RefExpr.isInvalid())
5310 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005311
John McCalle3027922010-08-25 11:45:40 +00005312 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005313
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005314 // We might need to perform a trailing qualification conversion, since
5315 // the element type on the parameter could be more qualified than the
5316 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005317 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005318 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005319 ParamType.getUnqualifiedType(), false,
5320 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005321 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005322
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005323 assert(!RefExpr.isInvalid() &&
5324 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005325 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005326 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005327 }
5328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005329
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005330 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005331
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005332 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005333 // When the non-type template parameter is a pointer, take the
5334 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005335 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005336 if (RefExpr.isInvalid())
5337 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005338
5339 if (T->isFunctionType() || T->isArrayType()) {
5340 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005341 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005342 if (RefExpr.isInvalid())
5343 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005344
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005345 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005346 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005347
Douglas Gregorb242683d2010-04-01 18:32:35 +00005348 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005349 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005350 }
5351
John McCall7decc9e2010-11-18 06:31:45 +00005352 ExprValueKind VK = VK_RValue;
5353
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005354 // If the non-type template parameter has reference type, qualify the
5355 // resulting declaration reference with the extra qualifiers on the
5356 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005357 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5358 VK = VK_LValue;
5359 T = Context.getQualifiedType(T,
5360 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005361 } else if (isa<FunctionDecl>(VD)) {
5362 // References to functions are always lvalues.
5363 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005365
John McCall7decc9e2010-11-18 06:31:45 +00005366 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005367}
5368
5369/// \brief Construct a new expression that refers to the given
5370/// integral template argument with the given source-location
5371/// information.
5372///
5373/// This routine takes care of the mapping from an integral template
5374/// argument (which may have any integral type) to the appropriate
5375/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005376ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005377Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5378 SourceLocation Loc) {
5379 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005380 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005381 QualType OrigT = Arg.getIntegralType();
5382
5383 // If this is an enum type that we're instantiating, we need to use an integer
5384 // type the same size as the enumerator. We don't want to build an
5385 // IntegerLiteral with enum type. The integer type of an enum type can be of
5386 // any integral type with C++11 enum classes, make sure we create the right
5387 // type of literal for it.
5388 QualType T = OrigT;
5389 if (const EnumType *ET = OrigT->getAs<EnumType>())
5390 T = ET->getDecl()->getIntegerType();
5391
5392 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005393 if (T->isAnyCharacterType()) {
5394 CharacterLiteral::CharacterKind Kind;
5395 if (T->isWideCharType())
5396 Kind = CharacterLiteral::Wide;
5397 else if (T->isChar16Type())
5398 Kind = CharacterLiteral::UTF16;
5399 else if (T->isChar32Type())
5400 Kind = CharacterLiteral::UTF32;
5401 else
5402 Kind = CharacterLiteral::Ascii;
5403
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005404 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5405 Kind, T, Loc);
5406 } else if (T->isBooleanType()) {
5407 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5408 T, Loc);
5409 } else if (T->isNullPtrType()) {
5410 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5411 } else {
5412 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005413 }
5414
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005415 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005416 // FIXME: This is a hack. We need a better way to handle substituted
5417 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005418 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5419 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005420 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005421 Loc, Loc);
5422 }
5423
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005424 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005425}
5426
Douglas Gregor641040a2011-01-12 23:45:44 +00005427/// \brief Match two template parameters within template parameter lists.
5428static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5429 bool Complain,
5430 Sema::TemplateParameterListEqualKind Kind,
5431 SourceLocation TemplateArgLoc) {
5432 // Check the actual kind (type, non-type, template).
5433 if (Old->getKind() != New->getKind()) {
5434 if (Complain) {
5435 unsigned NextDiag = diag::err_template_param_different_kind;
5436 if (TemplateArgLoc.isValid()) {
5437 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5438 NextDiag = diag::note_template_param_different_kind;
5439 }
5440 S.Diag(New->getLocation(), NextDiag)
5441 << (Kind != Sema::TPL_TemplateMatch);
5442 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5443 << (Kind != Sema::TPL_TemplateMatch);
5444 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005445
Douglas Gregor641040a2011-01-12 23:45:44 +00005446 return false;
5447 }
5448
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005449 // Check that both are parameter packs are neither are parameter packs.
5450 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005451 // template template parameter, the template template parameter can have
5452 // a parameter pack where the template template argument does not.
5453 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5454 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5455 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005456 if (Complain) {
5457 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5458 if (TemplateArgLoc.isValid()) {
5459 S.Diag(TemplateArgLoc,
5460 diag::err_template_arg_template_params_mismatch);
5461 NextDiag = diag::note_template_parameter_pack_non_pack;
5462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005463
Douglas Gregor641040a2011-01-12 23:45:44 +00005464 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5465 : isa<NonTypeTemplateParmDecl>(New)? 1
5466 : 2;
5467 S.Diag(New->getLocation(), NextDiag)
5468 << ParamKind << New->isParameterPack();
5469 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5470 << ParamKind << Old->isParameterPack();
5471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005472
Douglas Gregor641040a2011-01-12 23:45:44 +00005473 return false;
5474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005475
Douglas Gregor641040a2011-01-12 23:45:44 +00005476 // For non-type template parameters, check the type of the parameter.
5477 if (NonTypeTemplateParmDecl *OldNTTP
5478 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5479 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005480
Douglas Gregor641040a2011-01-12 23:45:44 +00005481 // If we are matching a template template argument to a template
5482 // template parameter and one of the non-type template parameter types
5483 // is dependent, then we must wait until template instantiation time
5484 // to actually compare the arguments.
5485 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5486 (OldNTTP->getType()->isDependentType() ||
5487 NewNTTP->getType()->isDependentType()))
5488 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005489
Douglas Gregor641040a2011-01-12 23:45:44 +00005490 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5491 if (Complain) {
5492 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5493 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005494 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005495 diag::err_template_arg_template_params_mismatch);
5496 NextDiag = diag::note_template_nontype_parm_different_type;
5497 }
5498 S.Diag(NewNTTP->getLocation(), NextDiag)
5499 << NewNTTP->getType()
5500 << (Kind != Sema::TPL_TemplateMatch);
5501 S.Diag(OldNTTP->getLocation(),
5502 diag::note_template_nontype_parm_prev_declaration)
5503 << OldNTTP->getType();
5504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505
Douglas Gregor641040a2011-01-12 23:45:44 +00005506 return false;
5507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005508
Douglas Gregor641040a2011-01-12 23:45:44 +00005509 return true;
5510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005511
Douglas Gregor641040a2011-01-12 23:45:44 +00005512 // For template template parameters, check the template parameter types.
5513 // The template parameter lists of template template
5514 // parameters must agree.
5515 if (TemplateTemplateParmDecl *OldTTP
5516 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005517 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005518 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5519 OldTTP->getTemplateParameters(),
5520 Complain,
5521 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005522 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005523 : Kind),
5524 TemplateArgLoc);
5525 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005526
Douglas Gregor641040a2011-01-12 23:45:44 +00005527 return true;
5528}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005529
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005530/// \brief Diagnose a known arity mismatch when comparing template argument
5531/// lists.
5532static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005533void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005534 TemplateParameterList *New,
5535 TemplateParameterList *Old,
5536 Sema::TemplateParameterListEqualKind Kind,
5537 SourceLocation TemplateArgLoc) {
5538 unsigned NextDiag = diag::err_template_param_list_different_arity;
5539 if (TemplateArgLoc.isValid()) {
5540 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5541 NextDiag = diag::note_template_param_list_different_arity;
5542 }
5543 S.Diag(New->getTemplateLoc(), NextDiag)
5544 << (New->size() > Old->size())
5545 << (Kind != Sema::TPL_TemplateMatch)
5546 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5547 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5548 << (Kind != Sema::TPL_TemplateMatch)
5549 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5550}
5551
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005552/// \brief Determine whether the given template parameter lists are
5553/// equivalent.
5554///
Mike Stump11289f42009-09-09 15:08:12 +00005555/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005556/// source code as part of a new template declaration.
5557///
5558/// \param Old The old template parameter list, typically found via
5559/// name lookup of the template declared with this template parameter
5560/// list.
5561///
5562/// \param Complain If true, this routine will produce a diagnostic if
5563/// the template parameter lists are not equivalent.
5564///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005565/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005566///
5567/// \param TemplateArgLoc If this source location is valid, then we
5568/// are actually checking the template parameter list of a template
5569/// argument (New) against the template parameter list of its
5570/// corresponding template template parameter (Old). We produce
5571/// slightly different diagnostics in this scenario.
5572///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005573/// \returns True if the template parameter lists are equal, false
5574/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005575bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005576Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5577 TemplateParameterList *Old,
5578 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005579 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005580 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005581 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5582 if (Complain)
5583 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5584 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005585
5586 return false;
5587 }
5588
Douglas Gregor641040a2011-01-12 23:45:44 +00005589 // C++0x [temp.arg.template]p3:
5590 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005591 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005592 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005593 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005594 // template-parameter-list of P. [...]
5595 TemplateParameterList::iterator NewParm = New->begin();
5596 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005597 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005598 OldParmEnd = Old->end();
5599 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005600 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5601 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005602 if (NewParm == NewParmEnd) {
5603 if (Complain)
5604 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5605 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005606
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005607 return false;
5608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005609
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005610 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5611 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005612 return false;
5613
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005614 ++NewParm;
5615 continue;
5616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005617
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005618 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005619 // [...] When P's template- parameter-list contains a template parameter
5620 // pack (14.5.3), the template parameter pack will match zero or more
5621 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005622 // template-parameter-list of A with the same type and form as the
5623 // template parameter pack in P (ignoring whether those template
5624 // parameters are template parameter packs).
5625 for (; NewParm != NewParmEnd; ++NewParm) {
5626 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5627 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005628 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005629 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005630 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005631
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005632 // Make sure we exhausted all of the arguments.
5633 if (NewParm != NewParmEnd) {
5634 if (Complain)
5635 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5636 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005637
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005638 return false;
5639 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005640
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005641 return true;
5642}
5643
5644/// \brief Check whether a template can be declared within this scope.
5645///
5646/// If the template declaration is valid in this scope, returns
5647/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005648bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005649Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005650 if (!S)
5651 return false;
5652
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005653 // Find the nearest enclosing declaration scope.
5654 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5655 (S->getFlags() & Scope::TemplateParamScope) != 0)
5656 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005657
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005658 // C++ [temp]p4:
5659 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005660 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005661 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005662 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005663 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005664
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005665 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005666 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005667
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005668 // C++ [temp]p2:
5669 // A template-declaration can appear only as a namespace scope or
5670 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005671 if (Ctx) {
5672 if (Ctx->isFileContext())
5673 return false;
5674 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5675 // C++ [temp.mem]p2:
5676 // A local class shall not have member templates.
5677 if (RD->isLocalClass())
5678 return Diag(TemplateParams->getTemplateLoc(),
5679 diag::err_template_inside_local_class)
5680 << TemplateParams->getSourceRange();
5681 else
5682 return false;
5683 }
5684 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005685
Mike Stump11289f42009-09-09 15:08:12 +00005686 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005687 diag::err_template_outside_namespace_or_class_scope)
5688 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005689}
Douglas Gregor67a65642009-02-17 23:15:12 +00005690
Douglas Gregor54888652009-10-07 00:13:32 +00005691/// \brief Determine what kind of template specialization the given declaration
5692/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005693static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005694 if (!D)
5695 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005696
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005697 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5698 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005699 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5700 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005701 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5702 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005703
Douglas Gregor54888652009-10-07 00:13:32 +00005704 return TSK_Undeclared;
5705}
5706
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005707/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005708/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005709///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005710/// This routine determines whether a template specialization can be declared
5711/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005712///
5713/// \param S the semantic analysis object for which this check is being
5714/// performed.
5715///
5716/// \param Specialized the entity being specialized or instantiated, which
5717/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005718/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005719/// member class).
5720///
5721/// \param PrevDecl the previous declaration of this entity, if any.
5722///
5723/// \param Loc the location of the explicit specialization or instantiation of
5724/// this entity.
5725///
5726/// \param IsPartialSpecialization whether this is a partial specialization of
5727/// a class template.
5728///
Douglas Gregor54888652009-10-07 00:13:32 +00005729/// \returns true if there was an error that we cannot recover from, false
5730/// otherwise.
5731static bool CheckTemplateSpecializationScope(Sema &S,
5732 NamedDecl *Specialized,
5733 NamedDecl *PrevDecl,
5734 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005735 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005736 // Keep these "kind" numbers in sync with the %select statements in the
5737 // various diagnostics emitted by this routine.
5738 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005739 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005740 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005741 else if (isa<VarTemplateDecl>(Specialized))
5742 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005743 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005744 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005745 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005746 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005747 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005748 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005749 else if (isa<RecordDecl>(Specialized))
5750 EntityKind = 7;
5751 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5752 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005753 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005754 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005755 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005756 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005757 return true;
5758 }
5759
Douglas Gregorf47b9112009-02-25 22:02:03 +00005760 // C++ [temp.expl.spec]p2:
5761 // An explicit specialization shall be declared in the namespace
5762 // of which the template is a member, or, for member templates, in
5763 // the namespace of which the enclosing class or enclosing class
5764 // template is a member. An explicit specialization of a member
5765 // function, member class or static data member of a class
5766 // template shall be declared in the namespace of which the class
5767 // template is a member. Such a declaration may also be a
5768 // definition. If the declaration is not a definition, the
5769 // specialization may be defined later in the name- space in which
5770 // the explicit specialization was declared, or in a namespace
5771 // that encloses the one in which the explicit specialization was
5772 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005773 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005774 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005775 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005776 return true;
5777 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005778
Douglas Gregor40fb7442009-10-07 17:30:37 +00005779 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005780 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005781 // Do not warn for class scope explicit specialization during
5782 // instantiation, warning was already emitted during pattern
5783 // semantic analysis.
5784 if (!S.ActiveTemplateInstantiations.size())
5785 S.Diag(Loc, diag::ext_function_specialization_in_class)
5786 << Specialized;
5787 } else {
5788 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5789 << Specialized;
5790 return true;
5791 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005792 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005793
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005794 if (S.CurContext->isRecord() &&
5795 !S.CurContext->Equals(Specialized->getDeclContext())) {
5796 // Make sure that we're specializing in the right record context.
5797 // Otherwise, things can go horribly wrong.
5798 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5799 << Specialized;
5800 return true;
5801 }
5802
Douglas Gregore4b05162009-10-07 17:21:34 +00005803 // C++ [temp.class.spec]p6:
5804 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005805 // in any namespace scope in which its definition may be defined (14.5.1
5806 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005807 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005808 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005809 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005810
5811 // Make sure that this redeclaration (or definition) occurs in an enclosing
5812 // namespace.
5813 // Note that HandleDeclarator() performs this check for explicit
5814 // specializations of function templates, static data members, and member
5815 // functions, so we skip the check here for those kinds of entities.
5816 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5817 // Should we refactor that check, so that it occurs later?
5818 if (!DC->Encloses(SpecializedContext) &&
5819 !(isa<FunctionTemplateDecl>(Specialized) ||
5820 isa<FunctionDecl>(Specialized) ||
5821 isa<VarTemplateDecl>(Specialized) ||
5822 isa<VarDecl>(Specialized))) {
5823 if (isa<TranslationUnitDecl>(SpecializedContext))
5824 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5825 << EntityKind << Specialized;
5826 else if (isa<NamespaceDecl>(SpecializedContext))
5827 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
5828 << EntityKind << Specialized
5829 << cast<NamedDecl>(SpecializedContext);
5830 else
5831 llvm_unreachable("unexpected namespace context for specialization");
5832
5833 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5834 } else if ((!PrevDecl ||
5835 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5836 getTemplateSpecializationKind(PrevDecl) ==
5837 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005838 // C++ [temp.exp.spec]p2:
5839 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005840 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005841 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005842 // An explicit specialization of a member function, member class or
5843 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005844 // namespace of which the class template is a member.
5845 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005846 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005847 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005848 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005849 // C++11 [temp.explicit]p3:
5850 // An explicit instantiation shall appear in an enclosing namespace of its
5851 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005852 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005853 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005854 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005855 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005856 "DC encloses TU but isn't in enclosing namespace set");
5857 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005858 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005859 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5860 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005861 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005862 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005863 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005864 Diag = diag::ext_template_spec_decl_out_of_scope;
5865 else
5866 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5867 S.Diag(Loc, Diag)
5868 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5869 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005870
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005871 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00005872 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00005873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005874
Douglas Gregorf47b9112009-02-25 22:02:03 +00005875 return false;
5876}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005877
Richard Smith6056d5e2014-02-09 00:54:43 +00005878static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5879 if (!E->isInstantiationDependent())
5880 return SourceLocation();
5881 DependencyChecker Checker(Depth);
5882 Checker.TraverseStmt(E);
5883 if (Checker.Match && Checker.MatchLoc.isInvalid())
5884 return E->getSourceRange();
5885 return Checker.MatchLoc;
5886}
5887
5888static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5889 if (!TL.getType()->isDependentType())
5890 return SourceLocation();
5891 DependencyChecker Checker(Depth);
5892 Checker.TraverseTypeLoc(TL);
5893 if (Checker.Match && Checker.MatchLoc.isInvalid())
5894 return TL.getSourceRange();
5895 return Checker.MatchLoc;
5896}
5897
Larisse Voufo39a1e502013-08-06 01:03:05 +00005898/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005899/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005900static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005901 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5902 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005903 for (unsigned I = 0; I != NumArgs; ++I) {
5904 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005905 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005906 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5907 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005908 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005909
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005910 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005911 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005912
Eli Friedmanb826a002012-09-26 02:36:12 +00005913 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005914 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00005915
5916 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005917
Douglas Gregor98318c22011-01-03 21:37:45 +00005918 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005919 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5920 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00005921
5922 // Strip off any implicit casts we added as part of type checking.
5923 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5924 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005925
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005926 // C++ [temp.class.spec]p8:
5927 // A non-type argument is non-specialized if it is the name of a
5928 // non-type parameter. All other non-type arguments are
5929 // specialized.
5930 //
5931 // Below, we check the two conditions that only apply to
5932 // specialized non-type arguments, so skip any non-specialized
5933 // arguments.
5934 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00005935 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005936 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005937
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005938 // C++ [temp.class.spec]p9:
5939 // Within the argument list of a class template partial
5940 // specialization, the following restrictions apply:
5941 // -- A partially specialized non-type argument expression
5942 // shall not involve a template parameter of the partial
5943 // specialization except when the argument expression is a
5944 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00005945 SourceRange ParamUseRange =
5946 findTemplateParameter(Param->getDepth(), ArgExpr);
5947 if (ParamUseRange.isValid()) {
5948 if (IsDefaultArgument) {
5949 S.Diag(TemplateNameLoc,
5950 diag::err_dependent_non_type_arg_in_partial_spec);
5951 S.Diag(ParamUseRange.getBegin(),
5952 diag::note_dependent_non_type_default_arg_in_partial_spec)
5953 << ParamUseRange;
5954 } else {
5955 S.Diag(ParamUseRange.getBegin(),
5956 diag::err_dependent_non_type_arg_in_partial_spec)
5957 << ParamUseRange;
5958 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005959 return true;
5960 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005961
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005962 // -- The type of a template parameter corresponding to a
5963 // specialized non-type argument shall not be dependent on a
5964 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00005965 //
5966 // FIXME: We need to delay this check until instantiation in some cases:
5967 //
5968 // template<template<typename> class X> struct A {
5969 // template<typename T, X<T> N> struct B;
5970 // template<typename T> struct B<T, 0>;
5971 // };
5972 // template<typename> using X = int;
5973 // A<X>::B<int, 0> b;
5974 ParamUseRange = findTemplateParameter(
5975 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
5976 if (ParamUseRange.isValid()) {
5977 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
5978 diag::err_dependent_typed_non_type_arg_in_partial_spec)
5979 << Param->getType() << ParamUseRange;
5980 S.Diag(Param->getLocation(), diag::note_template_param_here)
5981 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005982 return true;
5983 }
5984 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005985
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005986 return false;
5987}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005988
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005989/// \brief Check the non-type template arguments of a class template
5990/// partial specialization according to C++ [temp.class.spec]p9.
5991///
Richard Smith6056d5e2014-02-09 00:54:43 +00005992/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005993/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00005994/// template.
5995/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00005996/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00005997/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005998///
Richard Smith6056d5e2014-02-09 00:54:43 +00005999/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006000static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006001 Sema &S, SourceLocation TemplateNameLoc,
6002 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006003 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006004 const TemplateArgument *ArgList = TemplateArgs.data();
6005
6006 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6007 NonTypeTemplateParmDecl *Param
6008 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6009 if (!Param)
6010 continue;
6011
Richard Smith6056d5e2014-02-09 00:54:43 +00006012 if (CheckNonTypeTemplatePartialSpecializationArgs(
6013 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006014 return true;
6015 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006016
6017 return false;
6018}
6019
John McCall48871652010-08-21 09:40:31 +00006020DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006021Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6022 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006023 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006024 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006025 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006026 AttributeList *Attr,
6027 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006028 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006029
Richard Smith4b55a9c2014-04-17 03:29:33 +00006030 CXXScopeSpec &SS = TemplateId.SS;
6031
Abramo Bagnara60804e12011-03-18 15:16:37 +00006032 // NOTE: KWLoc is the location of the tag keyword. This will instead
6033 // store the location of the outermost template keyword in the declaration.
6034 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006035 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6036 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6037 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6038 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006039
Douglas Gregor67a65642009-02-17 23:15:12 +00006040 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006041 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006042 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006043 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6044
6045 if (!ClassTemplate) {
6046 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006047 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006048 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6049 return true;
6050 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006051
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006052 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006053 bool isPartialSpecialization = false;
6054
Douglas Gregorf47b9112009-02-25 22:02:03 +00006055 // Check the validity of the template headers that introduce this
6056 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006057 // FIXME: We probably shouldn't complain about these headers for
6058 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006059 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006060 TemplateParameterList *TemplateParams =
6061 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006062 KWLoc, TemplateNameLoc, SS, &TemplateId,
6063 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6064 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006065 if (Invalid)
6066 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006067
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006068 if (TemplateParams && TemplateParams->size() > 0) {
6069 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006070
Douglas Gregorec9518b2010-12-21 08:14:57 +00006071 if (TUK == TUK_Friend) {
6072 Diag(KWLoc, diag::err_partial_specialization_friend)
6073 << SourceRange(LAngleLoc, RAngleLoc);
6074 return true;
6075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006076
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006077 // C++ [temp.class.spec]p10:
6078 // The template parameter list of a specialization shall not
6079 // contain default template argument values.
6080 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6081 Decl *Param = TemplateParams->getParam(I);
6082 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6083 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006084 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006085 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006086 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006087 }
6088 } else if (NonTypeTemplateParmDecl *NTTP
6089 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6090 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006091 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006092 diag::err_default_arg_in_partial_spec)
6093 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006094 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006095 }
6096 } else {
6097 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006098 if (TTP->hasDefaultArgument()) {
6099 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006100 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006101 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006102 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006103 }
6104 }
6105 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006106 } else if (TemplateParams) {
6107 if (TUK == TUK_Friend)
6108 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006109 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006110 SourceRange(TemplateParams->getTemplateLoc(),
6111 TemplateParams->getRAngleLoc()))
6112 << SourceRange(LAngleLoc, RAngleLoc);
6113 else
6114 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006115 } else {
6116 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006117 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006118
Douglas Gregor67a65642009-02-17 23:15:12 +00006119 // Check that the specialization uses the same tag kind as the
6120 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006121 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6122 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006123 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006124 Kind, TUK == TUK_Definition, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00006125 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006126 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006127 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006128 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006129 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006130 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006131 diag::note_previous_use);
6132 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6133 }
6134
Douglas Gregorc40290e2009-03-09 23:48:35 +00006135 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006136 TemplateArgumentListInfo TemplateArgs =
6137 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006138
Douglas Gregor14406932011-01-03 20:35:03 +00006139 // Check for unexpanded parameter packs in any of the template arguments.
6140 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006141 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006142 UPPC_PartialSpecialization))
6143 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006144
Douglas Gregor67a65642009-02-17 23:15:12 +00006145 // Check that the template argument list is well-formed for this
6146 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006147 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006148 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6149 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006150 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006151
Douglas Gregor2373c592009-05-31 09:31:02 +00006152 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006153 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006154 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006155 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006156 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6157 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006158 return true;
6159
Douglas Gregor678d76c2011-07-01 01:22:09 +00006160 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006161 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006162 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006163 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006164 TemplateArgs.size(),
6165 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006166 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6167 << ClassTemplate->getDeclName();
6168 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006169 }
6170 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006171
Craig Topperc3ec1492014-05-26 06:22:03 +00006172 void *InsertPos = nullptr;
6173 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006174
6175 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006176 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006177 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006178 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006179 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006180
Craig Topperc3ec1492014-05-26 06:22:03 +00006181 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006182
Douglas Gregorf47b9112009-02-25 22:02:03 +00006183 // Check whether we can declare a class template specialization in
6184 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006185 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006186 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6187 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006188 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006189 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006190
Douglas Gregor15301382009-07-30 17:40:51 +00006191 // The canonical type
6192 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006193 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006194 // Build the canonical type that describes the converted template
6195 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006196 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6197 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006198 Converted.data(),
6199 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006200
6201 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006202 ClassTemplate->getInjectedClassNameSpecialization())) {
6203 // C++ [temp.class.spec]p9b3:
6204 //
6205 // -- The argument list of the specialization shall not be identical
6206 // to the implicit argument list of the primary template.
6207 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006208 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006209 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006210 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6211 ClassTemplate->getIdentifier(),
6212 TemplateNameLoc,
6213 Attr,
6214 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006215 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006216 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006217 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006218 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006219 }
Douglas Gregor15301382009-07-30 17:40:51 +00006220
Douglas Gregor2373c592009-05-31 09:31:02 +00006221 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006222 ClassTemplatePartialSpecializationDecl *PrevPartial
6223 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006224 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006225 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006226 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006227 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006228 TemplateParams,
6229 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006230 Converted.data(),
6231 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006232 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006233 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006234 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006235 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006236 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006237 Partial->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006238 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006239 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006240 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006241
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006242 if (!PrevPartial)
6243 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006244 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006245
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006246 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006247 // template specialization, make a note of that.
6248 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6249 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006250
Douglas Gregor91772d12009-06-13 00:26:55 +00006251 // Check that all of the template parameters of the class template
6252 // partial specialization are deducible from the template
6253 // arguments. If not, this class template partial specialization
6254 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006255 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006256 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006257 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006258 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006259
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006260 if (!DeducibleParams.all()) {
6261 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006262 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006263 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006264 << SourceRange(TemplateNameLoc, RAngleLoc);
6265 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6266 if (!DeducibleParams[I]) {
6267 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6268 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006269 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006270 diag::note_partial_spec_unused_parameter)
6271 << Param->getDeclName();
6272 else
Mike Stump11289f42009-09-09 15:08:12 +00006273 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006274 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006275 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006276 }
6277 }
6278 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006279 } else {
6280 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006281 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006282 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006283 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006284 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006285 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006286 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006287 Converted.data(),
6288 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006289 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006290 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006291 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006292 Specialization->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006293 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006294 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006295 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006296
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006297 if (!PrevDecl)
6298 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006299
6300 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006301 }
6302
Douglas Gregor06db9f52009-10-12 20:18:28 +00006303 // C++ [temp.expl.spec]p6:
6304 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006305 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006306 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006307 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006308 // use occurs; no diagnostic is required.
6309 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006310 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006311 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006312 // Is there any previous explicit specialization declaration?
6313 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6314 Okay = true;
6315 break;
6316 }
6317 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006318
Douglas Gregorc854c662010-02-26 06:03:23 +00006319 if (!Okay) {
6320 SourceRange Range(TemplateNameLoc, RAngleLoc);
6321 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6322 << Context.getTypeDeclType(Specialization) << Range;
6323
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006324 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006325 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006326 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006327 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006328 return true;
6329 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006330 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006331
Douglas Gregor2208a292009-09-26 20:57:03 +00006332 // If this is not a friend, note that this is an explicit specialization.
6333 if (TUK != TUK_Friend)
6334 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006335
6336 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006337 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00006338 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006339 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006340 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006341 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006342 Diag(Def->getLocation(), diag::note_previous_definition);
6343 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006344 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006345 }
6346 }
6347
John McCall659a3372010-12-18 03:30:47 +00006348 if (Attr)
6349 ProcessDeclAttributeList(S, Specialization, Attr);
6350
Richard Smith034b94a2012-08-17 03:20:55 +00006351 // Add alignment attributes if necessary; these attributes are checked when
6352 // the ASTContext lays out the structure.
6353 if (TUK == TUK_Definition) {
6354 AddAlignmentAttributesForRecord(Specialization);
6355 AddMsStructLayoutForRecord(Specialization);
6356 }
6357
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006358 if (ModulePrivateLoc.isValid())
6359 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6360 << (isPartialSpecialization? 1 : 0)
6361 << FixItHint::CreateRemoval(ModulePrivateLoc);
6362
Douglas Gregord56a91e2009-02-26 22:19:44 +00006363 // Build the fully-sugared type for this class template
6364 // specialization as the user wrote in the specialization
6365 // itself. This means that we'll pretty-print the type retrieved
6366 // from the specialization's declaration the way that the user
6367 // actually wrote the specialization, rather than formatting the
6368 // name based on the "canonical" representation used to store the
6369 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006370 TypeSourceInfo *WrittenTy
6371 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6372 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006373 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006374 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006375 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006376 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006377
Douglas Gregor1e249f82009-02-25 22:18:32 +00006378 // C++ [temp.expl.spec]p9:
6379 // A template explicit specialization is in the scope of the
6380 // namespace in which the template was defined.
6381 //
6382 // We actually implement this paragraph where we set the semantic
6383 // context (in the creation of the ClassTemplateSpecializationDecl),
6384 // but we also maintain the lexical context where the actual
6385 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006386 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006387
Douglas Gregor67a65642009-02-17 23:15:12 +00006388 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006389 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006390 Specialization->startDefinition();
6391
Douglas Gregor2208a292009-09-26 20:57:03 +00006392 if (TUK == TUK_Friend) {
6393 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6394 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006395 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006396 /*FIXME:*/KWLoc);
6397 Friend->setAccess(AS_public);
6398 CurContext->addDecl(Friend);
6399 } else {
6400 // Add the specialization into its lexical context, so that it can
6401 // be seen when iterating through the list of declarations in that
6402 // context. However, specializations are not found by name lookup.
6403 CurContext->addDecl(Specialization);
6404 }
John McCall48871652010-08-21 09:40:31 +00006405 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006406}
Douglas Gregor333489b2009-03-27 23:10:48 +00006407
John McCall48871652010-08-21 09:40:31 +00006408Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006409 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006410 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006411 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006412 ActOnDocumentableDecl(NewDecl);
6413 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006414}
6415
John McCall48871652010-08-21 09:40:31 +00006416Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00006417 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006418 Declarator &D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006419 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006420 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump11289f42009-09-09 15:08:12 +00006421
Douglas Gregor17a7c122009-06-24 00:54:41 +00006422 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00006423 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00006424 }
Mike Stump11289f42009-09-09 15:08:12 +00006425
Douglas Gregor17a7c122009-06-24 00:54:41 +00006426 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006427
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006428 D.setFunctionDefinitionKind(FDK_Definition);
John McCall48871652010-08-21 09:40:31 +00006429 Decl *DP = HandleDeclarator(ParentScope, D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006430 TemplateParameterLists);
Argyrios Kyrtzidis6fada2d2012-12-14 06:53:58 +00006431 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Douglas Gregor17a7c122009-06-24 00:54:41 +00006432}
6433
John McCall4f7ced62010-02-11 01:33:53 +00006434/// \brief Strips various properties off an implicit instantiation
6435/// that has just been explicitly specialized.
6436static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006437 D->dropAttr<DLLImportAttr>();
6438 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006439
Nico Webere4974382014-12-19 23:52:45 +00006440 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006441 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006442}
6443
Nico Webera8f80b32012-01-09 19:52:25 +00006444/// \brief Compute the diagnostic location for an explicit instantiation
6445// declaration or definition.
6446static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006447 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006448 // Explicit instantiations following a specialization have no effect and
6449 // hence no PointOfInstantiation. In that case, walk decl backwards
6450 // until a valid name loc is found.
6451 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006452 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6453 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006454 PrevDiagLoc = Prev->getLocation();
6455 }
6456 assert(PrevDiagLoc.isValid() &&
6457 "Explicit instantiation without point of instantiation?");
6458 return PrevDiagLoc;
6459}
6460
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006461/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006462/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006463/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006464/// new specialization/instantiation will have any effect.
6465///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006466/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006467/// instantiation.
6468///
6469/// \param NewTSK the kind of the new explicit specialization or instantiation.
6470///
6471/// \param PrevDecl the previous declaration of the entity.
6472///
6473/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6474///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006475/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006476/// declaration was instantiated (either implicitly or explicitly).
6477///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006478/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006479/// specialization or instantiation has no effect and should be ignored.
6480///
6481/// \returns true if there was an error that should prevent the introduction of
6482/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006483bool
6484Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6485 TemplateSpecializationKind NewTSK,
6486 NamedDecl *PrevDecl,
6487 TemplateSpecializationKind PrevTSK,
6488 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006489 bool &HasNoEffect) {
6490 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006491
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006492 switch (NewTSK) {
6493 case TSK_Undeclared:
6494 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006495 assert(
6496 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6497 "previous declaration must be implicit!");
6498 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006499
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006500 case TSK_ExplicitSpecialization:
6501 switch (PrevTSK) {
6502 case TSK_Undeclared:
6503 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006504 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006505 // explicitly specialized or has merely been mentioned without any
6506 // instantiation.
6507 return false;
6508
6509 case TSK_ImplicitInstantiation:
6510 if (PrevPointOfInstantiation.isInvalid()) {
6511 // The declaration itself has not actually been instantiated, so it is
6512 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006513 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006514 return false;
6515 }
6516 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006517
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006518 case TSK_ExplicitInstantiationDeclaration:
6519 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006520 assert((PrevTSK == TSK_ImplicitInstantiation ||
6521 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006522 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006523
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006524 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006525 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006526 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006527 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006528 // implicit instantiation to take place, in every translation unit in
6529 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006530 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006531 // Is there any previous explicit specialization declaration?
6532 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6533 return false;
6534 }
6535
Douglas Gregor1d957a32009-10-27 18:42:08 +00006536 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006537 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006538 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006539 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006540
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006541 return true;
6542 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006543
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006544 case TSK_ExplicitInstantiationDeclaration:
6545 switch (PrevTSK) {
6546 case TSK_ExplicitInstantiationDeclaration:
6547 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006548 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006549 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006550
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006551 case TSK_Undeclared:
6552 case TSK_ImplicitInstantiation:
6553 // We're explicitly instantiating something that may have already been
6554 // implicitly instantiated; that's fine.
6555 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006556
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006557 case TSK_ExplicitSpecialization:
6558 // C++0x [temp.explicit]p4:
6559 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006560 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006561 // specialization for that template, the explicit instantiation has no
6562 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006563 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006564 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006565
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006566 case TSK_ExplicitInstantiationDefinition:
6567 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006568 // If an entity is the subject of both an explicit instantiation
6569 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006570 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006571 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006572 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006573
6574 // Explicit instantiations following a specialization have no effect and
6575 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6576 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006577 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6578 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006579 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006580 return false;
6581 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006582
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006583 case TSK_ExplicitInstantiationDefinition:
6584 switch (PrevTSK) {
6585 case TSK_Undeclared:
6586 case TSK_ImplicitInstantiation:
6587 // We're explicitly instantiating something that may have already been
6588 // implicitly instantiated; that's fine.
6589 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006590
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006591 case TSK_ExplicitSpecialization:
6592 // C++ DR 259, C++0x [temp.explicit]p4:
6593 // For a given set of template parameters, if an explicit
6594 // instantiation of a template appears after a declaration of
6595 // an explicit specialization for that template, the explicit
6596 // instantiation has no effect.
6597 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006598 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006599 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006600 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006601 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006602 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6603 diag::ext_explicit_instantiation_after_specialization)
6604 << PrevDecl;
6605 Diag(PrevDecl->getLocation(),
6606 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006607 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006608 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006609
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006610 case TSK_ExplicitInstantiationDeclaration:
6611 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006612 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006613
6614 // C++0x [temp.explicit]p4:
6615 // For a given set of template parameters, if an explicit instantiation
6616 // of a template appears after a declaration of an explicit
6617 // specialization for that template, the explicit instantiation has no
6618 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006619 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006620 // Is there any previous explicit specialization declaration?
6621 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6622 HasNoEffect = true;
6623 break;
6624 }
6625 }
6626
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006627 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006628
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006629 case TSK_ExplicitInstantiationDefinition:
6630 // C++0x [temp.spec]p5:
6631 // For a given template and a given set of template-arguments,
6632 // - an explicit instantiation definition shall appear at most once
6633 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006634
6635 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6636 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006637 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006638 : diag::err_explicit_instantiation_duplicate)
6639 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006640 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006641 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006642 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006643 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006644 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006646
David Blaikie83d382b2011-09-23 05:06:16 +00006647 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006648}
6649
John McCallb9c78482010-04-08 09:05:18 +00006650/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006651/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006652///
James Dennettf14a6e52012-06-15 22:23:43 +00006653/// The only possible way to get a dependent function template specialization
6654/// is with a friend declaration, like so:
6655///
6656/// \code
6657/// template \<class T> void foo(T);
6658/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006659/// friend void foo<>(T);
6660/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006661/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006662///
6663/// There really isn't any useful analysis we can do here, so we
6664/// just store the information.
6665bool
6666Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6667 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6668 LookupResult &Previous) {
6669 // Remove anything from Previous that isn't a function template in
6670 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006671 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006672 LookupResult::Filter F = Previous.makeFilter();
6673 while (F.hasNext()) {
6674 NamedDecl *D = F.next()->getUnderlyingDecl();
6675 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006676 !FDLookupContext->InEnclosingNamespaceSetOf(
6677 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006678 F.erase();
6679 }
6680 F.done();
6681
6682 // Should this be diagnosed here?
6683 if (Previous.empty()) return true;
6684
6685 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6686 ExplicitTemplateArgs);
6687 return false;
6688}
6689
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006690/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006691/// specialization.
6692///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006693/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006694/// explicit function template specialization. On successful completion,
6695/// the function declaration \p FD will become a function template
6696/// specialization.
6697///
6698/// \param FD the function declaration, which will be updated to become a
6699/// function template specialization.
6700///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006701/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6702/// if any. Note that this may be valid info even when 0 arguments are
6703/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6704/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006705///
Francois Pichet3a44e432011-07-08 06:21:47 +00006706/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006707/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006708bool Sema::CheckFunctionTemplateSpecialization(
6709 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6710 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006711 // The set of function template specializations that could match this
6712 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006713 UnresolvedSet<8> Candidates;
Larisse Voufo98b20f12013-07-19 23:00:19 +00006714 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006715
Sebastian Redl50c68252010-08-31 00:36:30 +00006716 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006717 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6718 I != E; ++I) {
6719 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6720 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006721 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006722 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006723 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6724 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006725 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006726
Richard Smith574f4f62013-01-14 05:37:29 +00006727 // When matching a constexpr member function template specialization
6728 // against the primary template, we don't yet know whether the
6729 // specialization has an implicit 'const' (because we don't know whether
6730 // it will be a static member function until we know which template it
6731 // specializes), so adjust it now assuming it specializes this template.
6732 QualType FT = FD->getType();
6733 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006734 CXXMethodDecl *OldMD =
6735 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006736 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006737 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006738 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6739 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006740 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006741 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006742 }
6743 }
6744
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006745 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006746 // A trailing template-argument can be left unspecified in the
6747 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006748 // provided it can be deduced from the function argument type.
6749 // Perform template argument deduction to determine whether we may be
6750 // specializing this template.
6751 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006752 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006753 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006754 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6755 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6756 ExplicitTemplateArgs, FT, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006757 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006758 // that we can provide nifty diagnostics.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006759 FailedCandidates.addCandidate()
6760 .set(FunTmpl->getTemplatedDecl(),
6761 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006762 (void)TDK;
6763 continue;
6764 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006765
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006766 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00006767 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006768 }
6769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770
Douglas Gregor5de279c2009-09-26 03:41:46 +00006771 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006772 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006773 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006774 FD->getLocation(),
6775 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6776 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006777 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006778 PDiag(diag::note_function_template_spec_matched));
6779
John McCall58cc69d2010-01-27 01:50:18 +00006780 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006781 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006782
6783 // Ignore access information; it doesn't figure into redeclaration checking.
6784 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006785
6786 FunctionTemplateSpecializationInfo *SpecInfo
6787 = Specialization->getTemplateSpecializationInfo();
6788 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006789
6790 // Note: do not overwrite location info if previous template
6791 // specialization kind was explicit.
6792 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006793 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006794 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006795 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6796 // function can differ from the template declaration with respect to
6797 // the constexpr specifier.
6798 Specialization->setConstexpr(FD->isConstexpr());
6799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006800
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006801 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006802 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006803
6804 // If this is a friend declaration, then we're not really declaring
6805 // an explicit specialization.
6806 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006807
Douglas Gregor54888652009-10-07 00:13:32 +00006808 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006809 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006810 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006811 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006812 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006813 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006814 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006815
6816 // C++ [temp.expl.spec]p6:
6817 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006818 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006819 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006820 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006821 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006822 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006823 if (!isFriend &&
6824 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006825 TSK_ExplicitSpecialization,
6826 Specialization,
6827 SpecInfo->getTemplateSpecializationKind(),
6828 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006829 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006830 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006831
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006832 // Mark the prior declaration as an explicit specialization, so that later
6833 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006834 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00006835 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006836 MarkUnusedFileScopedDecl(Specialization);
6837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006838
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006839 // Turn the given function declaration into a function template
6840 // specialization, with the template arguments from the previous
6841 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006842 // Take copies of (semantic and syntactic) template argument lists.
6843 const TemplateArgumentList* TemplArgs = new (Context)
6844 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Douglas Gregord5058122010-02-11 01:19:42 +00006845 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006846 TemplArgs, /*InsertPos=*/nullptr,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006847 SpecInfo->getTemplateSpecializationKind(),
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00006848 ExplicitTemplateArgs);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006849
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006850 // The "previous declaration" for this function template specialization is
6851 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00006852 Previous.clear();
6853 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006854 return false;
6855}
6856
Douglas Gregor86d142a2009-10-08 07:24:58 +00006857/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006858/// specialization.
6859///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006860/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006861/// explicit member function specialization. On successful completion,
6862/// the function declaration \p FD will become a member function
6863/// specialization.
6864///
Douglas Gregor86d142a2009-10-08 07:24:58 +00006865/// \param Member the member declaration, which will be updated to become a
6866/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006867///
John McCall1f82f242009-11-18 22:49:29 +00006868/// \param Previous the set of declarations, one of which may be specialized
6869/// by this function specialization; the set will be modified to contain the
6870/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006871bool
John McCall1f82f242009-11-18 22:49:29 +00006872Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006873 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00006874
Douglas Gregor86d142a2009-10-08 07:24:58 +00006875 // Try to find the member we are instantiating.
Craig Topperc3ec1492014-05-26 06:22:03 +00006876 NamedDecl *Instantiation = nullptr;
6877 NamedDecl *InstantiatedFrom = nullptr;
6878 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006879
John McCall1f82f242009-11-18 22:49:29 +00006880 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006881 // Nowhere to look anyway.
6882 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006883 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6884 I != E; ++I) {
6885 NamedDecl *D = (*I)->getUnderlyingDecl();
6886 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00006887 QualType Adjusted = Function->getType();
6888 if (!hasExplicitCallingConv(Adjusted))
6889 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6890 if (Context.hasSameType(Adjusted, Method->getType())) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006891 Instantiation = Method;
6892 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006893 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006894 break;
6895 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006896 }
6897 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00006898 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006899 VarDecl *PrevVar;
6900 if (Previous.isSingleResult() &&
6901 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00006902 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00006903 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006904 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006905 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006906 }
6907 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006908 CXXRecordDecl *PrevRecord;
6909 if (Previous.isSingleResult() &&
6910 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6911 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006912 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006913 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006914 }
Richard Smith7d137e32012-03-23 03:33:32 +00006915 } else if (isa<EnumDecl>(Member)) {
6916 EnumDecl *PrevEnum;
6917 if (Previous.isSingleResult() &&
6918 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6919 Instantiation = PrevEnum;
6920 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6921 MSInfo = PrevEnum->getMemberSpecializationInfo();
6922 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006924
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006925 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006926 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006927 // specializations are always out-of-line, the caller will complain about
6928 // this mismatch later.
6929 return false;
6930 }
John McCalle820e5e2010-04-13 20:37:33 +00006931
6932 // If this is a friend, just bail out here before we start turning
6933 // things into explicit specializations.
6934 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6935 // Preserve instantiation information.
6936 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6937 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6938 cast<CXXMethodDecl>(InstantiatedFrom),
6939 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6940 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6941 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6942 cast<CXXRecordDecl>(InstantiatedFrom),
6943 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6944 }
6945
6946 Previous.clear();
6947 Previous.addDecl(Instantiation);
6948 return false;
6949 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006950
Douglas Gregor86d142a2009-10-08 07:24:58 +00006951 // Make sure that this is a specialization of a member.
6952 if (!InstantiatedFrom) {
6953 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6954 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006955 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6956 return true;
6957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006958
Douglas Gregor06db9f52009-10-12 20:18:28 +00006959 // C++ [temp.expl.spec]p6:
6960 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00006961 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006962 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006963 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006964 // use occurs; no diagnostic is required.
6965 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00006966
Abramo Bagnara8075c852010-06-12 07:44:57 +00006967 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00006968 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
6969 TSK_ExplicitSpecialization,
6970 Instantiation,
6971 MSInfo->getTemplateSpecializationKind(),
6972 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006973 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006974 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006975
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006976 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006977 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00006978 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006979 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006980 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006981 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00006982
Douglas Gregor86d142a2009-10-08 07:24:58 +00006983 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006984 // the original declaration to note that it is an explicit specialization
6985 // (if it was previously an implicit instantiation). This latter step
6986 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00006987 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006988 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
6989 if (InstantiationFunction->getTemplateSpecializationKind() ==
6990 TSK_ImplicitInstantiation) {
6991 InstantiationFunction->setTemplateSpecializationKind(
6992 TSK_ExplicitSpecialization);
6993 InstantiationFunction->setLocation(Member->getLocation());
6994 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006995
Douglas Gregor86d142a2009-10-08 07:24:58 +00006996 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
6997 cast<CXXMethodDecl>(InstantiatedFrom),
6998 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006999 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007000 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007001 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7002 if (InstantiationVar->getTemplateSpecializationKind() ==
7003 TSK_ImplicitInstantiation) {
7004 InstantiationVar->setTemplateSpecializationKind(
7005 TSK_ExplicitSpecialization);
7006 InstantiationVar->setLocation(Member->getLocation());
7007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007008
Larisse Voufo39a1e502013-08-06 01:03:05 +00007009 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7010 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007011 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007012 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007013 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7014 if (InstantiationClass->getTemplateSpecializationKind() ==
7015 TSK_ImplicitInstantiation) {
7016 InstantiationClass->setTemplateSpecializationKind(
7017 TSK_ExplicitSpecialization);
7018 InstantiationClass->setLocation(Member->getLocation());
7019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007020
Douglas Gregor86d142a2009-10-08 07:24:58 +00007021 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007022 cast<CXXRecordDecl>(InstantiatedFrom),
7023 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007024 } else {
7025 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7026 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7027 if (InstantiationEnum->getTemplateSpecializationKind() ==
7028 TSK_ImplicitInstantiation) {
7029 InstantiationEnum->setTemplateSpecializationKind(
7030 TSK_ExplicitSpecialization);
7031 InstantiationEnum->setLocation(Member->getLocation());
7032 }
7033
7034 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7035 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007036 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007037
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007038 // Save the caller the trouble of having to figure out which declaration
7039 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007040 Previous.clear();
7041 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007042 return false;
7043}
7044
Douglas Gregore47f5a72009-10-14 23:41:34 +00007045/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007046///
7047/// \returns true if a serious error occurs, false otherwise.
7048static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007049 SourceLocation InstLoc,
7050 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007051 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7052 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007053
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007054 if (CurContext->isRecord()) {
7055 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7056 << D;
7057 return true;
7058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007059
Richard Smith050d2612011-10-18 02:28:33 +00007060 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007061 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007062 // template. If the name declared in the explicit instantiation is an
7063 // unqualified name, the explicit instantiation shall appear in the
7064 // namespace where its template is declared or, if that namespace is inline
7065 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007066 //
7067 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007068 if (WasQualifiedName) {
7069 if (CurContext->Encloses(OrigContext))
7070 return false;
7071 } else {
7072 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7073 return false;
7074 }
7075
7076 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7077 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007078 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007079 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007080 diag::err_explicit_instantiation_out_of_scope :
7081 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007082 << D << NS;
7083 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007084 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007085 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007086 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7087 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7088 << D << NS;
7089 } else
7090 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007091 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007092 diag::err_explicit_instantiation_must_be_global :
7093 diag::warn_explicit_instantiation_must_be_global_0x)
7094 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007095 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007096 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007097}
7098
7099/// \brief Determine whether the given scope specifier has a template-id in it.
7100static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7101 if (!SS.isSet())
7102 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007103
Richard Smith050d2612011-10-18 02:28:33 +00007104 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007105 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007106 // or a static data member of a class template specialization, the name of
7107 // the class template specialization in the qualified-id for the member
7108 // name shall be a simple-template-id.
7109 //
7110 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007111 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7112 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007113 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007114 if (isa<TemplateSpecializationType>(T))
7115 return true;
7116
7117 return false;
7118}
7119
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007120// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007121DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007122Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007123 SourceLocation ExternLoc,
7124 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007125 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007126 SourceLocation KWLoc,
7127 const CXXScopeSpec &SS,
7128 TemplateTy TemplateD,
7129 SourceLocation TemplateNameLoc,
7130 SourceLocation LAngleLoc,
7131 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007132 SourceLocation RAngleLoc,
7133 AttributeList *Attr) {
7134 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007135 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007136 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007137 // Check that the specialization uses the same tag kind as the
7138 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007139 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7140 assert(Kind != TTK_Enum &&
7141 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007142
7143 if (isa<TypeAliasTemplateDecl>(TD)) {
7144 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7145 Diag(TD->getTemplatedDecl()->getLocation(),
7146 diag::note_previous_use);
7147 return true;
7148 }
7149
7150 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7151
Douglas Gregord9034f02009-05-14 16:41:31 +00007152 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007153 Kind, /*isDefinition*/false, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00007154 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007155 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007156 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007157 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007158 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007159 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007160 diag::note_previous_use);
7161 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7162 }
7163
Douglas Gregore47f5a72009-10-14 23:41:34 +00007164 // C++0x [temp.explicit]p2:
7165 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007166 // definition and an explicit instantiation declaration. An explicit
7167 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007168 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7169 ? TSK_ExplicitInstantiationDefinition
7170 : TSK_ExplicitInstantiationDeclaration;
7171
7172 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7173 // Check for dllexport class template instantiation declarations.
7174 for (AttributeList *A = Attr; A; A = A->getNext()) {
7175 if (A->getKind() == AttributeList::AT_DLLExport) {
7176 Diag(ExternLoc,
7177 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7178 Diag(A->getLoc(), diag::note_attribute);
7179 break;
7180 }
7181 }
7182
7183 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7184 Diag(ExternLoc,
7185 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7186 Diag(A->getLocation(), diag::note_attribute);
7187 }
7188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007189
Douglas Gregora1f49972009-05-13 00:25:59 +00007190 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007191 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007192 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007193
7194 // Check that the template argument list is well-formed for this
7195 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007196 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007197 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7198 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007199 return true;
7200
Douglas Gregora1f49972009-05-13 00:25:59 +00007201 // Find the class template specialization declaration that
7202 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007203 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007204 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007205 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007206
Abramo Bagnara8075c852010-06-12 07:44:57 +00007207 TemplateSpecializationKind PrevDecl_TSK
7208 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7209
Douglas Gregor54888652009-10-07 00:13:32 +00007210 // C++0x [temp.explicit]p2:
7211 // [...] An explicit instantiation shall appear in an enclosing
7212 // namespace of its template. [...]
7213 //
7214 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007215 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7216 SS.isSet()))
7217 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007218
Craig Topperc3ec1492014-05-26 06:22:03 +00007219 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007220
Abramo Bagnara8075c852010-06-12 07:44:57 +00007221 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007222 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007223 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007224 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007225 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007226 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007227 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007228
Abramo Bagnara8075c852010-06-12 07:44:57 +00007229 // Even though HasNoEffect == true means that this explicit instantiation
7230 // has no effect on semantics, we go on to put its syntax in the AST.
7231
7232 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7233 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007234 // Since the only prior class template specialization with these
7235 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007236 // declaration node as our own, updating the source location
7237 // for the template name to reflect our new declaration.
7238 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007239 Specialization = PrevDecl;
7240 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007241 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007242 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007243 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007244
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007245 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007246 // Create a new class template specialization declaration node for
7247 // this explicit specialization.
7248 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007249 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007250 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007251 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007252 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007253 Converted.data(),
7254 Converted.size(),
7255 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007256 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007257
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007258 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007259 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007260 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007261 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007262 }
7263
7264 // Build the fully-sugared type for this explicit instantiation as
7265 // the user wrote in the explicit instantiation itself. This means
7266 // that we'll pretty-print the type retrieved from the
7267 // specialization's declaration the way that the user actually wrote
7268 // the explicit instantiation, rather than formatting the name based
7269 // on the "canonical" representation used to store the template
7270 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007271 TypeSourceInfo *WrittenTy
7272 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7273 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007274 Context.getTypeDeclType(Specialization));
7275 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007276
Abramo Bagnara8075c852010-06-12 07:44:57 +00007277 // Set source locations for keywords.
7278 Specialization->setExternLoc(ExternLoc);
7279 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007280 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007281
Rafael Espindola0b062072012-01-03 06:04:21 +00007282 if (Attr)
7283 ProcessDeclAttributeList(S, Specialization, Attr);
7284
Abramo Bagnara8075c852010-06-12 07:44:57 +00007285 // Add the explicit instantiation into its lexical context. However,
7286 // since explicit instantiations are never found by name lookup, we
7287 // just put it into the declaration context directly.
7288 Specialization->setLexicalDeclContext(CurContext);
7289 CurContext->addDecl(Specialization);
7290
7291 // Syntax is now OK, so return if it has no other effect on semantics.
7292 if (HasNoEffect) {
7293 // Set the template specialization kind.
7294 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007295 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007296 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007297
7298 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007299 // A definition of a class template or class member template
7300 // shall be in scope at the point of the explicit instantiation of
7301 // the class template or class member template.
7302 //
7303 // This check comes when we actually try to perform the
7304 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007305 ClassTemplateSpecializationDecl *Def
7306 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007307 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007308 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007309 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007310 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007311 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007312 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7313 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007314
Douglas Gregor1d957a32009-10-27 18:42:08 +00007315 // Instantiate the members of this class template specialization.
7316 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007317 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007318 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007319 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7320
7321 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7322 // TSK_ExplicitInstantiationDefinition
7323 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7324 TSK == TSK_ExplicitInstantiationDefinition)
Richard Smitheb36ddf2014-04-24 22:45:46 +00007325 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007326 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007327
Douglas Gregor12e49d32009-10-15 22:53:21 +00007328 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007329 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007330
Abramo Bagnara8075c852010-06-12 07:44:57 +00007331 // Set the template specialization kind.
7332 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007333 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007334}
7335
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007336// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007337DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007338Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007339 SourceLocation ExternLoc,
7340 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007341 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007342 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007343 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007344 IdentifierInfo *Name,
7345 SourceLocation NameLoc,
7346 AttributeList *Attr) {
7347
Douglas Gregord6ab8742009-05-28 23:31:59 +00007348 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007349 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007350 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007351 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007352 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007353 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007354 SourceLocation(), false, TypeResult(),
7355 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007356 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7357
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007358 if (!TagD)
7359 return true;
7360
John McCall48871652010-08-21 09:40:31 +00007361 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007362 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007363
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007364 if (Tag->isInvalidDecl())
7365 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007366
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007367 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7368 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7369 if (!Pattern) {
7370 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7371 << Context.getTypeDeclType(Record);
7372 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7373 return true;
7374 }
7375
Douglas Gregore47f5a72009-10-14 23:41:34 +00007376 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007377 // If the explicit instantiation is for a class or member class, the
7378 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007379 // simple-template-id.
7380 //
7381 // C++98 has the same restriction, just worded differently.
7382 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007383 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007384 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007385
Douglas Gregore47f5a72009-10-14 23:41:34 +00007386 // C++0x [temp.explicit]p2:
7387 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007388 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007389 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007390 TemplateSpecializationKind TSK
7391 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7392 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007393
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007394 // C++0x [temp.explicit]p2:
7395 // [...] An explicit instantiation shall appear in an enclosing
7396 // namespace of its template. [...]
7397 //
7398 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007399 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007400
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007401 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007402 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007403 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007404 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007405 PrevDecl = Record;
7406 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007407 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007408 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007409 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007410 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007411 PrevDecl,
7412 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007413 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007414 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007415 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007416 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007417 return TagD;
7418 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007419
Douglas Gregor12e49d32009-10-15 22:53:21 +00007420 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007421 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007422 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007423 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007424 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007425 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007426 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007427 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007428 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007429 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7430 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007431 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7432 << Pattern;
7433 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007434 } else {
7435 if (InstantiateClass(NameLoc, Record, Def,
7436 getTemplateInstantiationArgs(Record),
7437 TSK))
7438 return true;
7439
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007440 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007441 if (!RecordDef)
7442 return true;
7443 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007444 }
7445
Douglas Gregor1d957a32009-10-27 18:42:08 +00007446 // Instantiate all of the members of the class.
7447 InstantiateClassMembers(NameLoc, RecordDef,
7448 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007449
Douglas Gregor88d292c2010-05-13 16:44:06 +00007450 if (TSK == TSK_ExplicitInstantiationDefinition)
7451 MarkVTableUsed(NameLoc, RecordDef, true);
7452
Mike Stump87c57ac2009-05-16 07:39:55 +00007453 // FIXME: We don't have any representation for explicit instantiations of
7454 // member classes. Such a representation is not needed for compilation, but it
7455 // should be available for clients that want to see all of the declarations in
7456 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007457 return TagD;
7458}
7459
John McCallfaf5fb42010-08-26 23:41:50 +00007460DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7461 SourceLocation ExternLoc,
7462 SourceLocation TemplateLoc,
7463 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007464 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007465 // TODO: check if/when DNInfo should replace Name.
7466 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7467 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007468 if (!Name) {
7469 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007470 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007471 diag::err_explicit_instantiation_requires_name)
7472 << D.getDeclSpec().getSourceRange()
7473 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007474
Douglas Gregor450f00842009-09-25 18:43:00 +00007475 return true;
7476 }
7477
7478 // The scope passed in may not be a decl scope. Zip up the scope tree until
7479 // we find one that is.
7480 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7481 (S->getFlags() & Scope::TemplateParamScope) != 0)
7482 S = S->getParent();
7483
7484 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007485 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7486 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007487 if (R.isNull())
7488 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007489
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007490 // C++ [dcl.stc]p1:
7491 // A storage-class-specifier shall not be specified in [...] an explicit
7492 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007493 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007494 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7495 << Name;
7496 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007497 } else if (D.getDeclSpec().getStorageClassSpec()
7498 != DeclSpec::SCS_unspecified) {
7499 // Complain about then remove the storage class specifier.
7500 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7501 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7502
7503 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007504 }
7505
Douglas Gregor3c74d412009-10-14 20:14:33 +00007506 // C++0x [temp.explicit]p1:
7507 // [...] An explicit instantiation of a function template shall not use the
7508 // inline or constexpr specifiers.
7509 // Presumably, this also applies to member functions of class templates as
7510 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007511 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007512 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007513 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007514 diag::err_explicit_instantiation_inline :
7515 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007516 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007517 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007518 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7519 // not already specified.
7520 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7521 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007522
Douglas Gregore47f5a72009-10-14 23:41:34 +00007523 // C++0x [temp.explicit]p2:
7524 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007525 // definition and an explicit instantiation declaration. An explicit
7526 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007527 TemplateSpecializationKind TSK
7528 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7529 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007530
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007531 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007532 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007533
7534 if (!R->isFunctionType()) {
7535 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007536 // A [...] static data member of a class template can be explicitly
7537 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007538 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007539 // C++1y [temp.explicit]p1:
7540 // A [...] variable [...] template specialization can be explicitly
7541 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007542 if (Previous.isAmbiguous())
7543 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007544
John McCall67c00872009-12-02 08:25:40 +00007545 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007546 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007547
Larisse Voufo39a1e502013-08-06 01:03:05 +00007548 if (!PrevTemplate) {
7549 if (!Prev || !Prev->isStaticDataMember()) {
7550 // We expect to see a data data member here.
7551 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7552 << Name;
7553 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7554 P != PEnd; ++P)
7555 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7556 return true;
7557 }
7558
7559 if (!Prev->getInstantiatedFromStaticDataMember()) {
7560 // FIXME: Check for explicit specialization?
7561 Diag(D.getIdentifierLoc(),
7562 diag::err_explicit_instantiation_data_member_not_instantiated)
7563 << Prev;
7564 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7565 // FIXME: Can we provide a note showing where this was declared?
7566 return true;
7567 }
7568 } else {
7569 // Explicitly instantiate a variable template.
7570
7571 // C++1y [dcl.spec.auto]p6:
7572 // ... A program that uses auto or decltype(auto) in a context not
7573 // explicitly allowed in this section is ill-formed.
7574 //
7575 // This includes auto-typed variable template instantiations.
7576 if (R->isUndeducedType()) {
7577 Diag(T->getTypeLoc().getLocStart(),
7578 diag::err_auto_not_allowed_var_inst);
7579 return true;
7580 }
7581
Richard Smithef985ac2013-09-18 02:10:12 +00007582 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7583 // C++1y [temp.explicit]p3:
7584 // If the explicit instantiation is for a variable, the unqualified-id
7585 // in the declaration shall be a template-id.
7586 Diag(D.getIdentifierLoc(),
7587 diag::err_explicit_instantiation_without_template_id)
7588 << PrevTemplate;
7589 Diag(PrevTemplate->getLocation(),
7590 diag::note_explicit_instantiation_here);
7591 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007592 }
7593
Richard Smithef985ac2013-09-18 02:10:12 +00007594 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007595 TemplateArgumentListInfo TemplateArgs =
7596 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007597
Larisse Voufo39a1e502013-08-06 01:03:05 +00007598 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7599 D.getIdentifierLoc(), TemplateArgs);
7600 if (Res.isInvalid())
7601 return true;
7602
7603 // Ignore access control bits, we don't need them for redeclaration
7604 // checking.
7605 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007607
Douglas Gregore47f5a72009-10-14 23:41:34 +00007608 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007609 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007610 // or a static data member of a class template specialization, the name of
7611 // the class template specialization in the qualified-id for the member
7612 // name shall be a simple-template-id.
7613 //
7614 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007615 //
Richard Smith5977d872013-09-18 21:55:14 +00007616 // This does not apply to variable template specializations, where the
7617 // template-id is in the unqualified-id instead.
7618 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007619 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007620 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007621 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007622
Douglas Gregore47f5a72009-10-14 23:41:34 +00007623 // Check the scope of this explicit instantiation.
7624 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007625
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007626 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007627 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7628 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007629 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007630 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007631 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007632 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007633
Larisse Voufo39a1e502013-08-06 01:03:05 +00007634 if (!HasNoEffect) {
7635 // Instantiate static data member or variable template.
7636
7637 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7638 if (PrevTemplate) {
7639 // Merge attributes.
7640 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7641 ProcessDeclAttributeList(S, Prev, Attr);
7642 }
7643 if (TSK == TSK_ExplicitInstantiationDefinition)
7644 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7645 }
7646
7647 // Check the new variable specialization against the parsed input.
7648 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7649 Diag(T->getTypeLoc().getLocStart(),
7650 diag::err_invalid_var_template_spec_type)
7651 << 0 << PrevTemplate << R << Prev->getType();
7652 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7653 << 2 << PrevTemplate->getDeclName();
7654 return true;
7655 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007656
Douglas Gregor450f00842009-09-25 18:43:00 +00007657 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007658 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007659 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007660
7661 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007662 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007663 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007664 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007665 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007666 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007667 HasExplicitTemplateArgs = true;
7668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007669
Douglas Gregor450f00842009-09-25 18:43:00 +00007670 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007671 // A [...] function [...] can be explicitly instantiated from its template.
7672 // A member function [...] of a class template can be explicitly
7673 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007674 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007675 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007676 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007677 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7678 P != PEnd; ++P) {
7679 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007680 if (!HasExplicitTemplateArgs) {
7681 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007682 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7683 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007684 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007685
John McCall58cc69d2010-01-27 01:50:18 +00007686 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007687 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7688 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007689 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007690 }
7691 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007692
Douglas Gregor450f00842009-09-25 18:43:00 +00007693 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7694 if (!FunTmpl)
7695 continue;
7696
Larisse Voufo98b20f12013-07-19 23:00:19 +00007697 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007698 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007699 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007700 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007701 (HasExplicitTemplateArgs ? &TemplateArgs
7702 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007703 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007704 // Keep track of almost-matches.
7705 FailedCandidates.addCandidate()
7706 .set(FunTmpl->getTemplatedDecl(),
7707 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007708 (void)TDK;
7709 continue;
7710 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007711
John McCall58cc69d2010-01-27 01:50:18 +00007712 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007714
Douglas Gregor450f00842009-09-25 18:43:00 +00007715 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007716 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007717 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007718 D.getIdentifierLoc(),
7719 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7720 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7721 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007722
John McCall58cc69d2010-01-27 01:50:18 +00007723 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007724 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007725
7726 // Ignore access control bits, we don't need them for redeclaration checking.
7727 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007728
Alexey Bataev73983912014-11-06 10:10:50 +00007729 // C++11 [except.spec]p4
7730 // In an explicit instantiation an exception-specification may be specified,
7731 // but is not required.
7732 // If an exception-specification is specified in an explicit instantiation
7733 // directive, it shall be compatible with the exception-specifications of
7734 // other declarations of that function.
7735 if (auto *FPT = R->getAs<FunctionProtoType>())
7736 if (FPT->hasExceptionSpec()) {
7737 unsigned DiagID =
7738 diag::err_mismatched_exception_spec_explicit_instantiation;
7739 if (getLangOpts().MicrosoftExt)
7740 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7741 bool Result = CheckEquivalentExceptionSpec(
7742 PDiag(DiagID) << Specialization->getType(),
7743 PDiag(diag::note_explicit_instantiation_here),
7744 Specialization->getType()->getAs<FunctionProtoType>(),
7745 Specialization->getLocation(), FPT, D.getLocStart());
7746 // In Microsoft mode, mismatching exception specifications just cause a
7747 // warning.
7748 if (!getLangOpts().MicrosoftExt && Result)
7749 return true;
7750 }
7751
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007752 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007753 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007754 diag::err_explicit_instantiation_member_function_not_instantiated)
7755 << Specialization
7756 << (Specialization->getTemplateSpecializationKind() ==
7757 TSK_ExplicitSpecialization);
7758 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7759 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007760 }
7761
Douglas Gregorec9fd132012-01-14 16:38:05 +00007762 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00007763 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7764 PrevDecl = Specialization;
7765
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007766 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007767 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007768 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007769 PrevDecl,
7770 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007771 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007772 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007773 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007774
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007775 // FIXME: We may still want to build some representation of this
7776 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007777 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00007778 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007779 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00007780
7781 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00007782 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7783 if (Attr)
7784 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007785
Richard Smitheb36ddf2014-04-24 22:45:46 +00007786 if (Specialization->isDefined()) {
7787 // Let the ASTConsumer know that this function has been explicitly
7788 // instantiated now, and its linkage might have changed.
7789 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7790 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00007791 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007792
Douglas Gregore47f5a72009-10-14 23:41:34 +00007793 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007794 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007795 // or a static data member of a class template specialization, the name of
7796 // the class template specialization in the qualified-id for the member
7797 // name shall be a simple-template-id.
7798 //
7799 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007800 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00007801 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007802 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00007803 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007804 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007805 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007806 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007807
Douglas Gregore47f5a72009-10-14 23:41:34 +00007808 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007809 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00007810 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007811 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00007812 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007813
Douglas Gregor450f00842009-09-25 18:43:00 +00007814 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00007815 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007816}
7817
John McCallfaf5fb42010-08-26 23:41:50 +00007818TypeResult
John McCall7f41d982009-09-11 04:59:25 +00007819Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7820 const CXXScopeSpec &SS, IdentifierInfo *Name,
7821 SourceLocation TagLoc, SourceLocation NameLoc) {
7822 // This has to hold, because SS is expected to be defined.
7823 assert(Name && "Expected a name in a dependent tag");
7824
Aaron Ballman4a979672014-01-03 13:56:08 +00007825 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00007826 if (!NNS)
7827 return true;
7828
Abramo Bagnara6150c882010-05-11 21:36:43 +00007829 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00007830
Douglas Gregorba41d012010-04-24 16:38:41 +00007831 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7832 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00007833 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00007834 return true;
7835 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00007836
Douglas Gregore7c20652011-03-02 00:47:37 +00007837 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007838 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00007839 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7840
7841 // Create type-source location information for this type.
7842 TypeLocBuilder TLB;
7843 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007844 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00007845 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7846 TL.setNameLoc(NameLoc);
7847 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00007848}
7849
John McCallfaf5fb42010-08-26 23:41:50 +00007850TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007851Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7852 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00007853 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007854 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00007855 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007856
Richard Smith0bf8a4922011-10-18 20:49:44 +00007857 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7858 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007859 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007860 diag::warn_cxx98_compat_typename_outside_of_template :
7861 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007862 << FixItHint::CreateRemoval(TypenameLoc);
7863
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007864 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00007865 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7866 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00007867 if (T.isNull())
7868 return true;
John McCall99b2fe52010-04-29 23:50:39 +00007869
7870 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7871 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00007872 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007873 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007874 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00007875 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007876 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00007877 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007878 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007879 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00007880 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007881 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007882
John McCallba7bf592010-08-24 05:47:05 +00007883 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00007884}
7885
John McCallfaf5fb42010-08-26 23:41:50 +00007886TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007887Sema::ActOnTypenameType(Scope *S,
7888 SourceLocation TypenameLoc,
7889 const CXXScopeSpec &SS,
7890 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00007891 TemplateTy TemplateIn,
7892 SourceLocation TemplateNameLoc,
7893 SourceLocation LAngleLoc,
7894 ASTTemplateArgsPtr TemplateArgsIn,
7895 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00007896 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7897 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007898 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007899 diag::warn_cxx98_compat_typename_outside_of_template :
7900 diag::ext_typename_outside_of_template)
7901 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007902
7903 // Translate the parser's template argument list in our AST format.
7904 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7905 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7906
7907 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007908 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7909 // Construct a dependent template specialization type.
7910 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00007911 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007912 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7913 DTN->getQualifier(),
7914 DTN->getIdentifier(),
7915 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007916
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007917 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00007918 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007919 DependentTemplateSpecializationTypeLoc SpecTL
7920 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007921 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7922 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00007923 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007924 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007925 SpecTL.setLAngleLoc(LAngleLoc);
7926 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007927 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7928 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007929 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00007930 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00007931
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007932 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7933 if (T.isNull())
7934 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00007935
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007936 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00007937 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007938 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007939 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007940 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7941 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007942 SpecTL.setLAngleLoc(LAngleLoc);
7943 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007944 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7945 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7946
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007947 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
7948 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007949 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007950 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7951
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007952 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
7953 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00007954}
7955
Douglas Gregorb09518c2011-02-27 22:46:49 +00007956
Richard Smith6f8d2c62012-05-09 05:17:00 +00007957/// Determine whether this failed name lookup should be treated as being
7958/// disabled by a usage of std::enable_if.
7959static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
7960 SourceRange &CondRange) {
7961 // We must be looking for a ::type...
7962 if (!II.isStr("type"))
7963 return false;
7964
7965 // ... within an explicitly-written template specialization...
7966 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
7967 return false;
7968 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007969 TemplateSpecializationTypeLoc EnableIfTSTLoc =
7970 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
7971 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00007972 return false;
7973 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00007974 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00007975
7976 // ... which names a complete class template declaration...
7977 const TemplateDecl *EnableIfDecl =
7978 EnableIfTST->getTemplateName().getAsTemplateDecl();
7979 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
7980 return false;
7981
7982 // ... called "enable_if".
7983 const IdentifierInfo *EnableIfII =
7984 EnableIfDecl->getDeclName().getAsIdentifierInfo();
7985 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
7986 return false;
7987
7988 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00007989 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00007990 return true;
7991}
7992
Douglas Gregor333489b2009-03-27 23:10:48 +00007993/// \brief Build the type that describes a C++ typename specifier,
7994/// e.g., "typename T::type".
7995QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007996Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
7997 SourceLocation KeywordLoc,
7998 NestedNameSpecifierLoc QualifierLoc,
7999 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008000 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008001 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008002 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008003
John McCall0b66eb32010-05-01 00:40:08 +00008004 DeclContext *Ctx = computeDeclContext(SS);
8005 if (!Ctx) {
8006 // If the nested-name-specifier is dependent and couldn't be
8007 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008008 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8009 return Context.getDependentNameType(Keyword,
8010 QualifierLoc.getNestedNameSpecifier(),
8011 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008012 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008013
John McCall0b66eb32010-05-01 00:40:08 +00008014 // If the nested-name-specifier refers to the current instantiation,
8015 // the "typename" keyword itself is superfluous. In C++03, the
8016 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8017 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008018 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008019
John McCall0b66eb32010-05-01 00:40:08 +00008020 if (RequireCompleteDeclContext(SS, Ctx))
8021 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008022
8023 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008024 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008025 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008026 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008027 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008028 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008029 case LookupResult::NotFound: {
8030 // If we're looking up 'type' within a template named 'enable_if', produce
8031 // a more specific diagnostic.
8032 SourceRange CondRange;
8033 if (isEnableIf(QualifierLoc, II, CondRange)) {
8034 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8035 << Ctx << CondRange;
8036 return QualType();
8037 }
8038
Douglas Gregore40876a2009-10-13 21:16:44 +00008039 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008040 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008041 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008042
8043 case LookupResult::FoundUnresolvedValue: {
8044 // We found a using declaration that is a value. Most likely, the using
8045 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008046 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008047 IILoc);
8048 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8049 << Name << Ctx << FullRange;
8050 if (UnresolvedUsingValueDecl *Using
8051 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008052 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008053 Diag(Loc, diag::note_using_value_decl_missing_typename)
8054 << FixItHint::CreateInsertion(Loc, "typename ");
8055 }
8056 }
8057 // Fall through to create a dependent typename type, from which we can recover
8058 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008059
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008060 case LookupResult::NotFoundInCurrentInstantiation:
8061 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008062 return Context.getDependentNameType(Keyword,
8063 QualifierLoc.getNestedNameSpecifier(),
8064 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008065
8066 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008067 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008068 // We found a type. Build an ElaboratedType, since the
8069 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008070 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008071 return Context.getElaboratedType(ETK_Typename,
8072 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008073 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008074 }
8075
8076 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008077 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008078 break;
8079
8080 case LookupResult::FoundOverloaded:
8081 DiagID = diag::err_typename_nested_not_type;
8082 Referenced = *Result.begin();
8083 break;
8084
John McCall6538c932009-10-10 05:48:19 +00008085 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008086 return QualType();
8087 }
8088
8089 // If we get here, it's because name lookup did not find a
8090 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008091 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008092 IILoc);
8093 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008094 if (Referenced)
8095 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8096 << Name;
8097 return QualType();
8098}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008099
8100namespace {
8101 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008102 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008103 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008104 SourceLocation Loc;
8105 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008106
Douglas Gregor15acfb92009-08-06 16:20:37 +00008107 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008108 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008109
Mike Stump11289f42009-09-09 15:08:12 +00008110 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008111 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008112 DeclarationName Entity)
8113 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008114 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008115
8116 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008117 /// transformed.
8118 ///
8119 /// For the purposes of type reconstruction, a type has already been
8120 /// transformed if it is NULL or if it is not dependent.
8121 bool AlreadyTransformed(QualType T) {
8122 return T.isNull() || !T->isDependentType();
8123 }
Mike Stump11289f42009-09-09 15:08:12 +00008124
8125 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008126 /// rebuilt.
8127 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008128
Douglas Gregor15acfb92009-08-06 16:20:37 +00008129 /// \brief Returns the name of the entity whose type is being rebuilt.
8130 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008131
Douglas Gregoref6ab412009-10-27 06:26:26 +00008132 /// \brief Sets the "base" location and entity when that
8133 /// information is known based on another transformation.
8134 void setBase(SourceLocation Loc, DeclarationName Entity) {
8135 this->Loc = Loc;
8136 this->Entity = Entity;
8137 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008138
8139 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8140 // Lambdas never need to be transformed.
8141 return E;
8142 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008143 };
8144}
8145
Douglas Gregor15acfb92009-08-06 16:20:37 +00008146/// \brief Rebuilds a type within the context of the current instantiation.
8147///
Mike Stump11289f42009-09-09 15:08:12 +00008148/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008149/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008150/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008151/// partial specialization thereof). This routine will rebuild that type now
8152/// that we have entered the declarator's scope, which may produce different
8153/// canonical types, e.g.,
8154///
8155/// \code
8156/// template<typename T>
8157/// struct X {
8158/// typedef T* pointer;
8159/// pointer data();
8160/// };
8161///
8162/// template<typename T>
8163/// typename X<T>::pointer X<T>::data() { ... }
8164/// \endcode
8165///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008166/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008167/// since we do not know that we can look into X<T> when we parsed the type.
8168/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008169/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008170/// as the canonical type of T*, allowing the return types of the out-of-line
8171/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008172TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8173 SourceLocation Loc,
8174 DeclarationName Name) {
8175 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008176 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008177
Douglas Gregor15acfb92009-08-06 16:20:37 +00008178 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8179 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008180}
Douglas Gregorbe999392009-09-15 16:23:51 +00008181
John McCalldadc5752010-08-24 06:29:42 +00008182ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008183 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8184 DeclarationName());
8185 return Rebuilder.TransformExpr(E);
8186}
8187
John McCall99b2fe52010-04-29 23:50:39 +00008188bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008189 if (SS.isInvalid())
8190 return true;
John McCall2408e322010-04-27 00:57:59 +00008191
Douglas Gregor10176412011-02-25 16:07:42 +00008192 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008193 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8194 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008195 NestedNameSpecifierLoc Rebuilt
8196 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8197 if (!Rebuilt)
8198 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008199
Douglas Gregor10176412011-02-25 16:07:42 +00008200 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008201 return false;
John McCall2408e322010-04-27 00:57:59 +00008202}
8203
Douglas Gregor041b0842011-10-14 15:31:12 +00008204/// \brief Rebuild the template parameters now that we know we're in a current
8205/// instantiation.
8206bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8207 TemplateParameterList *Params) {
8208 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8209 Decl *Param = Params->getParam(I);
8210
8211 // There is nothing to rebuild in a type parameter.
8212 if (isa<TemplateTypeParmDecl>(Param))
8213 continue;
8214
8215 // Rebuild the template parameter list of a template template parameter.
8216 if (TemplateTemplateParmDecl *TTP
8217 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8218 if (RebuildTemplateParamsInCurrentInstantiation(
8219 TTP->getTemplateParameters()))
8220 return true;
8221
8222 continue;
8223 }
8224
8225 // Rebuild the type of a non-type template parameter.
8226 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8227 TypeSourceInfo *NewTSI
8228 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8229 NTTP->getLocation(),
8230 NTTP->getDeclName());
8231 if (!NewTSI)
8232 return true;
8233
8234 if (NewTSI != NTTP->getTypeSourceInfo()) {
8235 NTTP->setTypeSourceInfo(NewTSI);
8236 NTTP->setType(NewTSI->getType());
8237 }
8238 }
8239
8240 return false;
8241}
8242
Douglas Gregorbe999392009-09-15 16:23:51 +00008243/// \brief Produces a formatted string that describes the binding of
8244/// template parameters to template arguments.
8245std::string
8246Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8247 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008248 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008249}
8250
8251std::string
8252Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8253 const TemplateArgument *Args,
8254 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008255 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008256 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008257
Douglas Gregore62e6a02009-11-11 19:13:48 +00008258 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008259 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008260
Douglas Gregorbe999392009-09-15 16:23:51 +00008261 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008262 if (I >= NumArgs)
8263 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008264
Douglas Gregorbe999392009-09-15 16:23:51 +00008265 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008266 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008267 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008268 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008269
Douglas Gregorbe999392009-09-15 16:23:51 +00008270 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008271 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008272 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008273 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008274 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008275
Douglas Gregor0192c232010-12-20 16:52:59 +00008276 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008277 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008278 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008279
8280 Out << ']';
8281 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008282}
Francois Pichet1c229c02011-04-22 22:18:13 +00008283
Richard Smithe40f2ba2013-08-07 21:41:30 +00008284void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8285 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008286 if (!FD)
8287 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008288
8289 LateParsedTemplate *LPT = new LateParsedTemplate;
8290
8291 // Take tokens to avoid allocations
8292 LPT->Toks.swap(Toks);
8293 LPT->D = FnD;
8294 LateParsedTemplateMap[FD] = LPT;
8295
8296 FD->setLateTemplateParsed(true);
8297}
8298
8299void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8300 if (!FD)
8301 return;
8302 FD->setLateTemplateParsed(false);
8303}
Francois Pichet1c229c02011-04-22 22:18:13 +00008304
8305bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8306 DeclContext *DC = CurContext;
8307
8308 while (DC) {
8309 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8310 const FunctionDecl *FD = RD->isLocalClass();
8311 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8312 } else if (DC->isTranslationUnit() || DC->isNamespace())
8313 return false;
8314
8315 DC = DC->getParent();
8316 }
8317 return false;
8318}