blob: dd2dfe4235a9f8a5be316eb9bc93d160f641ae47 [file] [log] [blame]
Eugene Zelenko1ced5092016-02-12 22:53:10 +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.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +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"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000021#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedTemplate.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000032#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000034#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000035
Eric Fiselier6ad68552016-07-01 01:24:09 +000036#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000037using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000039
John McCall9b72f892010-11-10 02:40:36 +000040// Exported for use by Parser.
41SourceRange
42clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 unsigned N) {
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46}
47
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000048namespace clang {
49/// \brief [temp.constr.decl]p2: A template's associated constraints are
50/// defined as a single constraint-expression derived from the introduced
51/// constraint-expressions [ ... ].
52///
53/// \param Params The template parameter list and optional requires-clause.
54///
55/// \param FD The underlying templated function declaration for a function
56/// template.
57static Expr *formAssociatedConstraints(TemplateParameterList *Params,
58 FunctionDecl *FD);
59}
60
61static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
62 FunctionDecl *FD) {
63 // FIXME: Concepts: collect additional introduced constraint-expressions
64 assert(!FD && "Cannot collect constraints from function declaration yet.");
65 return Params->getRequiresClause();
66}
67
Douglas Gregorb7bfe792009-09-02 22:59:36 +000068/// \brief Determine whether the declaration found is acceptable as the name
69/// of a template and, if so, return that template declaration. Otherwise,
70/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000071static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000072 NamedDecl *Orig,
73 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000074 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000076 if (isa<TemplateDecl>(D)) {
77 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000078 return nullptr;
79
John McCalle9cccd82010-06-16 08:42:20 +000080 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000081 }
Mike Stump11289f42009-09-09 15:08:12 +000082
Douglas Gregorb7bfe792009-09-02 22:59:36 +000083 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
84 // C++ [temp.local]p1:
85 // Like normal (non-template) classes, class templates have an
86 // injected-class-name (Clause 9). The injected-class-name
87 // can be used with or without a template-argument-list. When
88 // it is used without a template-argument-list, it is
89 // equivalent to the injected-class-name followed by the
90 // template-parameters of the class template enclosed in
91 // <>. When it is used with a template-argument-list, it
92 // refers to the specified class template specialization,
93 // which could be the current specialization or another
94 // specialization.
95 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000096 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000097 if (Record->getDescribedClassTemplate())
98 return Record->getDescribedClassTemplate();
99
100 if (ClassTemplateSpecializationDecl *Spec
101 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
102 return Spec->getSpecializedTemplate();
103 }
Mike Stump11289f42009-09-09 15:08:12 +0000104
Craig Topperc3ec1492014-05-26 06:22:03 +0000105 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106 }
Mike Stump11289f42009-09-09 15:08:12 +0000107
Craig Topperc3ec1492014-05-26 06:22:03 +0000108 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000109}
110
Simon Pilgrim6905d222016-12-30 22:55:33 +0000111void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000112 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000113 // The set of class templates we've already seen.
114 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +0000115 LookupResult::Filter filter = R.makeFilter();
116 while (filter.hasNext()) {
117 NamedDecl *Orig = filter.next();
Simon Pilgrim6905d222016-12-30 22:55:33 +0000118 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000119 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +0000120 if (!Repl)
121 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000122 else if (Repl != Orig) {
123
124 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000125 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000126 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000127 // one base class). If all of the injected-class-names that are found
128 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000129 // is used as a template-name, the reference refers to the class
130 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000131 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000132 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000133 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000134 filter.erase();
135 continue;
136 }
John McCallbd8062d2010-08-13 07:02:08 +0000137
138 // FIXME: we promote access to public here as a workaround to
139 // the fact that LookupResult doesn't let us remember that we
140 // found this template through a particular injected class name,
141 // which means we end up doing nasty things to the invariants.
142 // Pretending that access is public is *much* safer.
143 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000144 }
John McCalle66edc12009-11-24 19:00:30 +0000145 }
146 filter.done();
147}
148
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000149bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
150 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000151 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000152 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000153 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +0000154
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000155 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000156}
157
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000159 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000160 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000161 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000162 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000163 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000164 TemplateTy &TemplateResult,
165 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000166 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000167
Douglas Gregor3cf81312009-11-03 23:16:33 +0000168 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000169 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000170
Douglas Gregor3cf81312009-11-03 23:16:33 +0000171 switch (Name.getKind()) {
172 case UnqualifiedId::IK_Identifier:
173 TName = DeclarationName(Name.Identifier);
174 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000175
Douglas Gregor3cf81312009-11-03 23:16:33 +0000176 case UnqualifiedId::IK_OperatorFunctionId:
177 TName = Context.DeclarationNames.getCXXOperatorName(
178 Name.OperatorFunctionId.Operator);
179 break;
180
Alexis Hunted0530f2009-11-28 08:58:14 +0000181 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000182 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
183 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000184
Douglas Gregor3cf81312009-11-03 23:16:33 +0000185 default:
186 return TNK_Non_template;
187 }
Mike Stump11289f42009-09-09 15:08:12 +0000188
John McCallba7bf592010-08-24 05:47:05 +0000189 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000190
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000191 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000192 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
193 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000194 if (R.empty()) return TNK_Non_template;
195 if (R.isAmbiguous()) {
196 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000197 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000198
199 // FIXME: we might have ambiguous templates, in which case we
200 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000201 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000202 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000203
John McCalld28ae272009-12-02 08:04:21 +0000204 TemplateName Template;
205 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000206
John McCalld28ae272009-12-02 08:04:21 +0000207 unsigned ResultCount = R.end() - R.begin();
208 if (ResultCount > 1) {
209 // We assume that we'll preserve the qualifier from a function
210 // template name in other ways.
211 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
212 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000213
214 // We'll do this lookup again later.
215 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000216 } else {
John McCalld28ae272009-12-02 08:04:21 +0000217 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
218
219 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000220 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000221 Template = Context.getQualifiedTemplateName(Qualifier,
222 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000223 } else {
224 Template = TemplateName(TD);
225 }
226
John McCalldcc71402010-08-13 02:23:42 +0000227 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000228 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000229
230 // We'll do this lookup again later.
231 R.suppressDiagnostics();
232 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000233 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000234 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
235 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000236 TemplateKind =
237 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000238 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000239 }
Mike Stump11289f42009-09-09 15:08:12 +0000240
John McCalld28ae272009-12-02 08:04:21 +0000241 TemplateResult = TemplateTy::make(Template);
242 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000243}
244
Richard Smith278890f2017-02-10 20:39:58 +0000245bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
246 SourceLocation NameLoc,
247 ParsedTemplateTy *Template) {
248 CXXScopeSpec SS;
249 bool MemberOfUnknownSpecialization = false;
250
251 // We could use redeclaration lookup here, but we don't need to: the
252 // syntactic form of a deduction guide is enough to identify it even
253 // if we can't look up the template name at all.
254 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
255 LookupTemplateName(R, S, SS, /*ObjectType*/QualType(),
256 /*EnteringContext*/false, MemberOfUnknownSpecialization);
257
258 if (R.empty()) return false;
259 if (R.isAmbiguous()) {
260 // FIXME: Diagnose an ambiguity if we find at least one template.
261 R.suppressDiagnostics();
262 return false;
263 }
264
265 // We only treat template-names that name type templates as valid deduction
266 // guide names.
267 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
268 if (!TD || !getAsTypeTemplateDecl(TD))
269 return false;
270
271 if (Template)
272 *Template = TemplateTy::make(TemplateName(TD));
273 return true;
274}
275
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000277 SourceLocation IILoc,
278 Scope *S,
279 const CXXScopeSpec *SS,
280 TemplateTy &SuggestedTemplate,
281 TemplateNameKind &SuggestedKind) {
282 // We can't recover unless there's a dependent scope specifier preceding the
283 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000284 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000285 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
286 computeDeclContext(*SS))
287 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000288
Douglas Gregor18473f32010-01-12 21:28:44 +0000289 // The code is missing a 'template' keyword prior to the dependent template
290 // name.
291 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
292 Diag(IILoc, diag::err_template_kw_missing)
293 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000294 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000295 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000296 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
297 SuggestedKind = TNK_Dependent_template_name;
298 return true;
299}
300
John McCalle66edc12009-11-24 19:00:30 +0000301void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000302 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000303 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000304 bool EnteringContext,
305 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000306 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000307 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000308 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000309 bool isDependent = false;
310 if (!ObjectType.isNull()) {
311 // This nested-name-specifier occurs in a member access expression, e.g.,
312 // x->B::f, and we are looking into the type of the object.
313 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
314 LookupCtx = computeDeclContext(ObjectType);
315 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000316 assert((isDependent || !ObjectType->isIncompleteType() ||
317 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000318 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000319
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000320 // Template names cannot appear inside an Objective-C class or object type.
321 if (ObjectType->isObjCObjectOrInterfaceType()) {
322 Found.clear();
323 return;
324 }
John McCalle66edc12009-11-24 19:00:30 +0000325 } else if (SS.isSet()) {
326 // This nested-name-specifier occurs after another nested-name-specifier,
327 // so long into the context associated with the prior nested-name-specifier.
328 LookupCtx = computeDeclContext(SS, EnteringContext);
329 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000330
John McCalle66edc12009-11-24 19:00:30 +0000331 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000332 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000333 return;
334 }
335
336 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000337 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000338 if (LookupCtx) {
339 // Perform "qualified" name lookup into the declaration context we
340 // computed, which is either the type of the base of a member access
341 // expression or the declaration context associated with a prior
342 // nested-name-specifier.
343 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000344 if (!ObjectType.isNull() && Found.empty()) {
345 // C++ [basic.lookup.classref]p1:
346 // In a class member access expression (5.2.5), if the . or -> token is
347 // immediately followed by an identifier followed by a <, the
348 // identifier must be looked up to determine whether the < is the
349 // beginning of a template argument list (14.2) or a less-than operator.
350 // The identifier is first looked up in the class of the object
351 // expression. If the identifier is not found, it is then looked up in
352 // the context of the entire postfix-expression and shall name a class
353 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000354 if (S) LookupName(Found, S);
355 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000356 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000357 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000358 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000359 // We cannot look into a dependent object type or nested nme
360 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000361 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000362 return;
363 } else {
364 // Perform unqualified name lookup in the current scope.
365 LookupName(Found, S);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000366
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000367 if (!ObjectType.isNull())
368 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000369 }
370
Douglas Gregorc119dd52010-01-12 17:06:20 +0000371 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000372 // If we did not find any names, attempt to correct any typos.
373 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000374 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000375 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000376 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
377 FilterCCC->WantTypeSpecifiers = false;
378 FilterCCC->WantExpressionKeywords = false;
379 FilterCCC->WantRemainingKeywords = false;
380 FilterCCC->WantCXXNamedCasts = true;
381 if (TypoCorrection Corrected = CorrectTypo(
382 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
383 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000384 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000385 if (auto *ND = Corrected.getFoundDecl())
386 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000387 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000388 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000389 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000390 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
391 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000392 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000393 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
394 << Name << LookupCtx << DroppedSpecifier
395 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000396 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000397 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000398 }
John McCalle9cccd82010-06-16 08:42:20 +0000399 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000400 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000401 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000402 }
403 }
404
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000405 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000406 if (Found.empty()) {
407 if (isDependent)
408 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000409 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000410 }
John McCalle66edc12009-11-24 19:00:30 +0000411
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000412 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000413 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000414 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000415 // [...] If the lookup in the class of the object expression finds a
416 // template, the name is also looked up in the context of the entire
417 // postfix-expression and [...]
418 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000419 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000420 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
421 LookupOrdinaryName);
422 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000423 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000424
John McCalle66edc12009-11-24 19:00:30 +0000425 if (FoundOuter.empty()) {
426 // - if the name is not found, the name found in the class of the
427 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000428 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
429 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000430 // - if the name is found in the context of the entire
431 // postfix-expression and does not name a class template, the name
432 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000433 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000434 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000435 // - if the name found is a class template, it must refer to the same
436 // entity as the one found in the class of the object expression,
437 // otherwise the program is ill-formed.
438 if (!Found.isSingleResult() ||
439 Found.getFoundDecl()->getCanonicalDecl()
440 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000442 diag::ext_nested_name_member_ref_lookup_ambiguous)
443 << Found.getLookupName()
444 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000445 Diag(Found.getRepresentativeDecl()->getLocation(),
446 diag::note_ambig_member_ref_object_type)
447 << ObjectType;
448 Diag(FoundOuter.getFoundDecl()->getLocation(),
449 diag::note_ambig_member_ref_scope);
450
451 // Recover by taking the template that we found in the object
452 // expression's type.
453 }
454 }
455 }
456}
457
John McCallcd4b4772009-12-02 03:53:29 +0000458/// ActOnDependentIdExpression - Handle a dependent id-expression that
459/// was just parsed. This is only possible with an explicit scope
460/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000461ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000462Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000463 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000464 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000465 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000466 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000467 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000468
Reid Kleckner1af391df2016-03-11 18:59:12 +0000469 // C++11 [expr.prim.general]p12:
470 // An id-expression that denotes a non-static data member or non-static
471 // member function of a class can only be used:
472 // (...)
473 // - if that id-expression denotes a non-static data member and it
474 // appears in an unevaluated operand.
475 //
476 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
477 // CXXDependentScopeMemberExpr. The former can instantiate to either
478 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
479 // always a MemberExpr.
480 bool MightBeCxx11UnevalField =
481 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
482
Akira Hatanakad644e022016-12-16 03:19:41 +0000483 // Check if the nested name specifier is an enum type.
484 bool IsEnum = false;
485 if (NestedNameSpecifier *NNS = SS.getScopeRep())
486 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
487
488 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000489 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000490 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000491
John McCalle66edc12009-11-24 19:00:30 +0000492 // Since the 'this' expression is synthesized, we don't need to
493 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000494 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000495
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000496 return CXXDependentScopeMemberExpr::Create(
497 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
498 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
499 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000500 }
501
Abramo Bagnara7945c982012-01-27 09:46:47 +0000502 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000503}
504
John McCalldadc5752010-08-24 06:29:42 +0000505ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000506Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000507 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000508 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000509 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000510 return DependentScopeDeclRefExpr::Create(
511 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
512 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000513}
514
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000515
516/// Determine whether we would be unable to instantiate this template (because
517/// it either has no definition, or is in the process of being instantiated).
518bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
519 NamedDecl *Instantiation,
520 bool InstantiatedFromMember,
521 const NamedDecl *Pattern,
522 const NamedDecl *PatternDef,
523 TemplateSpecializationKind TSK,
524 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000525 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
526 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000527
Richard Smithedbc6e92016-10-14 21:41:24 +0000528 bool IsEntityBeingDefined = false;
529 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
530 IsEntityBeingDefined = TD->isBeingDefined();
531
532 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000533 NamedDecl *SuggestedDef = nullptr;
534 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
535 /*OnlyNeedComplete*/false)) {
536 // If we're allowed to diagnose this and recover, do so.
537 bool Recover = Complain && !isSFINAEContext();
538 if (Complain)
539 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
540 Sema::MissingImportKind::Definition, Recover);
541 return !Recover;
542 }
543 return false;
544 }
545
Richard Smith6f4e2e02016-08-23 19:41:39 +0000546 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
547 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000548
Richard Smithedbc6e92016-10-14 21:41:24 +0000549 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000550 QualType InstantiationTy;
551 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
552 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000553 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000554 Diag(PointOfInstantiation,
555 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000556 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000557 << InstantiationTy;
558 // Not much point in noting the template declaration here, since
559 // we're lexically inside it.
560 Instantiation->setInvalidDecl();
561 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000562 if (isa<FunctionDecl>(Instantiation)) {
563 Diag(PointOfInstantiation,
564 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000565 << /*member function*/ 1 << Instantiation->getDeclName()
566 << Instantiation->getDeclContext();
567 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000568 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000569 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000570 Diag(PointOfInstantiation,
571 diag::err_implicit_instantiate_member_undefined)
572 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000573 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000574 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000575 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000576 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000577 Diag(PointOfInstantiation,
578 diag::err_explicit_instantiation_undefined_func_template)
579 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000580 Note = diag::note_explicit_instantiation_here;
581 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000582 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
583 << (TSK != TSK_ImplicitInstantiation)
584 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000585 Note = diag::note_template_decl_here;
586 } else {
587 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
588 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
589 Diag(PointOfInstantiation,
590 diag::err_explicit_instantiation_undefined_var_template)
591 << Instantiation;
592 Instantiation->setInvalidDecl();
593 } else
594 Diag(PointOfInstantiation,
595 diag::err_explicit_instantiation_undefined_member)
596 << /*static data member*/ 2 << Instantiation->getDeclName()
597 << Instantiation->getDeclContext();
598 Note = diag::note_explicit_instantiation_here;
599 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000600 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000601 if (Note) // Diagnostics were emitted.
602 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000603
604 // In general, Instantiation isn't marked invalid to get more than one
605 // error for multiple undefined instantiations. But the code that does
606 // explicit declaration -> explicit definition conversion can't handle
607 // invalid declarations, so mark as invalid in that case.
608 if (TSK == TSK_ExplicitInstantiationDeclaration)
609 Instantiation->setInvalidDecl();
610 return true;
611}
612
Douglas Gregor5101c242008-12-05 18:15:24 +0000613/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
614/// that the template parameter 'PrevDecl' is being shadowed by a new
615/// declaration at location Loc. Returns true to indicate that this is
616/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000617void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000618 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000619
620 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000621 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000622 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000623
624 // C++ [temp.local]p4:
625 // A template-parameter shall not be redeclared within its
626 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000627 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000628 << cast<NamedDecl>(PrevDecl)->getDeclName();
629 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000630}
631
Douglas Gregor463421d2009-03-03 04:44:36 +0000632/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000633/// the parameter D to reference the templated declaration and return a pointer
634/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000635TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
636 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
637 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000638 return Temp;
639 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000640 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000641}
642
Douglas Gregoreb29d182011-01-05 17:40:24 +0000643ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
644 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000646 "Only template template arguments can be pack expansions here");
647 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
648 "Template template argument pack expansion without packs");
649 ParsedTemplateArgument Result(*this);
650 Result.EllipsisLoc = EllipsisLoc;
651 return Result;
652}
653
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000654static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
655 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000657 switch (Arg.getKind()) {
658 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000659 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000660 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000662 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000663 return TemplateArgumentLoc(TemplateArgument(T), DI);
664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000666 case ParsedTemplateArgument::NonType: {
667 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
668 return TemplateArgumentLoc(TemplateArgument(E), E);
669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000671 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000672 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000673 TemplateArgument TArg;
674 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000675 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000676 else
677 TArg = Template;
678 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000679 Arg.getScopeSpec().getWithLocInContext(
680 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000681 Arg.getLocation(),
682 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000683 }
684 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000686 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000687}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000689/// \brief Translates template arguments as provided by the parser
690/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000691void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
692 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000693 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000694 TemplateArgs.addArgument(translateTemplateArgument(*this,
695 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000696}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Richard Smithb80d5402013-06-25 22:21:36 +0000698static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
699 SourceLocation Loc,
700 IdentifierInfo *Name) {
701 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
702 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
703 if (PrevDecl && PrevDecl->isTemplateParameter())
704 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
705}
706
Douglas Gregor5101c242008-12-05 18:15:24 +0000707/// ActOnTypeParameter - Called when a C++ template type parameter
708/// (e.g., "typename T") has been parsed. Typename specifies whether
709/// the keyword "typename" was used to declare the type parameter
710/// (otherwise, "class" was used), and KeyLoc is the location of the
711/// "class" or "typename" keyword. ParamName is the name of the
712/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000713/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000714/// If the type parameter has a default argument, it will be added
715/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000716Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000717 SourceLocation EllipsisLoc,
718 SourceLocation KeyLoc,
719 IdentifierInfo *ParamName,
720 SourceLocation ParamNameLoc,
721 unsigned Depth, unsigned Position,
722 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000723 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000724 assert(S->isTemplateParamScope() &&
725 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000726
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000727 SourceLocation Loc = ParamNameLoc;
728 if (!ParamName)
729 Loc = KeyLoc;
730
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000731 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000732 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000733 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000734 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000735 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000736 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000737
738 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000739 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
740
Douglas Gregor5101c242008-12-05 18:15:24 +0000741 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000742 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000743 IdResolver.AddDecl(Param);
744 }
745
Douglas Gregorf5500772011-01-05 15:48:55 +0000746 // C++0x [temp.param]p9:
747 // A default template-argument may be specified for any kind of
748 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000749 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000750 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000751 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000752 }
753
Douglas Gregordc13ded2010-07-01 00:00:45 +0000754 // Handle the default argument, if provided.
755 if (DefaultArg) {
756 TypeSourceInfo *DefaultTInfo;
757 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000758
Douglas Gregordc13ded2010-07-01 00:00:45 +0000759 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000760
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000761 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000763 UPPC_DefaultArgument))
764 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000765
Douglas Gregordc13ded2010-07-01 00:00:45 +0000766 // Check the template argument itself.
767 if (CheckTemplateArgument(Param, DefaultTInfo)) {
768 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000769 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000771
Richard Smith1469b912015-06-10 00:29:03 +0000772 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774
John McCall48871652010-08-21 09:40:31 +0000775 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000776}
777
Douglas Gregor463421d2009-03-03 04:44:36 +0000778/// \brief Check that the type of a non-type template parameter is
779/// well-formed.
780///
781/// \returns the (possibly-promoted) parameter type if valid;
782/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000783QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
784 SourceLocation Loc) {
785 if (TSI->getType()->isUndeducedType()) {
786 // C++1z [temp.dep.expr]p3:
787 // An id-expression is type-dependent if it contains
788 // - an identifier associated by name lookup with a non-type
789 // template-parameter declared with a type that contains a
790 // placeholder type (7.1.7.4),
791 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
792 }
793
794 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
795}
796
797QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
798 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000799 // We don't allow variably-modified types as the type of non-type template
800 // parameters.
801 if (T->isVariablyModifiedType()) {
802 Diag(Loc, diag::err_variably_modified_nontype_template_param)
803 << T;
804 return QualType();
805 }
806
Douglas Gregor463421d2009-03-03 04:44:36 +0000807 // C++ [temp.param]p4:
808 //
809 // A non-type template-parameter shall have one of the following
810 // (optionally cv-qualified) types:
811 //
812 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000813 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000814 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000815 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000816 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000817 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000818 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000819 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000820 // -- std::nullptr_t.
821 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000822 // If T is a dependent type, we can't do the check now, so we
823 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +0000824 T->isDependentType() ||
825 // Allow use of auto in template parameter declarations.
826 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +0000827 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
828 // are ignored when determining its type.
829 return T.getUnqualifiedType();
830 }
831
Douglas Gregor463421d2009-03-03 04:44:36 +0000832 // C++ [temp.param]p8:
833 //
834 // A non-type template-parameter of type "array of T" or
835 // "function returning T" is adjusted to be of type "pointer to
836 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000837 else if (T->isArrayType() || T->isFunctionType())
838 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839
Douglas Gregor463421d2009-03-03 04:44:36 +0000840 Diag(Loc, diag::err_template_nontype_parm_bad_type)
841 << T;
842
843 return QualType();
844}
845
John McCall48871652010-08-21 09:40:31 +0000846Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
847 unsigned Depth,
848 unsigned Position,
849 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000850 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000851 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +0000852
853 if (TInfo->getType()->isUndeducedType()) {
854 Diag(D.getIdentifierLoc(),
855 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
856 << QualType(TInfo->getType()->getContainedAutoType(), 0);
857 }
Douglas Gregor5101c242008-12-05 18:15:24 +0000858
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000859 assert(S->isTemplateParamScope() &&
860 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000861 bool Invalid = false;
862
Richard Smith15361a22016-12-28 06:27:18 +0000863 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000864 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000865 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000866 Invalid = true;
867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868
Richard Smithb80d5402013-06-25 22:21:36 +0000869 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000870 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000871 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000872 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000873 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000874 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000875 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000876 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000877 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000878
Douglas Gregor5101c242008-12-05 18:15:24 +0000879 if (Invalid)
880 Param->setInvalidDecl();
881
Richard Smithb80d5402013-06-25 22:21:36 +0000882 if (ParamName) {
883 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
884 ParamName);
885
Douglas Gregor5101c242008-12-05 18:15:24 +0000886 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000887 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000888 IdResolver.AddDecl(Param);
889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000890
Douglas Gregorf5500772011-01-05 15:48:55 +0000891 // C++0x [temp.param]p9:
892 // A default template-argument may be specified for any kind of
893 // template-parameter that is not a template parameter pack.
894 if (Default && IsParameterPack) {
895 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000896 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000897 }
898
Douglas Gregordc13ded2010-07-01 00:00:45 +0000899 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000900 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000901 // Check for unexpanded parameter packs.
902 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
903 return Param;
904
Douglas Gregordc13ded2010-07-01 00:00:45 +0000905 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000906 ExprResult DefaultRes =
907 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000908 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000909 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000910 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000911 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000912 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000913
Richard Smith1469b912015-06-10 00:29:03 +0000914 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916
John McCall48871652010-08-21 09:40:31 +0000917 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000918}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000919
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000920/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000921/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000922/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000923Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
924 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000925 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000926 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000927 IdentifierInfo *Name,
928 SourceLocation NameLoc,
929 unsigned Depth,
930 unsigned Position,
931 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000932 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000933 assert(S->isTemplateParamScope() &&
934 "Template template parameter not in template parameter scope!");
935
936 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000937 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000938 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000939 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000940 NameLoc.isInvalid()? TmpLoc : NameLoc,
941 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000942 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000943 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000944
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000945 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000946 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000947 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000948 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
949
John McCall48871652010-08-21 09:40:31 +0000950 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000951 IdResolver.AddDecl(Param);
952 }
953
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000954 if (Params->size() == 0) {
955 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
956 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
957 Param->setInvalidDecl();
958 }
959
Douglas Gregorf5500772011-01-05 15:48:55 +0000960 // C++0x [temp.param]p9:
961 // A default template-argument may be specified for any kind of
962 // template-parameter that is not a template parameter pack.
963 if (IsParameterPack && !Default.isInvalid()) {
964 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
965 Default = ParsedTemplateArgument();
966 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967
Douglas Gregordc13ded2010-07-01 00:00:45 +0000968 if (!Default.isInvalid()) {
969 // Check only that we have a template template argument. We don't want to
970 // try to check well-formedness now, because our template template parameter
971 // might have dependent types in its template parameters, which we wouldn't
972 // be able to match now.
973 //
974 // If none of the template template parameter's template arguments mention
975 // other template parameters, we could actually perform more checking here.
976 // However, it isn't worth doing.
977 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
978 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000979 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000980 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000981 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000984 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000986 DefaultArg.getArgument().getAsTemplate(),
987 UPPC_DefaultArgument))
988 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000989
Richard Smith1469b912015-06-10 00:29:03 +0000990 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000992
John McCall48871652010-08-21 09:40:31 +0000993 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000994}
995
Hubert Tongf608c052016-04-29 18:05:37 +0000996/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
997/// constrained by RequiresClause, that contains the template parameters in
998/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000999TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001000Sema::ActOnTemplateParameterList(unsigned Depth,
1001 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001002 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001003 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +00001004 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001005 SourceLocation RAngleLoc,
1006 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001007 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001008 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001009
David Majnemer902f8c62015-12-27 07:16:27 +00001010 return TemplateParameterList::Create(
1011 Context, TemplateLoc, LAngleLoc,
1012 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001013 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001014}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001015
John McCall3e11ebe2010-03-15 10:12:16 +00001016static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1017 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +00001018 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00001019}
1020
John McCallfaf5fb42010-08-26 23:41:50 +00001021DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00001022Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001023 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001024 IdentifierInfo *Name, SourceLocation NameLoc,
1025 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001026 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00001027 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001028 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001029 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +00001030 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +00001031 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001032 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001033 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001034 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001035 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001036
1037 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001038 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001039 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001040
Abramo Bagnara6150c882010-05-11 21:36:43 +00001041 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1042 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001043
1044 // There is no such thing as an unnamed class template.
1045 if (!Name) {
1046 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001047 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001048 }
1049
Richard Smith6483d222012-04-21 01:27:54 +00001050 // Find any previous declaration with this name. For a friend with no
1051 // scope explicitly specified, we only look for tag declarations (per
1052 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001053 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001054 LookupResult Previous(*this, Name, NameLoc,
1055 (SS.isEmpty() && TUK == TUK_Friend)
1056 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00001057 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001058 if (SS.isNotEmpty() && !SS.isInvalid()) {
1059 SemanticContext = computeDeclContext(SS, true);
1060 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001061 // FIXME: Horrible, horrible hack! We can't currently represent this
1062 // in the AST, and historically we have just ignored such friend
1063 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001064 Diag(NameLoc, TUK == TUK_Friend
1065 ? diag::warn_template_qualified_friend_ignored
1066 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001067 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001068 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001069 }
Mike Stump11289f42009-09-09 15:08:12 +00001070
John McCall0b66eb32010-05-01 00:40:08 +00001071 if (RequireCompleteDeclContext(SS, SemanticContext))
1072 return true;
1073
Simon Pilgrim6905d222016-12-30 22:55:33 +00001074 // If we're adding a template to a dependent context, we may need to
1075 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001076 // now that we know what the current instantiation is.
1077 if (SemanticContext->isDependentContext()) {
1078 ContextRAII SavedContext(*this, SemanticContext);
1079 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1080 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001081 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1082 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +00001083
John McCall27b18f82009-11-17 02:14:36 +00001084 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001085 } else {
1086 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001087
1088 // C++14 [class.mem]p14:
1089 // If T is the name of a class, then each of the following shall have a
1090 // name different from T:
1091 // -- every member template of class T
1092 if (TUK != TUK_Friend &&
1093 DiagnoseClassNameShadow(SemanticContext,
1094 DeclarationNameInfo(Name, NameLoc)))
1095 return true;
1096
John McCall27b18f82009-11-17 02:14:36 +00001097 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001098 }
Mike Stump11289f42009-09-09 15:08:12 +00001099
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001100 if (Previous.isAmbiguous())
1101 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001102
Craig Topperc3ec1492014-05-26 06:22:03 +00001103 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001104 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001105 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001106
Serge Pavlove50bf752016-06-10 04:39:07 +00001107 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1108 // Maybe we will complain about the shadowed template parameter.
1109 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1110 // Just pretend that we didn't see the previous declaration.
1111 PrevDecl = nullptr;
1112 }
1113
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001114 // If there is a previous declaration with the same name, check
1115 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +00001116 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001117 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001118
1119 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001121 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001123 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1124 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001125 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001126 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1127 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1128 PrevClassTemplate
1129 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1130 ->getSpecializedTemplate();
1131 }
1132 }
1133
John McCalld43784f2009-12-18 11:25:59 +00001134 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001135 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136 // [...] When looking for a prior declaration of a class or a function
1137 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001138 // function is neither a qualified name nor a template-id, scopes outside
1139 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001140 if (!SS.isSet()) {
1141 DeclContext *OutermostContext = CurContext;
1142 while (!OutermostContext->isFileContext())
1143 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001144
Richard Smith61e582f2012-04-20 07:12:26 +00001145 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001146 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1147 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1148 SemanticContext = PrevDecl->getDeclContext();
1149 } else {
1150 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001152 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001153 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001154 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001155
1156 // Check that the chosen semantic context doesn't already contain a
1157 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001158 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001159 DeclContext *LookupContext = SemanticContext;
1160 while (LookupContext->isTransparentContext())
1161 LookupContext = LookupContext->getLookupParent();
1162 LookupQualifiedName(Previous, LookupContext);
1163
1164 if (Previous.isAmbiguous())
1165 return true;
1166
1167 if (Previous.begin() != Previous.end())
1168 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001169 }
John McCall90d3bb92009-12-17 23:21:11 +00001170 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001171 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001172 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1173 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001174 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001175
Richard Smithfc805ca2015-07-06 04:43:58 +00001176 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1177 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1178 if (SS.isEmpty() &&
1179 !(PrevClassTemplate &&
1180 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1181 SemanticContext->getRedeclContext()))) {
1182 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1183 Diag(Shadow->getTargetDecl()->getLocation(),
1184 diag::note_using_decl_target);
1185 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1186 // Recover by ignoring the old declaration.
1187 PrevDecl = PrevClassTemplate = nullptr;
1188 }
1189 }
1190
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001191 // TODO Memory management; associated constraints are not always stored.
1192 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1193
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001194 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001195 // Ensure that the template parameter lists are compatible. Skip this check
1196 // for a friend in a dependent context: the template parameter list itself
1197 // could be dependent.
1198 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1199 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001200 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001201 /*Complain=*/true,
1202 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001203 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001204
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001205 // Check for matching associated constraints on redeclarations.
1206 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1207 const bool RedeclACMismatch = [&] {
1208 if (!(CurAC || PrevAC))
1209 return false; // Nothing to check; no mismatch.
1210 if (CurAC && PrevAC) {
1211 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1212 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1213 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1214 if (CurACInfo == PrevACInfo)
1215 return false; // All good; no mismatch.
1216 }
1217 return true;
1218 }();
1219
1220 if (RedeclACMismatch) {
1221 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1222 diag::err_template_different_associated_constraints);
1223 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1224 diag::note_template_prev_declaration) << /*declaration*/0;
1225 return true;
1226 }
1227
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001228 // C++ [temp.class]p4:
1229 // In a redeclaration, partial specialization, explicit
1230 // specialization or explicit instantiation of a class template,
1231 // the class-key shall agree in kind with the original class
1232 // template declaration (7.1.5.3).
1233 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001234 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001235 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001236 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001237 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001238 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001239 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001240 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001241 }
1242
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001243 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001244 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001245 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001246 // If we have a prior definition that is not visible, treat this as
1247 // simply making that previous definition visible.
1248 NamedDecl *Hidden = nullptr;
1249 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001250 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001251 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1252 assert(Tmpl && "original definition of a class template is not a "
1253 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001254 makeMergedDefinitionVisible(Hidden, KWLoc);
1255 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001256 return Def;
1257 }
1258
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001259 Diag(NameLoc, diag::err_redefinition) << Name;
1260 Diag(Def->getLocation(), diag::note_previous_definition);
1261 // FIXME: Would it make sense to try to "forget" the previous
1262 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001263 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001264 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001265 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001266 } else if (PrevDecl) {
1267 // C++ [temp]p5:
1268 // A class template shall not have the same name as any other
1269 // template, class, function, object, enumeration, enumerator,
1270 // namespace, or type in the same scope (3.3), except as specified
1271 // in (14.5.4).
1272 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1273 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001274 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001275 }
1276
Douglas Gregordba32632009-02-10 19:49:53 +00001277 // Check the template parameter list of this declaration, possibly
1278 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001279 // template declaration. Skip this check for a friend in a dependent
1280 // context, because the template parameter list might be dependent.
1281 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001282 CheckTemplateParameterList(
1283 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001284 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1285 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001286 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1287 SemanticContext->isDependentContext())
1288 ? TPC_ClassTemplateMember
1289 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1290 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001291 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001292
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001293 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001294 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001295 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001296 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1297 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001298 : diag::err_member_decl_does_not_match)
1299 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001300 Invalid = true;
1301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001302 }
1303
Vassil Vassilev352e4412017-01-12 09:16:26 +00001304 // If this is a templated friend in a dependent context we should not put it
1305 // on the redecl chain. In some cases, the templated friend can be the most
1306 // recent declaration tricking the template instantiator to make substitutions
1307 // there.
1308 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1309 bool ShouldAddRedecl
1310 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1311
Mike Stump11289f42009-09-09 15:08:12 +00001312 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001313 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001314 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001315 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001316 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001317 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001318 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001319 NewClass->setTemplateParameterListsInfo(
1320 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1321 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001322
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001323 // Add alignment attributes if necessary; these attributes are checked when
1324 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001325 if (TUK == TUK_Definition) {
1326 AddAlignmentAttributesForRecord(NewClass);
1327 AddMsStructLayoutForRecord(NewClass);
1328 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001329
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001330 // Attach the associated constraints when the declaration will not be part of
1331 // a decl chain.
1332 Expr *const ACtoAttach =
1333 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1334
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001335 ClassTemplateDecl *NewTemplate
1336 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1337 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001338 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001339
1340 if (ShouldAddRedecl)
1341 NewTemplate->setPreviousDecl(PrevClassTemplate);
1342
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001343 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001344
Douglas Gregor21823bf2011-12-20 18:11:52 +00001345 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001346 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001347
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001348 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001349 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001350 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001351 assert(T->isDependentType() && "Class template type is not dependent?");
1352 (void)T;
1353
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001354 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001355 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001356 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001357 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1358 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359
Anders Carlsson137108d2009-03-26 01:24:28 +00001360 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001361 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001362 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001363
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001364 // Set the lexical context of these templates
1365 NewClass->setLexicalDeclContext(CurContext);
1366 NewTemplate->setLexicalDeclContext(CurContext);
1367
John McCall9bb74a52009-07-31 02:45:11 +00001368 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001369 NewClass->startDefinition();
1370
1371 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001372 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001373
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001374 if (PrevClassTemplate)
1375 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1376
Rafael Espindola385c0422012-07-13 18:04:45 +00001377 AddPushedVisibilityAttribute(NewClass);
1378
Richard Smith234ff472014-08-23 00:49:01 +00001379 if (TUK != TUK_Friend) {
1380 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1381 Scope *Outer = S;
1382 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1383 Outer = Outer->getParent();
1384 PushOnScopeChains(NewTemplate, Outer);
1385 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001386 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001387 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001388 NewClass->setAccess(PrevClassTemplate->getAccess());
1389 }
John McCall27b5c252009-09-14 21:59:20 +00001390
Richard Smith64017682013-07-17 23:53:16 +00001391 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001392
John McCall27b5c252009-09-14 21:59:20 +00001393 // Friend templates are visible in fairly strange ways.
1394 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001395 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001396 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001397 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1398 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001401
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001402 FriendDecl *Friend = FriendDecl::Create(
1403 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001404 Friend->setAccess(AS_public);
1405 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001406 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001407
Douglas Gregordba32632009-02-10 19:49:53 +00001408 if (Invalid) {
1409 NewTemplate->setInvalidDecl();
1410 NewClass->setInvalidDecl();
1411 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001412
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001413 ActOnDocumentableDecl(NewTemplate);
1414
John McCall48871652010-08-21 09:40:31 +00001415 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001416}
1417
Douglas Gregored5731f2009-11-25 17:50:39 +00001418/// \brief Diagnose the presence of a default template argument on a
1419/// template parameter, which is ill-formed in certain contexts.
1420///
1421/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001423 Sema::TemplateParamListContext TPC,
1424 SourceLocation ParamLoc,
1425 SourceRange DefArgRange) {
1426 switch (TPC) {
1427 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001428 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001429 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001430 return false;
1431
1432 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001433 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001434 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001435 // A default template-argument shall not be specified in a
1436 // function template declaration or a function template
1437 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00001438 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001439 // template-argument, that declaration shall be a definition and shall be
1440 // the only declaration of the function template in the translation unit.
1441 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001442 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001443 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1444 : diag::ext_template_parameter_default_in_function_template)
1445 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001446 return false;
1447
1448 case Sema::TPC_ClassTemplateMember:
1449 // C++0x [temp.param]p9:
1450 // A default template-argument shall not be specified in the
1451 // template-parameter-lists of the definition of a member of a
1452 // class template that appears outside of the member's class.
1453 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1454 << DefArgRange;
1455 return true;
1456
David Majnemerba8f17a2013-06-25 22:08:55 +00001457 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001458 case Sema::TPC_FriendFunctionTemplate:
1459 // C++ [temp.param]p9:
1460 // A default template-argument shall not be specified in a
1461 // friend template declaration.
1462 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1463 << DefArgRange;
1464 return true;
1465
1466 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1467 // for friend function templates if there is only a single
1468 // declaration (and it is a definition). Strange!
1469 }
1470
David Blaikie8a40f702012-01-17 06:56:22 +00001471 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001472}
1473
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001474/// \brief Check for unexpanded parameter packs within the template parameters
1475/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001476static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1477 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001478 // A template template parameter which is a parameter pack is also a pack
1479 // expansion.
1480 if (TTP->isParameterPack())
1481 return false;
1482
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001483 TemplateParameterList *Params = TTP->getTemplateParameters();
1484 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1485 NamedDecl *P = Params->getParam(I);
1486 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001487 if (!NTTP->isParameterPack() &&
1488 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001489 NTTP->getTypeSourceInfo(),
1490 Sema::UPPC_NonTypeTemplateParameterType))
1491 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001492
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001493 continue;
1494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495
1496 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001497 = dyn_cast<TemplateTemplateParmDecl>(P))
1498 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1499 return true;
1500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001501
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001502 return false;
1503}
1504
Douglas Gregordba32632009-02-10 19:49:53 +00001505/// \brief Checks the validity of a template parameter list, possibly
1506/// considering the template parameter list from a previous
1507/// declaration.
1508///
1509/// If an "old" template parameter list is provided, it must be
1510/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1511/// template parameter list.
1512///
1513/// \param NewParams Template parameter list for a new template
1514/// declaration. This template parameter list will be updated with any
1515/// default arguments that are carried through from the previous
1516/// template parameter list.
1517///
1518/// \param OldParams If provided, template parameter list from a
1519/// previous declaration of the same template. Default template
1520/// arguments will be merged from the old template parameter list to
1521/// the new template parameter list.
1522///
Douglas Gregored5731f2009-11-25 17:50:39 +00001523/// \param TPC Describes the context in which we are checking the given
1524/// template parameter list.
1525///
Douglas Gregordba32632009-02-10 19:49:53 +00001526/// \returns true if an error occurred, false otherwise.
1527bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001528 TemplateParameterList *OldParams,
1529 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001530 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001531
Douglas Gregordba32632009-02-10 19:49:53 +00001532 // C++ [temp.param]p10:
1533 // The set of default template-arguments available for use with a
1534 // template declaration or definition is obtained by merging the
1535 // default arguments from the definition (if in scope) and all
1536 // declarations in scope in the same way default function
1537 // arguments are (8.3.6).
1538 bool SawDefaultArgument = false;
1539 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001540
Mike Stumpc89c8e32009-02-11 23:03:27 +00001541 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001542 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001543 if (OldParams)
1544 OldParam = OldParams->begin();
1545
Douglas Gregor0693def2011-01-27 01:40:17 +00001546 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001547 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1548 NewParamEnd = NewParams->end();
1549 NewParam != NewParamEnd; ++NewParam) {
1550 // Variables used to diagnose redundant default arguments
1551 bool RedundantDefaultArg = false;
1552 SourceLocation OldDefaultLoc;
1553 SourceLocation NewDefaultLoc;
1554
David Blaikie651c73c2011-10-19 05:19:50 +00001555 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001556 bool MissingDefaultArg = false;
1557
David Blaikie651c73c2011-10-19 05:19:50 +00001558 // Variable used to diagnose non-final parameter packs
1559 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001560
Douglas Gregordba32632009-02-10 19:49:53 +00001561 if (TemplateTypeParmDecl *NewTypeParm
1562 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001563 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001564 if (NewTypeParm->hasDefaultArgument() &&
1565 DiagnoseDefaultTemplateArgument(*this, TPC,
1566 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001567 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001568 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001569 NewTypeParm->removeDefaultArgument();
1570
1571 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001572 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001573 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001574 if (NewTypeParm->isParameterPack()) {
1575 assert(!NewTypeParm->hasDefaultArgument() &&
1576 "Parameter packs can't have a default argument!");
1577 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001578 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001579 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001580 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1581 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1582 SawDefaultArgument = true;
1583 RedundantDefaultArg = true;
1584 PreviousDefaultArgLoc = NewDefaultLoc;
1585 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1586 // Merge the default argument from the old declaration to the
1587 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001588 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001589 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1590 } else if (NewTypeParm->hasDefaultArgument()) {
1591 SawDefaultArgument = true;
1592 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1593 } else if (SawDefaultArgument)
1594 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001595 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001596 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001597 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001598 if (!NewNonTypeParm->isParameterPack() &&
1599 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001600 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001601 UPPC_NonTypeTemplateParameterType)) {
1602 Invalid = true;
1603 continue;
1604 }
1605
Douglas Gregored5731f2009-11-25 17:50:39 +00001606 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001607 if (NewNonTypeParm->hasDefaultArgument() &&
1608 DiagnoseDefaultTemplateArgument(*this, TPC,
1609 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001610 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001611 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001612 }
1613
Mike Stump12b8ce12009-08-04 21:02:39 +00001614 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001615 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001616 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001617 if (NewNonTypeParm->isParameterPack()) {
1618 assert(!NewNonTypeParm->hasDefaultArgument() &&
1619 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001620 if (!NewNonTypeParm->isPackExpansion())
1621 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001622 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001623 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001624 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1625 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1626 SawDefaultArgument = true;
1627 RedundantDefaultArg = true;
1628 PreviousDefaultArgLoc = NewDefaultLoc;
1629 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1630 // Merge the default argument from the old declaration to the
1631 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001632 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001633 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1634 } else if (NewNonTypeParm->hasDefaultArgument()) {
1635 SawDefaultArgument = true;
1636 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1637 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001638 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001639 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001640 TemplateTemplateParmDecl *NewTemplateParm
1641 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001642
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001643 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001644 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001645 Invalid = true;
1646 continue;
1647 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001648
David Blaikie651c73c2011-10-19 05:19:50 +00001649 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001650 if (NewTemplateParm->hasDefaultArgument() &&
1651 DiagnoseDefaultTemplateArgument(*this, TPC,
1652 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001653 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001654 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001655
1656 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001657 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001658 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001659 if (NewTemplateParm->isParameterPack()) {
1660 assert(!NewTemplateParm->hasDefaultArgument() &&
1661 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001662 if (!NewTemplateParm->isPackExpansion())
1663 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001664 } else if (OldTemplateParm &&
1665 hasVisibleDefaultArgument(OldTemplateParm) &&
1666 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001667 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1668 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001669 SawDefaultArgument = true;
1670 RedundantDefaultArg = true;
1671 PreviousDefaultArgLoc = NewDefaultLoc;
1672 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1673 // Merge the default argument from the old declaration to the
1674 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001675 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001676 PreviousDefaultArgLoc
1677 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001678 } else if (NewTemplateParm->hasDefaultArgument()) {
1679 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001680 PreviousDefaultArgLoc
1681 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001682 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001683 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001684 }
1685
Richard Smith1fde8ec2012-09-07 02:06:42 +00001686 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001687 // If a template parameter of a primary class template or alias template
1688 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001689 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001690 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1691 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001692 Diag((*NewParam)->getLocation(),
1693 diag::err_template_param_pack_must_be_last_template_parameter);
1694 Invalid = true;
1695 }
1696
Douglas Gregordba32632009-02-10 19:49:53 +00001697 if (RedundantDefaultArg) {
1698 // C++ [temp.param]p12:
1699 // A template-parameter shall not be given default arguments
1700 // by two different declarations in the same scope.
1701 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1702 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1703 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001704 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001705 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001706 // If a template-parameter of a class template has a default
1707 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001708 // have a default template-argument supplied or be a template parameter
1709 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001710 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001711 diag::err_template_param_default_arg_missing);
1712 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1713 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001714 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001715 }
1716
1717 // If we have an old template parameter list that we're merging
1718 // in, move on to the next parameter.
1719 if (OldParams)
1720 ++OldParam;
1721 }
1722
Douglas Gregor0693def2011-01-27 01:40:17 +00001723 // We were missing some default arguments at the end of the list, so remove
1724 // all of the default arguments.
1725 if (RemoveDefaultArguments) {
1726 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1727 NewParamEnd = NewParams->end();
1728 NewParam != NewParamEnd; ++NewParam) {
1729 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1730 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001731 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001732 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1733 NTTP->removeDefaultArgument();
1734 else
1735 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1736 }
1737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001738
Douglas Gregordba32632009-02-10 19:49:53 +00001739 return Invalid;
1740}
Douglas Gregord32e0282009-02-09 23:23:08 +00001741
John McCalla020a012010-10-20 05:44:58 +00001742namespace {
1743
1744/// A class which looks for a use of a certain level of template
1745/// parameter.
1746struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1747 typedef RecursiveASTVisitor<DependencyChecker> super;
1748
1749 unsigned Depth;
Richard Smith43a833b2017-01-09 23:54:33 +00001750 bool FindLessThanDepth;
Richard Smith57aae072016-12-28 02:37:25 +00001751
1752 // Whether we're looking for a use of a template parameter that makes the
1753 // overall construct type-dependent / a dependent type. This is strictly
1754 // best-effort for now; we may fail to match at all for a dependent type
1755 // in some cases if this is set.
1756 bool IgnoreNonTypeDependent;
1757
John McCalla020a012010-10-20 05:44:58 +00001758 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001759 SourceLocation MatchLoc;
1760
Richard Smith43a833b2017-01-09 23:54:33 +00001761 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent,
1762 bool FindLessThanDepth = false)
1763 : Depth(Depth), FindLessThanDepth(FindLessThanDepth),
1764 IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001765
Richard Smith57aae072016-12-28 02:37:25 +00001766 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith43a833b2017-01-09 23:54:33 +00001767 : DependencyChecker(Params->getDepth(), IgnoreNonTypeDependent) {}
John McCalla020a012010-10-20 05:44:58 +00001768
Richard Smith6056d5e2014-02-09 00:54:43 +00001769 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith43a833b2017-01-09 23:54:33 +00001770 if (FindLessThanDepth ^ (ParmDepth >= Depth)) {
John McCalla020a012010-10-20 05:44:58 +00001771 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001772 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001773 return true;
1774 }
1775 return false;
1776 }
1777
Richard Smith57aae072016-12-28 02:37:25 +00001778 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
1779 // Prune out non-type-dependent expressions if requested. This can
1780 // sometimes result in us failing to find a template parameter reference
1781 // (if a value-dependent expression creates a dependent type), but this
1782 // mode is best-effort only.
1783 if (auto *E = dyn_cast_or_null<Expr>(S))
1784 if (IgnoreNonTypeDependent && !E->isTypeDependent())
1785 return true;
1786 return super::TraverseStmt(S, Q);
1787 }
1788
1789 bool TraverseTypeLoc(TypeLoc TL) {
1790 if (IgnoreNonTypeDependent && !TL.isNull() &&
1791 !TL.getType()->isDependentType())
1792 return true;
1793 return super::TraverseTypeLoc(TL);
1794 }
1795
Richard Smith6056d5e2014-02-09 00:54:43 +00001796 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1797 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1798 }
1799
John McCalla020a012010-10-20 05:44:58 +00001800 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00001801 // For a best-effort search, keep looking until we find a location.
1802 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00001803 }
1804
1805 bool TraverseTemplateName(TemplateName N) {
1806 if (TemplateTemplateParmDecl *PD =
1807 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001808 if (Matches(PD->getDepth()))
1809 return false;
John McCalla020a012010-10-20 05:44:58 +00001810 return super::TraverseTemplateName(N);
1811 }
1812
1813 bool VisitDeclRefExpr(DeclRefExpr *E) {
1814 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001815 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1816 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001817 return false;
John McCalla020a012010-10-20 05:44:58 +00001818 return super::VisitDeclRefExpr(E);
1819 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001820
1821 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1822 return TraverseType(T->getReplacementType());
1823 }
1824
1825 bool
1826 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1827 return TraverseTemplateArgument(T->getArgumentPack());
1828 }
1829
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001830 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1831 return TraverseType(T->getInjectedSpecializationType());
1832 }
John McCalla020a012010-10-20 05:44:58 +00001833};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001834} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001835
Douglas Gregor972fe532011-05-10 18:27:06 +00001836/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001837/// list.
1838static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001839DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00001840 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00001841 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001842 return Checker.Match;
1843}
1844
Douglas Gregor972fe532011-05-10 18:27:06 +00001845// Find the source range corresponding to the named type in the given
1846// nested-name-specifier, if any.
1847static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1848 QualType T,
1849 const CXXScopeSpec &SS) {
1850 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1851 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1852 if (const Type *CurType = NNS->getAsType()) {
1853 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1854 return NNSLoc.getTypeLoc().getSourceRange();
1855 } else
1856 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001857
Douglas Gregor972fe532011-05-10 18:27:06 +00001858 NNSLoc = NNSLoc.getPrefix();
1859 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001860
Douglas Gregor972fe532011-05-10 18:27:06 +00001861 return SourceRange();
1862}
1863
Mike Stump11289f42009-09-09 15:08:12 +00001864/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001865/// specifier, returning the template parameter list that applies to the
1866/// name.
1867///
1868/// \param DeclStartLoc the start of the declaration that has a scope
1869/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001870///
Douglas Gregor972fe532011-05-10 18:27:06 +00001871/// \param DeclLoc The location of the declaration itself.
1872///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001873/// \param SS the scope specifier that will be matched to the given template
1874/// parameter lists. This scope specifier precedes a qualified name that is
1875/// being declared.
1876///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001877/// \param TemplateId The template-id following the scope specifier, if there
1878/// is one. Used to check for a missing 'template<>'.
1879///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001880/// \param ParamLists the template parameter lists, from the outermost to the
1881/// innermost template parameter lists.
1882///
John McCalle820e5e2010-04-13 20:37:33 +00001883/// \param IsFriend Whether to apply the slightly different rules for
1884/// matching template parameters to scope specifiers in friend
1885/// declarations.
1886///
Richard Smithf445f192017-02-09 21:04:43 +00001887/// \param IsMemberSpecialization will be set true if the scope specifier
1888/// denotes a fully-specialized type, and therefore this is a declaration of
1889/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001890///
Mike Stump11289f42009-09-09 15:08:12 +00001891/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001892/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001893/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001894/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001895/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001896/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001897TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1898 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001899 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001900 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00001901 bool &IsMemberSpecialization, bool &Invalid) {
1902 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001903 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001904
Douglas Gregor972fe532011-05-10 18:27:06 +00001905 // The sequence of nested types to which we will match up the template
1906 // parameter lists. We first build this list by starting with the type named
1907 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001908 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001909 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001910 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00001911 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001912 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1913 T = Context.getTypeDeclType(Record);
1914 else
1915 T = QualType(SS.getScopeRep()->getAsType(), 0);
1916 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001917
Douglas Gregor972fe532011-05-10 18:27:06 +00001918 // If we found an explicit specialization that prevents us from needing
1919 // 'template<>' headers, this will be set to the location of that
1920 // explicit specialization.
1921 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001922
Douglas Gregor972fe532011-05-10 18:27:06 +00001923 while (!T.isNull()) {
1924 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001925
Douglas Gregor972fe532011-05-10 18:27:06 +00001926 // Retrieve the parent of a record type.
1927 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1928 // If this type is an explicit specialization, we're done.
1929 if (ClassTemplateSpecializationDecl *Spec
1930 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00001931 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001932 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1933 ExplicitSpecLoc = Spec->getLocation();
1934 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001935 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001936 } else if (Record->getTemplateSpecializationKind()
1937 == TSK_ExplicitSpecialization) {
1938 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001939 break;
1940 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001941
Douglas Gregor972fe532011-05-10 18:27:06 +00001942 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1943 T = Context.getTypeDeclType(Parent);
1944 else
1945 T = QualType();
1946 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001947 }
1948
Douglas Gregor972fe532011-05-10 18:27:06 +00001949 if (const TemplateSpecializationType *TST
1950 = T->getAs<TemplateSpecializationType>()) {
1951 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1952 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1953 T = Context.getTypeDeclType(Parent);
1954 else
1955 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001956 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001957 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001958 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001959
Douglas Gregor972fe532011-05-10 18:27:06 +00001960 // Look one step prior in a dependent template specialization type.
1961 if (const DependentTemplateSpecializationType *DependentTST
1962 = T->getAs<DependentTemplateSpecializationType>()) {
1963 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1964 T = QualType(NNS->getAsType(), 0);
1965 else
1966 T = QualType();
1967 continue;
1968 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001969
Douglas Gregor972fe532011-05-10 18:27:06 +00001970 // Look one step prior in a dependent name type.
1971 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1972 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1973 T = QualType(NNS->getAsType(), 0);
1974 else
1975 T = QualType();
1976 continue;
1977 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001978
Douglas Gregor972fe532011-05-10 18:27:06 +00001979 // Retrieve the parent of an enumeration type.
1980 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1981 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1982 // check here.
1983 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001984
Douglas Gregor972fe532011-05-10 18:27:06 +00001985 // Get to the parent type.
1986 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1987 T = Context.getTypeDeclType(Parent);
1988 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00001989 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00001990 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001991 }
Mike Stump11289f42009-09-09 15:08:12 +00001992
Douglas Gregor972fe532011-05-10 18:27:06 +00001993 T = QualType();
1994 }
1995 // Reverse the nested types list, since we want to traverse from the outermost
1996 // to the innermost while checking template-parameter-lists.
1997 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001998
Douglas Gregor972fe532011-05-10 18:27:06 +00001999 // C++0x [temp.expl.spec]p17:
2000 // A member or a member template may be nested within many
2001 // enclosing class templates. In an explicit specialization for
2002 // such a member, the member declaration shall be preceded by a
2003 // template<> for each enclosing class template that is
2004 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002005 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002006
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002007 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002008 if (SawNonEmptyTemplateParameterList) {
2009 Diag(DeclLoc, diag::err_specialize_member_of_template)
2010 << !Recovery << Range;
2011 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002012 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002013 return true;
2014 }
2015
2016 return false;
2017 };
2018
2019 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2020 // Check that we can have an explicit specialization here.
2021 if (CheckExplicitSpecialization(Range, true))
2022 return true;
2023
2024 // We don't have a template header, but we should.
2025 SourceLocation ExpectedTemplateLoc;
2026 if (!ParamLists.empty())
2027 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2028 else
2029 ExpectedTemplateLoc = DeclStartLoc;
2030
2031 Diag(DeclLoc, diag::err_template_spec_needs_header)
2032 << Range
2033 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2034 return false;
2035 };
2036
Douglas Gregor972fe532011-05-10 18:27:06 +00002037 unsigned ParamIdx = 0;
2038 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2039 ++TypeIdx) {
2040 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002041
Douglas Gregor972fe532011-05-10 18:27:06 +00002042 // Whether we expect a 'template<>' header.
2043 bool NeedEmptyTemplateHeader = false;
2044
2045 // Whether we expect a template header with parameters.
2046 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002047
Douglas Gregor972fe532011-05-10 18:27:06 +00002048 // For a dependent type, the set of template parameters that we
2049 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002050 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002051
Douglas Gregor373af9b2011-05-11 23:26:17 +00002052 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002053 // A member or a member template may be nested within many enclosing
2054 // class templates. In an explicit specialization for such a member, the
2055 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002056 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002057 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2058 if (ClassTemplatePartialSpecializationDecl *Partial
2059 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2060 ExpectedTemplateParams = Partial->getTemplateParameters();
2061 NeedNonemptyTemplateHeader = true;
2062 } else if (Record->isDependentType()) {
2063 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002064 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002065 ->getTemplateParameters();
2066 NeedNonemptyTemplateHeader = true;
2067 }
2068 } else if (ClassTemplateSpecializationDecl *Spec
2069 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2070 // C++0x [temp.expl.spec]p4:
2071 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002072 // in the same manner as members of normal classes, and not using
2073 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002074 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2075 NeedEmptyTemplateHeader = true;
2076 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002077 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002078 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002079 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002080 != TSK_ExplicitSpecialization &&
2081 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002082 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002083
Douglas Gregor373af9b2011-05-11 23:26:17 +00002084 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002085 }
2086 } else if (const TemplateSpecializationType *TST
2087 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002088 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002089 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002090 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002091 }
2092 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2093 // FIXME: We actually could/should check the template arguments here
2094 // against the corresponding template parameter list.
2095 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002096 }
2097
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002098 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002099 // In an explicit specialization declaration for a member of a class
2100 // template or a member template that ap- pears in namespace scope, the
2101 // member template and some of its enclosing class templates may remain
2102 // unspecialized, except that the declaration shall not explicitly
2103 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002104 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002105 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002106 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002107 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2108 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002109 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002110 } else
2111 SawNonEmptyTemplateParameterList = true;
2112 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002113
Douglas Gregor972fe532011-05-10 18:27:06 +00002114 if (NeedEmptyTemplateHeader) {
2115 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002116 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002117 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002118 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002119
2120 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002121 if (ParamLists[ParamIdx]->size() > 0) {
2122 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002123 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002124 diag::err_template_param_list_matches_nontemplate)
2125 << T
2126 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2127 ParamLists[ParamIdx]->getRAngleLoc())
2128 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2129 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002130 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002131 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002132
Douglas Gregor972fe532011-05-10 18:27:06 +00002133 // Consume this template header.
2134 ++ParamIdx;
2135 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002136 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002137
2138 if (!IsFriend)
2139 if (DiagnoseMissingExplicitSpecialization(
2140 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002141 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002142
Douglas Gregor972fe532011-05-10 18:27:06 +00002143 continue;
2144 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002145
Douglas Gregor972fe532011-05-10 18:27:06 +00002146 if (NeedNonemptyTemplateHeader) {
2147 // In friend declarations we can have template-ids which don't
2148 // depend on the corresponding template parameter lists. But
2149 // assume that empty parameter lists are supposed to match this
2150 // template-id.
2151 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002152 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002153 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002154 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002155 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002156 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002157 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002158
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002159 if (ParamIdx < ParamLists.size()) {
2160 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002161 if (ExpectedTemplateParams &&
2162 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2163 ExpectedTemplateParams,
2164 true, TPL_TemplateMatch))
2165 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002166
Douglas Gregor972fe532011-05-10 18:27:06 +00002167 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002168 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002169 TPC_ClassTemplateMember))
2170 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002171
Douglas Gregor972fe532011-05-10 18:27:06 +00002172 ++ParamIdx;
2173 continue;
2174 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002175
Douglas Gregor972fe532011-05-10 18:27:06 +00002176 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2177 << T
2178 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2179 Invalid = true;
2180 continue;
2181 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002182 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002183
Douglas Gregord8d297c2009-07-21 23:53:31 +00002184 // If there were at least as many template-ids as there were template
2185 // parameter lists, then there are no template parameter lists remaining for
2186 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002187 if (ParamIdx >= ParamLists.size()) {
2188 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002189 // We don't have a template header for the declaration itself, but we
2190 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002191 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2192 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002193
2194 // Fabricate an empty template parameter list for the invented header.
2195 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002196 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002197 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002198 }
2199
Craig Topperc3ec1492014-05-26 06:22:03 +00002200 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002201 }
Mike Stump11289f42009-09-09 15:08:12 +00002202
Douglas Gregord8d297c2009-07-21 23:53:31 +00002203 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002204 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002205 bool HasAnyExplicitSpecHeader = false;
2206 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002207 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002208 if (ParamLists[I]->size() == 0)
2209 HasAnyExplicitSpecHeader = true;
2210 else
2211 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002212 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002213
Douglas Gregor972fe532011-05-10 18:27:06 +00002214 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002215 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2216 : diag::err_template_spec_extra_headers)
2217 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2218 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002219
2220 // If there was a specialization somewhere, such that 'template<>' is
2221 // not required, and there were any 'template<>' headers, note where the
2222 // specialization occurred.
2223 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002224 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002225 diag::note_explicit_template_spec_does_not_need_header)
2226 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002227
Douglas Gregor972fe532011-05-10 18:27:06 +00002228 // We have a template parameter list with no corresponding scope, which
2229 // means that the resulting template declaration can't be instantiated
2230 // properly (we'll end up with dependent nodes when we shouldn't).
2231 if (!AllExplicitSpecHeaders)
2232 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002233 }
Mike Stump11289f42009-09-09 15:08:12 +00002234
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002235 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002236 // In an explicit specialization declaration for a member of a class
2237 // template or a member template that ap- pears in namespace scope, the
2238 // member template and some of its enclosing class templates may remain
2239 // unspecialized, except that the declaration shall not explicitly
2240 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002241 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002242 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002243 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2244 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002245 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002246
Douglas Gregord8d297c2009-07-21 23:53:31 +00002247 // Return the last template parameter list, which corresponds to the
2248 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002249 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002250}
2251
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002252void Sema::NoteAllFoundTemplates(TemplateName Name) {
2253 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2254 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002255 << (isa<FunctionTemplateDecl>(Template)
2256 ? 0
2257 : isa<ClassTemplateDecl>(Template)
2258 ? 1
2259 : isa<VarTemplateDecl>(Template)
2260 ? 2
2261 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2262 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002263 return;
2264 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002265
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002266 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002267 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002268 IEnd = OST->end();
2269 I != IEnd; ++I)
2270 Diag((*I)->getLocation(), diag::note_template_declared_here)
2271 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002272
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002273 return;
2274 }
2275}
2276
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002277static QualType
2278checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2279 const SmallVectorImpl<TemplateArgument> &Converted,
2280 SourceLocation TemplateLoc,
2281 TemplateArgumentListInfo &TemplateArgs) {
2282 ASTContext &Context = SemaRef.getASTContext();
2283 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002284 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002285 // Specializations of __make_integer_seq<S, T, N> are treated like
2286 // S<T, 0, ..., N-1>.
2287
2288 // C++14 [inteseq.intseq]p1:
2289 // T shall be an integer type.
2290 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2291 SemaRef.Diag(TemplateArgs[1].getLocation(),
2292 diag::err_integer_sequence_integral_element_type);
2293 return QualType();
2294 }
2295
2296 // C++14 [inteseq.make]p1:
2297 // If N is negative the program is ill-formed.
2298 TemplateArgument NumArgsArg = Converted[2];
2299 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2300 if (NumArgs < 0) {
2301 SemaRef.Diag(TemplateArgs[2].getLocation(),
2302 diag::err_integer_sequence_negative_length);
2303 return QualType();
2304 }
2305
2306 QualType ArgTy = NumArgsArg.getIntegralType();
2307 TemplateArgumentListInfo SyntheticTemplateArgs;
2308 // The type argument gets reused as the first template argument in the
2309 // synthetic template argument list.
2310 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2311 // Expand N into 0 ... N-1.
2312 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2313 I < NumArgs; ++I) {
2314 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002315 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2316 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002317 }
2318 // The first template argument will be reused as the template decl that
2319 // our synthetic template arguments will be applied to.
2320 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2321 TemplateLoc, SyntheticTemplateArgs);
2322 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002323
2324 case BTK__type_pack_element:
2325 // Specializations of
2326 // __type_pack_element<Index, T_1, ..., T_N>
2327 // are treated like T_Index.
2328 assert(Converted.size() == 2 &&
2329 "__type_pack_element should be given an index and a parameter pack");
2330
2331 // If the Index is out of bounds, the program is ill-formed.
2332 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2333 llvm::APSInt Index = IndexArg.getAsIntegral();
2334 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2335 "type std::size_t, and hence be non-negative");
2336 if (Index >= Ts.pack_size()) {
2337 SemaRef.Diag(TemplateArgs[0].getLocation(),
2338 diag::err_type_pack_element_out_of_bounds);
2339 return QualType();
2340 }
2341
2342 // We simply return the type at index `Index`.
2343 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2344 return Nth->getAsType();
2345 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002346 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2347}
2348
Douglas Gregordc572a32009-03-30 22:58:21 +00002349QualType Sema::CheckTemplateIdType(TemplateName Name,
2350 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002351 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002352 DependentTemplateName *DTN
2353 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002354 if (DTN && DTN->isIdentifier())
2355 // When building a template-id where the template-name is dependent,
2356 // assume the template is a type template. Either our assumption is
2357 // correct, or the code is ill-formed and will be diagnosed when the
2358 // dependent name is substituted.
2359 return Context.getDependentTemplateSpecializationType(ETK_None,
2360 DTN->getQualifier(),
2361 DTN->getIdentifier(),
2362 TemplateArgs);
2363
Douglas Gregordc572a32009-03-30 22:58:21 +00002364 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002365 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2366 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002367 // We might have a substituted template template parameter pack. If so,
2368 // build a template specialization type for it.
2369 if (Name.getAsSubstTemplateTemplateParmPack())
2370 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002371
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002372 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2373 << Name;
2374 NoteAllFoundTemplates(Name);
2375 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002376 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002377
Douglas Gregorc40290e2009-03-09 23:48:35 +00002378 // Check that the template argument list is well-formed for this
2379 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002380 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002381 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002382 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002383 return QualType();
2384
Douglas Gregorc40290e2009-03-09 23:48:35 +00002385 QualType CanonType;
2386
Douglas Gregor678d76c2011-07-01 01:22:09 +00002387 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002388 if (TypeAliasTemplateDecl *AliasTemplate =
2389 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002390 // Find the canonical type for this type alias template specialization.
2391 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2392 if (Pattern->isInvalidDecl())
2393 return QualType();
2394
2395 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002396 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002397
2398 // Only substitute for the innermost template argument list.
2399 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002400 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002401 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2402 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002403 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002404
Richard Smith802c4b72012-08-23 06:16:52 +00002405 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002406 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002407 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002408 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002409
Richard Smith3f1b5d02011-05-05 21:57:07 +00002410 CanonType = SubstType(Pattern->getUnderlyingType(),
2411 TemplateArgLists, AliasTemplate->getLocation(),
2412 AliasTemplate->getDeclName());
2413 if (CanonType.isNull())
2414 return QualType();
2415 } else if (Name.isDependent() ||
2416 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002417 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002418 // This class template specialization is a dependent
2419 // type. Therefore, its canonical type is another class template
2420 // specialization type that contains all of the converted
2421 // arguments in canonical form. This ensures that, e.g., A<T> and
2422 // A<T, T> have identical types when A is declared as:
2423 //
2424 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00002425 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00002426
2427 // This might work out to be a current instantiation, in which
2428 // case the canonical type needs to be the InjectedClassNameType.
2429 //
2430 // TODO: in theory this could be a simple hashtable lookup; most
2431 // changes to CurContext don't change the set of current
2432 // instantiations.
2433 if (isa<ClassTemplateDecl>(Template)) {
2434 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2435 // If we get out to a namespace, we're done.
2436 if (Ctx->isFileContext()) break;
2437
2438 // If this isn't a record, keep looking.
2439 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2440 if (!Record) continue;
2441
2442 // Look for one of the two cases with InjectedClassNameTypes
2443 // and check whether it's the same template.
2444 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2445 !Record->getDescribedClassTemplate())
2446 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002447
John McCall2408e322010-04-27 00:57:59 +00002448 // Fetch the injected class name type and check whether its
2449 // injected type is equal to the type we just built.
2450 QualType ICNT = Context.getTypeDeclType(Record);
2451 QualType Injected = cast<InjectedClassNameType>(ICNT)
2452 ->getInjectedSpecializationType();
2453
2454 if (CanonType != Injected->getCanonicalTypeInternal())
2455 continue;
2456
2457 // If so, the canonical type of this TST is the injected
2458 // class name type of the record we just found.
2459 assert(ICNT.isCanonical());
2460 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002461 break;
2462 }
2463 }
Mike Stump11289f42009-09-09 15:08:12 +00002464 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002465 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002466 // Find the class template specialization declaration that
2467 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002468 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002469 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002470 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002471 if (!Decl) {
2472 // This is the first time we have referenced this class template
2473 // specialization. Create the canonical declaration and add it to
2474 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002475 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002476 ClassTemplate->getTemplatedDecl()->getTagKind(),
2477 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002478 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002479 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002480 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00002481 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002482 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002483 if (ClassTemplate->isOutOfLine())
2484 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002485 }
2486
Chandler Carruth2acfb222013-09-27 22:14:40 +00002487 // Diagnose uses of this specialization.
2488 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2489
Douglas Gregorc40290e2009-03-09 23:48:35 +00002490 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002491 assert(isa<RecordType>(CanonType) &&
2492 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002493 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2494 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2495 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002496 }
Mike Stump11289f42009-09-09 15:08:12 +00002497
Douglas Gregorc40290e2009-03-09 23:48:35 +00002498 // Build the fully-sugared type for this class template
2499 // specialization, which refers back to the class template
2500 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002501 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002502}
2503
John McCallfaf5fb42010-08-26 23:41:50 +00002504TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002505Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00002506 TemplateTy TemplateD, IdentifierInfo *TemplateII,
2507 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00002508 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002509 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002510 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00002511 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002512 if (SS.isInvalid())
2513 return true;
2514
Richard Smith62559bd2017-02-01 21:36:38 +00002515 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
2516 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
2517
2518 // C++ [temp.res]p3:
2519 // A qualified-id that refers to a type and in which the
2520 // nested-name-specifier depends on a template-parameter (14.6.2)
2521 // shall be prefixed by the keyword typename to indicate that the
2522 // qualified-id denotes a type, forming an
2523 // elaborated-type-specifier (7.1.5.3).
2524 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00002525 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00002526 << SS.getScopeRep() << TemplateII->getName();
2527 // Recover as if 'typename' were specified.
2528 // FIXME: This is not quite correct recovery as we don't transform SS
2529 // into the corresponding dependent form (and we don't diagnose missing
2530 // 'template' keywords within SS as a result).
2531 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
2532 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
2533 TemplateArgsIn, RAngleLoc);
2534 }
2535
2536 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
2537 // it's not actually allowed to be used as a type in most cases. Because
2538 // we annotate it before we know whether it's valid, we have to check for
2539 // this case here.
2540 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00002541 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
2542 Diag(TemplateIILoc,
2543 TemplateKWLoc.isInvalid()
2544 ? diag::err_out_of_line_qualified_id_type_names_constructor
2545 : diag::ext_out_of_line_qualified_id_type_names_constructor)
2546 << TemplateII << 0 /*injected-class-name used as template name*/
2547 << 1 /*if any keyword was present, it was 'template'*/;
2548 }
2549 }
2550
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002551 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002552
Douglas Gregorc40290e2009-03-09 23:48:35 +00002553 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002554 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002555 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002556
Douglas Gregor5a064722011-02-28 17:23:35 +00002557 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002558 QualType T
2559 = Context.getDependentTemplateSpecializationType(ETK_None,
2560 DTN->getQualifier(),
2561 DTN->getIdentifier(),
2562 TemplateArgs);
2563 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002564 TypeLocBuilder TLB;
2565 DependentTemplateSpecializationTypeLoc SpecTL
2566 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002567 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2568 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002569 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00002570 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002571 SpecTL.setLAngleLoc(LAngleLoc);
2572 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002573 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2574 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2575 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2576 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002577
Richard Smith74f02342017-01-19 21:00:13 +00002578 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002579 if (Result.isNull())
2580 return true;
2581
Douglas Gregore7c20652011-03-02 00:47:37 +00002582 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002583 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002584 TemplateSpecializationTypeLoc SpecTL
2585 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002586 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00002587 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002588 SpecTL.setLAngleLoc(LAngleLoc);
2589 SpecTL.setRAngleLoc(RAngleLoc);
2590 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2591 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002592
Abramo Bagnara4244b432012-01-27 08:46:19 +00002593 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2594 // constructor or destructor name (in such a case, the scope specifier
2595 // will be attached to the enclosing Decl or Expr node).
2596 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002597 // Create an elaborated-type-specifier containing the nested-name-specifier.
2598 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2599 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002600 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002601 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2602 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002603
Douglas Gregore7c20652011-03-02 00:47:37 +00002604 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002605}
John McCall06f6fe8d2009-09-04 01:14:41 +00002606
Douglas Gregore7c20652011-03-02 00:47:37 +00002607TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002608 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002609 SourceLocation TagLoc,
2610 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002611 SourceLocation TemplateKWLoc,
2612 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002613 SourceLocation TemplateLoc,
2614 SourceLocation LAngleLoc,
2615 ASTTemplateArgsPtr TemplateArgsIn,
2616 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002617 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002618
Douglas Gregore7c20652011-03-02 00:47:37 +00002619 // Translate the parser's template argument list in our AST format.
2620 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2621 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002622
Douglas Gregore7c20652011-03-02 00:47:37 +00002623 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002624 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002625 ElaboratedTypeKeyword Keyword
2626 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002627
Douglas Gregore7c20652011-03-02 00:47:37 +00002628 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2629 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00002630 DTN->getQualifier(),
2631 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00002632 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002633
2634 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00002635 TypeLocBuilder TLB;
2636 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002637 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2638 SpecTL.setElaboratedKeywordLoc(TagLoc);
2639 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002640 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002641 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002642 SpecTL.setLAngleLoc(LAngleLoc);
2643 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002644 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2645 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2646 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2647 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002648
2649 if (TypeAliasTemplateDecl *TAT =
2650 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2651 // C++0x [dcl.type.elab]p2:
2652 // If the identifier resolves to a typedef-name or the simple-template-id
2653 // resolves to an alias template specialization, the
2654 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00002655 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
2656 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002657 Diag(TAT->getLocation(), diag::note_declared_at);
2658 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002659
Douglas Gregore7c20652011-03-02 00:47:37 +00002660 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2661 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002662 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002663
Douglas Gregore7c20652011-03-02 00:47:37 +00002664 // Check the tag kind
2665 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002666 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002667
John McCalld8fe9af2009-09-08 17:47:29 +00002668 IdentifierInfo *Id = D->getIdentifier();
2669 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00002670
Richard Trieucaa33d32011-06-10 03:11:26 +00002671 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002672 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002673 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002674 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002675 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002676 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002677 }
2678 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002679
Douglas Gregore7c20652011-03-02 00:47:37 +00002680 // Provide source-location information for the template specialization.
2681 TypeLocBuilder TLB;
2682 TemplateSpecializationTypeLoc SpecTL
2683 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002684 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002685 SpecTL.setTemplateNameLoc(TemplateLoc);
2686 SpecTL.setLAngleLoc(LAngleLoc);
2687 SpecTL.setRAngleLoc(RAngleLoc);
2688 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2689 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002690
Douglas Gregore7c20652011-03-02 00:47:37 +00002691 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002692 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002693 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2694 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002695 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002696 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2697 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002698}
2699
Larisse Voufo39a1e502013-08-06 01:03:05 +00002700static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2701 NamedDecl *PrevDecl,
2702 SourceLocation Loc,
2703 bool IsPartialSpecialization);
2704
2705static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002706
Richard Smith300e0c32013-09-24 04:49:23 +00002707static bool isTemplateArgumentTemplateParameter(
2708 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2709 switch (Arg.getKind()) {
2710 case TemplateArgument::Null:
2711 case TemplateArgument::NullPtr:
2712 case TemplateArgument::Integral:
2713 case TemplateArgument::Declaration:
2714 case TemplateArgument::Pack:
2715 case TemplateArgument::TemplateExpansion:
2716 return false;
2717
2718 case TemplateArgument::Type: {
2719 QualType Type = Arg.getAsType();
2720 const TemplateTypeParmType *TPT =
2721 Arg.getAsType()->getAs<TemplateTypeParmType>();
2722 return TPT && !Type.hasQualifiers() &&
2723 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2724 }
2725
2726 case TemplateArgument::Expression: {
2727 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2728 if (!DRE || !DRE->getDecl())
2729 return false;
2730 const NonTypeTemplateParmDecl *NTTP =
2731 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2732 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2733 }
2734
2735 case TemplateArgument::Template:
2736 const TemplateTemplateParmDecl *TTP =
2737 dyn_cast_or_null<TemplateTemplateParmDecl>(
2738 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2739 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2740 }
2741 llvm_unreachable("unexpected kind of template argument");
2742}
2743
2744static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2745 ArrayRef<TemplateArgument> Args) {
2746 if (Params->size() != Args.size())
2747 return false;
2748
2749 unsigned Depth = Params->getDepth();
2750
2751 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2752 TemplateArgument Arg = Args[I];
2753
2754 // If the parameter is a pack expansion, the argument must be a pack
2755 // whose only element is a pack expansion.
2756 if (Params->getParam(I)->isParameterPack()) {
2757 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2758 !Arg.pack_begin()->isPackExpansion())
2759 return false;
2760 Arg = Arg.pack_begin()->getPackExpansionPattern();
2761 }
2762
2763 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2764 return false;
2765 }
2766
2767 return true;
2768}
2769
Richard Smith4b55a9c2014-04-17 03:29:33 +00002770/// Convert the parser's template argument list representation into our form.
2771static TemplateArgumentListInfo
2772makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2773 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2774 TemplateId.RAngleLoc);
2775 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2776 TemplateId.NumArgs);
2777 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2778 return TemplateArgs;
2779}
2780
Richard Smith0e617ec2016-12-27 07:56:27 +00002781template<typename PartialSpecDecl>
2782static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
2783 if (Partial->getDeclContext()->isDependentContext())
2784 return;
2785
2786 // FIXME: Get the TDK from deduction in order to provide better diagnostics
2787 // for non-substitution-failure issues?
2788 TemplateDeductionInfo Info(Partial->getLocation());
2789 if (S.isMoreSpecializedThanPrimary(Partial, Info))
2790 return;
2791
2792 auto *Template = Partial->getSpecializedTemplate();
2793 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00002794 diag::ext_partial_spec_not_more_specialized_than_primary)
2795 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00002796
2797 if (Info.hasSFINAEDiagnostic()) {
2798 PartialDiagnosticAt Diag = {SourceLocation(),
2799 PartialDiagnostic::NullDiagnostic()};
2800 Info.takeSFINAEDiagnostic(Diag);
2801 SmallString<128> SFINAEArgString;
2802 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
2803 S.Diag(Diag.first,
2804 diag::note_partial_spec_not_more_specialized_than_primary)
2805 << SFINAEArgString;
2806 }
2807
2808 S.Diag(Template->getLocation(), diag::note_template_decl_here);
2809}
2810
Richard Smith57aae072016-12-28 02:37:25 +00002811template<typename PartialSpecDecl>
2812static void checkTemplatePartialSpecialization(Sema &S,
2813 PartialSpecDecl *Partial) {
2814 // C++1z [temp.class.spec]p8: (DR1495)
2815 // - The specialization shall be more specialized than the primary
2816 // template (14.5.5.2).
2817 checkMoreSpecializedThanPrimary(S, Partial);
2818
2819 // C++ [temp.class.spec]p8: (DR1315)
2820 // - Each template-parameter shall appear at least once in the
2821 // template-id outside a non-deduced context.
2822 // C++1z [temp.class.spec.match]p3 (P0127R2)
2823 // If the template arguments of a partial specialization cannot be
2824 // deduced because of the structure of its template-parameter-list
2825 // and the template-id, the program is ill-formed.
2826 auto *TemplateParams = Partial->getTemplateParameters();
2827 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2828 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2829 TemplateParams->getDepth(), DeducibleParams);
2830
2831 if (!DeducibleParams.all()) {
2832 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
2833 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
2834 << isa<VarTemplatePartialSpecializationDecl>(Partial)
2835 << (NumNonDeducible > 1)
2836 << SourceRange(Partial->getLocation(),
2837 Partial->getTemplateArgsAsWritten()->RAngleLoc);
2838 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2839 if (!DeducibleParams[I]) {
2840 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2841 if (Param->getDeclName())
2842 S.Diag(Param->getLocation(),
2843 diag::note_partial_spec_unused_parameter)
2844 << Param->getDeclName();
2845 else
2846 S.Diag(Param->getLocation(),
2847 diag::note_partial_spec_unused_parameter)
2848 << "(anonymous)";
2849 }
2850 }
2851 }
2852}
2853
2854void Sema::CheckTemplatePartialSpecialization(
2855 ClassTemplatePartialSpecializationDecl *Partial) {
2856 checkTemplatePartialSpecialization(*this, Partial);
2857}
2858
2859void Sema::CheckTemplatePartialSpecialization(
2860 VarTemplatePartialSpecializationDecl *Partial) {
2861 checkTemplatePartialSpecialization(*this, Partial);
2862}
2863
Larisse Voufo39a1e502013-08-06 01:03:05 +00002864DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002865 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002866 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002867 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002868 // D must be variable template id.
2869 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2870 "Variable template specialization is declared with a template it.");
2871
2872 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002873 TemplateArgumentListInfo TemplateArgs =
2874 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002875 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2876 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2877 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002878
Richard Smithbeef3452014-01-16 23:39:20 +00002879 TemplateName Name = TemplateId->Template.get();
2880
2881 // The template-id must name a variable template.
2882 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002883 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2884 if (!VarTemplate) {
2885 NamedDecl *FnTemplate;
2886 if (auto *OTS = Name.getAsOverloadedTemplate())
2887 FnTemplate = *OTS->begin();
2888 else
2889 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2890 if (FnTemplate)
2891 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2892 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002893 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2894 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002895 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002896
2897 // Check for unexpanded parameter packs in any of the template arguments.
2898 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2899 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2900 UPPC_PartialSpecialization))
2901 return true;
2902
2903 // Check that the template argument list is well-formed for this
2904 // template.
2905 SmallVector<TemplateArgument, 4> Converted;
2906 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2907 false, Converted))
2908 return true;
2909
Larisse Voufo39a1e502013-08-06 01:03:05 +00002910 // Find the variable template (partial) specialization declaration that
2911 // corresponds to these arguments.
2912 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00002913 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
2914 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002915 return true;
2916
Richard Smith57aae072016-12-28 02:37:25 +00002917 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
2918 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002919 bool InstantiationDependent;
2920 if (!Name.isDependent() &&
2921 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00002922 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00002923 InstantiationDependent)) {
2924 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2925 << VarTemplate->getDeclName();
2926 IsPartialSpecialization = false;
2927 }
Richard Smith300e0c32013-09-24 04:49:23 +00002928
2929 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2930 Converted)) {
2931 // C++ [temp.class.spec]p9b3:
2932 //
2933 // -- The argument list of the specialization shall not be identical
2934 // to the implicit argument list of the primary template.
2935 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2936 << /*variable template*/ 1
2937 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2938 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2939 // FIXME: Recover from this by treating the declaration as a redeclaration
2940 // of the primary template.
2941 return true;
2942 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002943 }
2944
Craig Topperc3ec1492014-05-26 06:22:03 +00002945 void *InsertPos = nullptr;
2946 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002947
2948 if (IsPartialSpecialization)
2949 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002950 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002951 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002952 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002953
Craig Topperc3ec1492014-05-26 06:22:03 +00002954 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002955
2956 // Check whether we can declare a variable template specialization in
2957 // the current scope.
2958 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2959 TemplateNameLoc,
2960 IsPartialSpecialization))
2961 return true;
2962
2963 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2964 // Since the only prior variable template specialization with these
2965 // arguments was referenced but not declared, reuse that
2966 // declaration node as our own, updating its source location and
2967 // the list of outer template parameters to reflect our new declaration.
2968 Specialization = PrevDecl;
2969 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002970 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002971 } else if (IsPartialSpecialization) {
2972 // Create a new class template partial specialization declaration node.
2973 VarTemplatePartialSpecializationDecl *PrevPartial =
2974 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002975 VarTemplatePartialSpecializationDecl *Partial =
2976 VarTemplatePartialSpecializationDecl::Create(
2977 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2978 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00002979 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002980
2981 if (!PrevPartial)
2982 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2983 Specialization = Partial;
2984
2985 // If we are providing an explicit specialization of a member variable
2986 // template specialization, make a note of that.
2987 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002988 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002989
Richard Smith57aae072016-12-28 02:37:25 +00002990 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002991 } else {
2992 // Create a new class template specialization declaration node for
2993 // this explicit specialization or friend declaration.
2994 Specialization = VarTemplateSpecializationDecl::Create(
2995 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00002996 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002997 Specialization->setTemplateArgsInfo(TemplateArgs);
2998
2999 if (!PrevDecl)
3000 VarTemplate->AddSpecialization(Specialization, InsertPos);
3001 }
3002
3003 // C++ [temp.expl.spec]p6:
3004 // If a template, a member template or the member of a class template is
3005 // explicitly specialized then that specialization shall be declared
3006 // before the first use of that specialization that would cause an implicit
3007 // instantiation to take place, in every translation unit in which such a
3008 // use occurs; no diagnostic is required.
3009 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3010 bool Okay = false;
3011 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3012 // Is there any previous explicit specialization declaration?
3013 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3014 Okay = true;
3015 break;
3016 }
3017 }
3018
3019 if (!Okay) {
3020 SourceRange Range(TemplateNameLoc, RAngleLoc);
3021 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3022 << Name << Range;
3023
3024 Diag(PrevDecl->getPointOfInstantiation(),
3025 diag::note_instantiation_required_here)
3026 << (PrevDecl->getTemplateSpecializationKind() !=
3027 TSK_ImplicitInstantiation);
3028 return true;
3029 }
3030 }
3031
3032 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3033 Specialization->setLexicalDeclContext(CurContext);
3034
3035 // Add the specialization into its lexical context, so that it can
3036 // be seen when iterating through the list of declarations in that
3037 // context. However, specializations are not found by name lookup.
3038 CurContext->addDecl(Specialization);
3039
3040 // Note that this is an explicit specialization.
3041 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3042
3043 if (PrevDecl) {
3044 // Check that this isn't a redefinition of this specialization,
3045 // merging with previous declarations.
3046 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3047 ForRedeclaration);
3048 PrevSpec.addDecl(PrevDecl);
3049 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003050 } else if (Specialization->isStaticDataMember() &&
3051 Specialization->isOutOfLine()) {
3052 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003053 }
3054
3055 // Link instantiations of static data members back to the template from
3056 // which they were instantiated.
3057 if (Specialization->isStaticDataMember())
3058 Specialization->setInstantiationOfStaticDataMember(
3059 VarTemplate->getTemplatedDecl(),
3060 Specialization->getSpecializationKind());
3061
3062 return Specialization;
3063}
3064
3065namespace {
3066/// \brief A partial specialization whose template arguments have matched
3067/// a given template-id.
3068struct PartialSpecMatchResult {
3069 VarTemplatePartialSpecializationDecl *Partial;
3070 TemplateArgumentList *Args;
3071};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003072} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003073
3074DeclResult
3075Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3076 SourceLocation TemplateNameLoc,
3077 const TemplateArgumentListInfo &TemplateArgs) {
3078 assert(Template && "A variable template id without template?");
3079
3080 // Check that the template argument list is well-formed for this template.
3081 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003082 if (CheckTemplateArgumentList(
3083 Template, TemplateNameLoc,
3084 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003085 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003086 return true;
3087
3088 // Find the variable template specialization declaration that
3089 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003090 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003091 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003092 Converted, InsertPos)) {
3093 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003094 // If we already have a variable template specialization, return it.
3095 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003096 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003097
3098 // This is the first time we have referenced this variable template
3099 // specialization. Create the canonical declaration and add it to
3100 // the set of specializations, based on the closest partial specialization
3101 // that it represents. That is,
3102 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3103 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003104 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003105 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3106 bool AmbiguousPartialSpec = false;
3107 typedef PartialSpecMatchResult MatchResult;
3108 SmallVector<MatchResult, 4> Matched;
3109 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003110 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3111 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003112
3113 // 1. Attempt to find the closest partial specialization that this
3114 // specializes, if any.
3115 // If any of the template arguments is dependent, then this is probably
3116 // a placeholder for an incomplete declarative context; which must be
3117 // complete by instantiation time. Thus, do not search through the partial
3118 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003119 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3120 // Perhaps better after unification of DeduceTemplateArguments() and
3121 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003122 bool InstantiationDependent = false;
3123 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3124 TemplateArgs, InstantiationDependent)) {
3125
3126 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3127 Template->getPartialSpecializations(PartialSpecs);
3128
3129 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3130 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3131 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3132
3133 if (TemplateDeductionResult Result =
3134 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3135 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003136 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003137 FailedCandidates.addCandidate().set(
3138 DeclAccessPair::make(Template, AS_public), Partial,
3139 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003140 (void)Result;
3141 } else {
3142 Matched.push_back(PartialSpecMatchResult());
3143 Matched.back().Partial = Partial;
3144 Matched.back().Args = Info.take();
3145 }
3146 }
3147
Larisse Voufo39a1e502013-08-06 01:03:05 +00003148 if (Matched.size() >= 1) {
3149 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3150 if (Matched.size() == 1) {
3151 // -- If exactly one matching specialization is found, the
3152 // instantiation is generated from that specialization.
3153 // We don't need to do anything for this.
3154 } else {
3155 // -- If more than one matching specialization is found, the
3156 // partial order rules (14.5.4.2) are used to determine
3157 // whether one of the specializations is more specialized
3158 // than the others. If none of the specializations is more
3159 // specialized than all of the other matching
3160 // specializations, then the use of the variable template is
3161 // ambiguous and the program is ill-formed.
3162 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3163 PEnd = Matched.end();
3164 P != PEnd; ++P) {
3165 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3166 PointOfInstantiation) ==
3167 P->Partial)
3168 Best = P;
3169 }
3170
3171 // Determine if the best partial specialization is more specialized than
3172 // the others.
3173 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3174 PEnd = Matched.end();
3175 P != PEnd; ++P) {
3176 if (P != Best && getMoreSpecializedPartialSpecialization(
3177 P->Partial, Best->Partial,
3178 PointOfInstantiation) != Best->Partial) {
3179 AmbiguousPartialSpec = true;
3180 break;
3181 }
3182 }
3183 }
3184
3185 // Instantiate using the best variable template partial specialization.
3186 InstantiationPattern = Best->Partial;
3187 InstantiationArgs = Best->Args;
3188 } else {
3189 // -- If no match is found, the instantiation is generated
3190 // from the primary template.
3191 // InstantiationPattern = Template->getTemplatedDecl();
3192 }
3193 }
3194
Larisse Voufo39a1e502013-08-06 01:03:05 +00003195 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00003196 // Note that we do not instantiate a definition until we see an odr-use
3197 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003198 // FIXME: LateAttrs et al.?
3199 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3200 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3201 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3202 if (!Decl)
3203 return true;
3204
3205 if (AmbiguousPartialSpec) {
3206 // Partial ordering did not produce a clear winner. Complain.
3207 Decl->setInvalidDecl();
3208 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3209 << Decl;
3210
3211 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00003212 for (MatchResult P : Matched)
3213 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3214 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3215 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003216 return true;
3217 }
3218
3219 if (VarTemplatePartialSpecializationDecl *D =
3220 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3221 Decl->setInstantiationOf(D, InstantiationArgs);
3222
Richard Smith6739a102016-05-05 00:56:12 +00003223 checkSpecializationVisibility(TemplateNameLoc, Decl);
3224
Larisse Voufo39a1e502013-08-06 01:03:05 +00003225 assert(Decl && "No variable template specialization?");
3226 return Decl;
3227}
3228
3229ExprResult
3230Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3231 const DeclarationNameInfo &NameInfo,
3232 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3233 const TemplateArgumentListInfo *TemplateArgs) {
3234
3235 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3236 *TemplateArgs);
3237 if (Decl.isInvalid())
3238 return ExprError();
3239
3240 VarDecl *Var = cast<VarDecl>(Decl.get());
3241 if (!Var->getTemplateSpecializationKind())
3242 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3243 NameInfo.getLoc());
3244
3245 // Build an ordinary singleton decl ref.
3246 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003247 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003248}
3249
John McCalldadc5752010-08-24 06:29:42 +00003250ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003251 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003252 LookupResult &R,
3253 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003254 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003255 // FIXME: Can we do any checking at this point? I guess we could check the
3256 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003257 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003258 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003259 // foo<int> could identify a single function unambiguously
3260 // This approach does NOT work, since f<int>(1);
3261 // gets resolved prior to resorting to overload resolution
3262 // i.e., template<class T> void f(double);
3263 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003264
3265 // These should be filtered out by our callers.
3266 assert(!R.empty() && "empty lookup results when building templateid");
3267 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3268
Larisse Voufo39a1e502013-08-06 01:03:05 +00003269 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003270 bool InstantiationDependent;
3271 if (R.getAsSingle<VarTemplateDecl>() &&
3272 !TemplateSpecializationType::anyDependentTemplateArguments(
3273 *TemplateArgs, InstantiationDependent)) {
3274 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3275 R.getAsSingle<VarTemplateDecl>(),
3276 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003277 }
3278
John McCall58cc69d2010-01-27 01:50:18 +00003279 // We don't want lookup warnings at this point.
3280 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003281
John McCalle66edc12009-11-24 19:00:30 +00003282 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003283 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003284 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003285 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003286 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003287 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003288 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003289
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003290 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003291}
3292
John McCalle66edc12009-11-24 19:00:30 +00003293// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003294ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003295Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003296 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003297 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003298 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003299
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003300 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003301 DeclContext *DC;
3302 if (!(DC = computeDeclContext(SS, false)) ||
3303 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003304 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003305 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003306
Douglas Gregor786123d2010-05-21 23:18:07 +00003307 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003308 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003309 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003310 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003311
John McCalle66edc12009-11-24 19:00:30 +00003312 if (R.isAmbiguous())
3313 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003314
John McCalle66edc12009-11-24 19:00:30 +00003315 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003316 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3317 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003318 return ExprError();
3319 }
3320
3321 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003322 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003323 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003324 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003325 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3326 return ExprError();
3327 }
3328
Abramo Bagnara7945c982012-01-27 09:46:47 +00003329 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003330}
3331
Douglas Gregorb67535d2009-03-31 00:43:58 +00003332/// \brief Form a dependent template name.
3333///
3334/// This action forms a dependent template name given the template
3335/// name and its (presumably dependent) scope specifier. For
3336/// example, given "MetaFun::template apply", the scope specifier \p
3337/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3338/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003339TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003340 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003341 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003342 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003343 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003344 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00003345 TemplateTy &Result,
3346 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003347 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3348 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003349 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003350 diag::warn_cxx98_compat_template_outside_of_template :
3351 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352 << FixItHint::CreateRemoval(TemplateKWLoc);
3353
Craig Topperc3ec1492014-05-26 06:22:03 +00003354 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003355 if (SS.isSet())
3356 LookupCtx = computeDeclContext(SS, EnteringContext);
3357 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003358 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003359 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003360 // C++0x [temp.names]p5:
3361 // If a name prefixed by the keyword template is not the name of
3362 // a template, the program is ill-formed. [Note: the keyword
3363 // template may not be applied to non-template members of class
3364 // templates. -end note ] [ Note: as is the case with the
3365 // typename prefix, the template prefix is allowed in cases
3366 // where it is not strictly necessary; i.e., when the
3367 // nested-name-specifier or the expression on the left of the ->
3368 // or . is not dependent on a template-parameter, or the use
3369 // does not appear in the scope of a template. -end note]
3370 //
3371 // Note: C++03 was more strict here, because it banned the use of
3372 // the "template" keyword prior to a template-name that was not a
3373 // dependent name. C++ DR468 relaxed this requirement (the
3374 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003375 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003376 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003377 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003378 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003379 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003380 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3381 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003382 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3383 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003384 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003385 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003386 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003387 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003388 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003389 << Name.getSourceRange()
3390 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003391 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003392 } else {
3393 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00003394 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
3395 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
3396 Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
3397 LookupRD->getIdentifier() == Name.Identifier) {
3398 // C++14 [class.qual]p2:
3399 // In a lookup in which function names are not ignored and the
3400 // nested-name-specifier nominates a class C, if the name specified
3401 // [...] is the injected-class-name of C, [...] the name is instead
3402 // considered to name the constructor
3403 //
3404 // We don't get here if naming the constructor would be valid, so we
3405 // just reject immediately and recover by treating the
3406 // injected-class-name as naming the template.
3407 Diag(Name.getLocStart(),
3408 diag::ext_out_of_line_qualified_id_type_names_constructor)
3409 << Name.Identifier << 0 /*injected-class-name used as template name*/
3410 << 1 /*'template' keyword was used*/;
3411 }
Douglas Gregorbb119652010-06-16 23:00:59 +00003412 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003413 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003414 }
3415
Aaron Ballman4a979672014-01-03 13:56:08 +00003416 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417
Douglas Gregor3cf81312009-11-03 23:16:33 +00003418 switch (Name.getKind()) {
3419 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003421 Name.Identifier));
3422 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003423
Douglas Gregor71395fa2009-11-04 00:56:37 +00003424 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003425 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003426 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003427 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003428
3429 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003430 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003431
Douglas Gregor3cf81312009-11-03 23:16:33 +00003432 default:
3433 break;
3434 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003436 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003437 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003438 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003439 << Name.getSourceRange()
3440 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003441 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003442}
3443
Mike Stump11289f42009-09-09 15:08:12 +00003444bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003445 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003446 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003447 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003448 QualType ArgType;
3449 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003450
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003451 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003452 switch(Arg.getKind()) {
3453 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003454 // C++ [temp.arg.type]p1:
3455 // A template-argument for a template-parameter which is a
3456 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003457 ArgType = Arg.getAsType();
3458 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003459 break;
3460 case TemplateArgument::Template: {
3461 // We have a template type parameter but the template argument
3462 // is a template without any arguments.
3463 SourceRange SR = AL.getSourceRange();
3464 TemplateName Name = Arg.getAsTemplate();
3465 Diag(SR.getBegin(), diag::err_template_missing_args)
Richard Smith0c062b42017-01-14 02:19:59 +00003466 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003467 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3468 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003469
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003470 return true;
3471 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003472 case TemplateArgument::Expression: {
3473 // We have a template type parameter but the template argument is an
3474 // expression; see if maybe it is missing the "typename" keyword.
3475 CXXScopeSpec SS;
3476 DeclarationNameInfo NameInfo;
3477
3478 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3479 SS.Adopt(ArgExpr->getQualifierLoc());
3480 NameInfo = ArgExpr->getNameInfo();
3481 } else if (DependentScopeDeclRefExpr *ArgExpr =
3482 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3483 SS.Adopt(ArgExpr->getQualifierLoc());
3484 NameInfo = ArgExpr->getNameInfo();
3485 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3486 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003487 if (ArgExpr->isImplicitAccess()) {
3488 SS.Adopt(ArgExpr->getQualifierLoc());
3489 NameInfo = ArgExpr->getMemberNameInfo();
3490 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003491 }
3492
Reid Kleckner377c1592014-06-10 23:29:48 +00003493 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003494 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3495 LookupParsedName(Result, CurScope, &SS);
3496
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003497 if (Result.getAsSingle<TypeDecl>() ||
3498 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003499 LookupResult::NotFoundInCurrentInstantiation) {
3500 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003501 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003502 Diag(Loc, getLangOpts().MSVCCompat
3503 ? diag::ext_ms_template_type_arg_missing_typename
3504 : diag::err_template_arg_must_be_type_suggest)
3505 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003506 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003507
3508 // Recover by synthesizing a type using the location information that we
3509 // already have.
3510 ArgType =
3511 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3512 TypeLocBuilder TLB;
3513 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3514 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3515 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3516 TL.setNameLoc(NameInfo.getLoc());
3517 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3518
3519 // Overwrite our input TemplateArgumentLoc so that we can recover
3520 // properly.
3521 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3522 TemplateArgumentLocInfo(TSI));
3523
3524 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003525 }
3526 }
3527 // fallthrough
3528 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003529 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003530 // We have a template type parameter but the template argument
3531 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003532 SourceRange SR = AL.getSourceRange();
3533 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003534 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003535
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003536 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003537 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003538 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003539
Reid Kleckner377c1592014-06-10 23:29:48 +00003540 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003541 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003542
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003543 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003544 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003545
Douglas Gregore46db902011-06-17 22:11:49 +00003546 // Objective-C ARC:
3547 // If an explicitly-specified template argument type is a lifetime type
3548 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003549 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003550 ArgType->isObjCLifetimeType() &&
3551 !ArgType.getObjCLifetime()) {
3552 Qualifiers Qs;
3553 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3554 ArgType = Context.getQualifiedType(ArgType, Qs);
3555 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003556
Douglas Gregore46db902011-06-17 22:11:49 +00003557 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003558 return false;
3559}
3560
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003561/// \brief Substitute template arguments into the default template argument for
3562/// the given template type parameter.
3563///
3564/// \param SemaRef the semantic analysis object for which we are performing
3565/// the substitution.
3566///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003567/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003568/// for.
3569///
3570/// \param TemplateLoc the location of the template name that started the
3571/// template-id we are checking.
3572///
3573/// \param RAngleLoc the location of the right angle bracket ('>') that
3574/// terminates the template-id.
3575///
3576/// \param Param the template template parameter whose default we are
3577/// substituting into.
3578///
3579/// \param Converted the list of template arguments provided for template
3580/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003581/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003582static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003583SubstDefaultTemplateArgument(Sema &SemaRef,
3584 TemplateDecl *Template,
3585 SourceLocation TemplateLoc,
3586 SourceLocation RAngleLoc,
3587 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003588 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003589 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003590
3591 // If the argument type is dependent, instantiate it now based
3592 // on the previously-computed template arguments.
3593 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003594 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003595 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003596 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003597 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003598 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599
David Majnemer8b622692016-07-03 21:17:51 +00003600 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003601
3602 // Only substitute for the innermost template argument list.
3603 MultiLevelTemplateArgumentList TemplateArgLists;
3604 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3605 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3606 TemplateArgLists.addOuterTemplateArguments(None);
3607
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003608 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003609 ArgType =
3610 SemaRef.SubstType(ArgType, TemplateArgLists,
3611 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003612 }
3613
3614 return ArgType;
3615}
3616
3617/// \brief Substitute template arguments into the default template argument for
3618/// the given non-type template parameter.
3619///
3620/// \param SemaRef the semantic analysis object for which we are performing
3621/// the substitution.
3622///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003623/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003624/// for.
3625///
3626/// \param TemplateLoc the location of the template name that started the
3627/// template-id we are checking.
3628///
3629/// \param RAngleLoc the location of the right angle bracket ('>') that
3630/// terminates the template-id.
3631///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003632/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003633/// substituting into.
3634///
3635/// \param Converted the list of template arguments provided for template
3636/// parameters that precede \p Param in the template parameter list.
3637///
3638/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003639static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003640SubstDefaultTemplateArgument(Sema &SemaRef,
3641 TemplateDecl *Template,
3642 SourceLocation TemplateLoc,
3643 SourceLocation RAngleLoc,
3644 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003645 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003646 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003647 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003648 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003649 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003650 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003651
David Majnemer8b622692016-07-03 21:17:51 +00003652 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003653
3654 // Only substitute for the innermost template argument list.
3655 MultiLevelTemplateArgumentList TemplateArgLists;
3656 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3657 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3658 TemplateArgLists.addOuterTemplateArguments(None);
3659
Faisal Vali48401eb2015-11-19 19:20:17 +00003660 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3661 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003662 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003663}
3664
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003665/// \brief Substitute template arguments into the default template argument for
3666/// the given template template parameter.
3667///
3668/// \param SemaRef the semantic analysis object for which we are performing
3669/// the substitution.
3670///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003672/// for.
3673///
3674/// \param TemplateLoc the location of the template name that started the
3675/// template-id we are checking.
3676///
3677/// \param RAngleLoc the location of the right angle bracket ('>') that
3678/// terminates the template-id.
3679///
3680/// \param Param the template template parameter whose default we are
3681/// substituting into.
3682///
3683/// \param Converted the list of template arguments provided for template
3684/// parameters that precede \p Param in the template parameter list.
3685///
Simon Pilgrim6905d222016-12-30 22:55:33 +00003686/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00003687/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003688///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003689/// \returns the substituted template argument, or NULL if an error occurred.
3690static TemplateName
3691SubstDefaultTemplateArgument(Sema &SemaRef,
3692 TemplateDecl *Template,
3693 SourceLocation TemplateLoc,
3694 SourceLocation RAngleLoc,
3695 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003696 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003697 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00003698 Sema::InstantiatingTemplate Inst(
3699 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
3700 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003701 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003702 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003703
David Majnemer8b622692016-07-03 21:17:51 +00003704 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003705
3706 // Only substitute for the innermost template argument list.
3707 MultiLevelTemplateArgumentList TemplateArgLists;
3708 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3709 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3710 TemplateArgLists.addOuterTemplateArguments(None);
3711
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003712 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003713 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003714 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003715 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003716 QualifierLoc =
3717 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003718 if (!QualifierLoc)
3719 return TemplateName();
3720 }
David Majnemer89189202013-08-28 23:48:32 +00003721
3722 return SemaRef.SubstTemplateName(
3723 QualifierLoc,
3724 Param->getDefaultArgument().getArgument().getAsTemplate(),
3725 Param->getDefaultArgument().getTemplateNameLoc(),
3726 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003727}
3728
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003729/// \brief If the given template parameter has a default template
3730/// argument, substitute into that default template argument and
3731/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003733Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3734 SourceLocation TemplateLoc,
3735 SourceLocation RAngleLoc,
3736 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003737 SmallVectorImpl<TemplateArgument>
3738 &Converted,
3739 bool &HasDefaultArg) {
3740 HasDefaultArg = false;
3741
3742 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003743 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003744 return TemplateArgumentLoc();
3745
Richard Smithc87b9382013-07-04 01:01:24 +00003746 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003747 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003748 TemplateLoc,
3749 RAngleLoc,
3750 TypeParm,
3751 Converted);
3752 if (DI)
3753 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3754
3755 return TemplateArgumentLoc();
3756 }
3757
3758 if (NonTypeTemplateParmDecl *NonTypeParm
3759 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003760 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003761 return TemplateArgumentLoc();
3762
Richard Smithc87b9382013-07-04 01:01:24 +00003763 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003764 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003765 TemplateLoc,
3766 RAngleLoc,
3767 NonTypeParm,
3768 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003769 if (Arg.isInvalid())
3770 return TemplateArgumentLoc();
3771
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003772 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003773 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3774 }
3775
3776 TemplateTemplateParmDecl *TempTempParm
3777 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003778 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003779 return TemplateArgumentLoc();
3780
Richard Smithc87b9382013-07-04 01:01:24 +00003781 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003782 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003783 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003784 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003785 RAngleLoc,
3786 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003787 Converted,
3788 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003789 if (TName.isNull())
3790 return TemplateArgumentLoc();
3791
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003792 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003793 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003794 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3795}
3796
Richard Smith11255ec2017-01-18 19:19:22 +00003797/// Convert a template-argument that we parsed as a type into a template, if
3798/// possible. C++ permits injected-class-names to perform dual service as
3799/// template template arguments and as template type arguments.
3800static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
3801 // Extract and step over any surrounding nested-name-specifier.
3802 NestedNameSpecifierLoc QualLoc;
3803 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
3804 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
3805 return TemplateArgumentLoc();
3806
3807 QualLoc = ETLoc.getQualifierLoc();
3808 TLoc = ETLoc.getNamedTypeLoc();
3809 }
3810
3811 // If this type was written as an injected-class-name, it can be used as a
3812 // template template argument.
3813 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
3814 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
3815 QualLoc, InjLoc.getNameLoc());
3816
3817 // If this type was written as an injected-class-name, it may have been
3818 // converted to a RecordType during instantiation. If the RecordType is
3819 // *not* wrapped in a TemplateSpecializationType and denotes a class
3820 // template specialization, it must have come from an injected-class-name.
3821 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
3822 if (auto *CTSD =
3823 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
3824 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
3825 QualLoc, RecLoc.getNameLoc());
3826
3827 return TemplateArgumentLoc();
3828}
3829
Douglas Gregorda0fb532009-11-11 19:31:23 +00003830/// \brief Check that the given template argument corresponds to the given
3831/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003832///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003833/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003834/// checked.
3835///
Richard Trieu15b66532015-01-24 02:48:32 +00003836/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003837///
3838/// \param Template The template in which the template argument resides.
3839///
3840/// \param TemplateLoc The location of the template name for the template
3841/// whose argument list we're matching.
3842///
3843/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3844/// the template argument list.
3845///
3846/// \param ArgumentPackIndex The index into the argument pack where this
3847/// argument will be placed. Only valid if the parameter is a parameter pack.
3848///
3849/// \param Converted The checked, converted argument will be added to the
3850/// end of this small vector.
3851///
3852/// \param CTAK Describes how we arrived at this particular template argument:
3853/// explicitly written, deduced, etc.
3854///
3855/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003856bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003857 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003858 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003859 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003860 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003861 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003862 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003863 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003864 // Check template type parameters.
3865 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003866 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003867
Douglas Gregoreebed722009-11-11 19:41:09 +00003868 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003869 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003870 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003871 // with the template arguments we've seen thus far. But if the
3872 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003873 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003874 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3875 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003876
Peter Collingbourne01687632010-12-10 17:08:53 +00003877 if (NTTPType->isDependentType() &&
3878 !isa<TemplateTemplateParmDecl>(Template) &&
3879 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003880 // Do substitution on the type of the non-type template parameter.
3881 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003882 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003883 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003884 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003885 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003886
3887 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003888 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003889 NTTPType = SubstType(NTTPType,
3890 MultiLevelTemplateArgumentList(TemplateArgs),
3891 NTTP->getLocation(),
3892 NTTP->getDeclName());
3893 // If that worked, check the non-type template parameter type
3894 // for validity.
3895 if (!NTTPType.isNull())
3896 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3897 NTTP->getLocation());
3898 if (NTTPType.isNull())
3899 return true;
3900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003901
Douglas Gregorda0fb532009-11-11 19:31:23 +00003902 switch (Arg.getArgument().getKind()) {
3903 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003904 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003905
Douglas Gregorda0fb532009-11-11 19:31:23 +00003906 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003907 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003908 ExprResult Res =
3909 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3910 Result, CTAK);
3911 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003912 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003913
Richard Trieu15b66532015-01-24 02:48:32 +00003914 // If the resulting expression is new, then use it in place of the
3915 // old expression in the template argument.
3916 if (Res.get() != Arg.getArgument().getAsExpr()) {
3917 TemplateArgument TA(Res.get());
3918 Arg = TemplateArgumentLoc(TA, Res.get());
3919 }
3920
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003921 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003922 break;
3923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003924
Douglas Gregorda0fb532009-11-11 19:31:23 +00003925 case TemplateArgument::Declaration:
3926 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003927 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003928 // We've already checked this template argument, so just copy
3929 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003930 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003931 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003932
Douglas Gregorda0fb532009-11-11 19:31:23 +00003933 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003934 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003935 // We were given a template template argument. It may not be ill-formed;
3936 // see below.
3937 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003938 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3939 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003940 // We have a template argument such as \c T::template X, which we
3941 // parsed as a template template argument. However, since we now
3942 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003943 // template name into an expression.
3944
3945 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3946 Arg.getTemplateNameLoc());
3947
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003948 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003949 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003950 // FIXME: the template-template arg was a DependentTemplateName,
3951 // so it was provided with a template keyword. However, its source
3952 // location is not stored in the template argument structure.
3953 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003954 ExprResult E = DependentScopeDeclRefExpr::Create(
3955 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3956 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003957
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003958 // If we parsed the template argument as a pack expansion, create a
3959 // pack expansion expression.
3960 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003961 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003962 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003963 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003965
Douglas Gregorda0fb532009-11-11 19:31:23 +00003966 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003967 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003968 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003969 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003970
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003971 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003972 break;
3973 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003974
Douglas Gregorda0fb532009-11-11 19:31:23 +00003975 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003976 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003977 // therefore cannot be a non-type template argument.
3978 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3979 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003980
Douglas Gregorda0fb532009-11-11 19:31:23 +00003981 Diag(Param->getLocation(), diag::note_template_param_here);
3982 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003983
Douglas Gregorda0fb532009-11-11 19:31:23 +00003984 case TemplateArgument::Type: {
3985 // We have a non-type template parameter but the template
3986 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003987
Douglas Gregorda0fb532009-11-11 19:31:23 +00003988 // C++ [temp.arg]p2:
3989 // In a template-argument, an ambiguity between a type-id and
3990 // an expression is resolved to a type-id, regardless of the
3991 // form of the corresponding template-parameter.
3992 //
3993 // We warn specifically about this case, since it can be rather
3994 // confusing for users.
3995 QualType T = Arg.getArgument().getAsType();
3996 SourceRange SR = Arg.getSourceRange();
3997 if (T->isFunctionType())
3998 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3999 else
4000 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4001 Diag(Param->getLocation(), diag::note_template_param_here);
4002 return true;
4003 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004004
Douglas Gregorda0fb532009-11-11 19:31:23 +00004005 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004006 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004008
Douglas Gregorda0fb532009-11-11 19:31:23 +00004009 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004010 }
4011
4012
Douglas Gregorda0fb532009-11-11 19:31:23 +00004013 // Check template template parameters.
4014 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004015
Douglas Gregorda0fb532009-11-11 19:31:23 +00004016 // Substitute into the template parameter list of the template
4017 // template parameter, since previously-supplied template arguments
4018 // may appear within the template template parameter.
4019 {
4020 // Set up a template instantiation context.
4021 LocalInstantiationScope Scope(*this);
4022 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004023 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004024 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004025 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004026 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004027
David Majnemer8b622692016-07-03 21:17:51 +00004028 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004029 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004030 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004031 MultiLevelTemplateArgumentList(TemplateArgs)));
4032 if (!TempParm)
4033 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004034 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004035
Richard Smith11255ec2017-01-18 19:19:22 +00004036 // C++1z [temp.local]p1: (DR1004)
4037 // When [the injected-class-name] is used [...] as a template-argument for
4038 // a template template-parameter [...] it refers to the class template
4039 // itself.
4040 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4041 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4042 Arg.getTypeSourceInfo()->getTypeLoc());
4043 if (!ConvertedArg.getArgument().isNull())
4044 Arg = ConvertedArg;
4045 }
4046
Douglas Gregorda0fb532009-11-11 19:31:23 +00004047 switch (Arg.getArgument().getKind()) {
4048 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004049 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050
Douglas Gregorda0fb532009-11-11 19:31:23 +00004051 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004052 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00004053 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004054 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004055
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004056 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004057 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004058
Douglas Gregorda0fb532009-11-11 19:31:23 +00004059 case TemplateArgument::Expression:
4060 case TemplateArgument::Type:
4061 // We have a template template parameter but the template
4062 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004063 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004064 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004065 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004066
Douglas Gregorda0fb532009-11-11 19:31:23 +00004067 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004068 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004069 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004070 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004071 case TemplateArgument::NullPtr:
4072 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004073
Douglas Gregorda0fb532009-11-11 19:31:23 +00004074 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004075 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004076 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004077
Douglas Gregorda0fb532009-11-11 19:31:23 +00004078 return false;
4079}
4080
Simon Pilgrim6905d222016-12-30 22:55:33 +00004081/// \brief Diagnose an arity mismatch in the
Douglas Gregor8e072612012-02-03 07:34:46 +00004082static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4083 SourceLocation TemplateLoc,
4084 TemplateArgumentListInfo &TemplateArgs) {
4085 TemplateParameterList *Params = Template->getTemplateParameters();
4086 unsigned NumParams = Params->size();
4087 unsigned NumArgs = TemplateArgs.size();
4088
4089 SourceRange Range;
4090 if (NumArgs > NumParams)
Simon Pilgrim6905d222016-12-30 22:55:33 +00004091 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
Douglas Gregor8e072612012-02-03 07:34:46 +00004092 TemplateArgs.getRAngleLoc());
4093 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4094 << (NumArgs > NumParams)
Richard Smith0c062b42017-01-14 02:19:59 +00004095 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
Douglas Gregor8e072612012-02-03 07:34:46 +00004096 << Template << Range;
4097 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4098 << Params->getSourceRange();
4099 return true;
4100}
4101
Richard Smith1fde8ec2012-09-07 02:06:42 +00004102/// \brief Check whether the template parameter is a pack expansion, and if so,
4103/// determine the number of parameters produced by that expansion. For instance:
4104///
4105/// \code
4106/// template<typename ...Ts> struct A {
4107/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4108/// };
4109/// \endcode
4110///
4111/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4112/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004113static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004114 if (NonTypeTemplateParmDecl *NTTP
4115 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4116 if (NTTP->isExpandedParameterPack())
4117 return NTTP->getNumExpansionTypes();
4118 }
4119
4120 if (TemplateTemplateParmDecl *TTP
4121 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4122 if (TTP->isExpandedParameterPack())
4123 return TTP->getNumExpansionTemplateParameters();
4124 }
4125
David Blaikie7a30dc52013-02-21 01:47:18 +00004126 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00004127}
4128
Richard Smith35c1df52015-06-17 20:16:32 +00004129/// Diagnose a missing template argument.
4130template<typename TemplateParmDecl>
4131static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4132 TemplateDecl *TD,
4133 const TemplateParmDecl *D,
4134 TemplateArgumentListInfo &Args) {
4135 // Dig out the most recent declaration of the template parameter; there may be
4136 // declarations of the template that are more recent than TD.
4137 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4138 ->getTemplateParameters()
4139 ->getParam(D->getIndex()));
4140
4141 // If there's a default argument that's not visible, diagnose that we're
4142 // missing a module import.
4143 llvm::SmallVector<Module*, 8> Modules;
4144 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4145 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4146 D->getDefaultArgumentLoc(), Modules,
4147 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00004148 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00004149 return true;
4150 }
4151
4152 // FIXME: If there's a more recent default argument that *is* visible,
4153 // diagnose that it was declared too late.
4154
4155 return diagnoseArityMismatch(S, TD, Loc, Args);
4156}
4157
Douglas Gregord32e0282009-02-09 23:23:08 +00004158/// \brief Check that the given template argument list is well-formed
4159/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00004160bool Sema::CheckTemplateArgumentList(
4161 TemplateDecl *Template, SourceLocation TemplateLoc,
4162 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4163 SmallVectorImpl<TemplateArgument> &Converted,
4164 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00004165 // Make a copy of the template arguments for processing. Only make the
4166 // changes at the end when successful in matching the arguments to the
4167 // template.
4168 TemplateArgumentListInfo NewArgs = TemplateArgs;
4169
Douglas Gregord32e0282009-02-09 23:23:08 +00004170 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00004171
Richard Trieu15b66532015-01-24 02:48:32 +00004172 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00004173
Mike Stump11289f42009-09-09 15:08:12 +00004174 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00004175 // [...] The type and form of each template-argument specified in
4176 // a template-id shall match the type and form specified for the
4177 // corresponding parameter declared by the template in its
4178 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00004179 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004180 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00004181 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00004182 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00004183 for (TemplateParameterList::iterator Param = Params->begin(),
4184 ParamEnd = Params->end();
4185 Param != ParamEnd; /* increment in loop */) {
4186 // If we have an expanded parameter pack, make sure we don't have too
4187 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00004188 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004189 if (*Expansions == ArgumentPack.size()) {
4190 // We're done with this parameter pack. Pack up its arguments and add
4191 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00004192 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00004193 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004194 ArgumentPack.clear();
4195
Richard Smith1fde8ec2012-09-07 02:06:42 +00004196 // This argument is assigned to the next parameter.
4197 ++Param;
4198 continue;
4199 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4200 // Not enough arguments for this parameter pack.
4201 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4202 << false
Richard Smith0c062b42017-01-14 02:19:59 +00004203 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00004204 << Template;
4205 Diag(Template->getLocation(), diag::note_template_decl_here)
4206 << Params->getSourceRange();
4207 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004208 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004210
Richard Smith1fde8ec2012-09-07 02:06:42 +00004211 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00004212 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00004213 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004214 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004215 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00004216 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004217
Richard Smith96d71c32014-11-12 23:38:38 +00004218 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00004219 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00004220 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4221 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00004222 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00004223 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00004224 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00004225 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00004226 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00004227 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00004228 Diag((*Param)->getLocation(), diag::note_template_param_here);
4229 return true;
4230 }
4231
Richard Smith1fde8ec2012-09-07 02:06:42 +00004232 // We're now done with this argument.
4233 ++ArgIdx;
4234
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004235 if ((*Param)->isTemplateParameterPack()) {
4236 // The template parameter was a template parameter pack, so take the
4237 // deduced argument and place it on the argument pack. Note that we
4238 // stay on the same template parameter so that we can deduce more
4239 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004240 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004241 } else {
4242 // Move to the next template parameter.
4243 ++Param;
4244 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004245
Richard Smith96d71c32014-11-12 23:38:38 +00004246 // If we just saw a pack expansion into a non-pack, then directly convert
4247 // the remaining arguments, because we don't know what parameters they'll
4248 // match up with.
4249 if (PackExpansionIntoNonPack) {
4250 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004251 // If we were part way through filling in an expanded parameter pack,
4252 // fall back to just producing individual arguments.
4253 Converted.insert(Converted.end(),
4254 ArgumentPack.begin(), ArgumentPack.end());
4255 ArgumentPack.clear();
4256 }
4257
4258 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00004259 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00004260 ++ArgIdx;
4261 }
4262
Richard Smith1fde8ec2012-09-07 02:06:42 +00004263 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00004264 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004265
Douglas Gregor84d49a22009-11-11 21:54:23 +00004266 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
Douglas Gregor2f157c92011-06-03 02:59:40 +00004269 // If we're checking a partial template argument list, we're done.
4270 if (PartialTemplateArgs) {
4271 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00004272 Converted.push_back(
4273 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4274
Richard Smith1fde8ec2012-09-07 02:06:42 +00004275 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00004276 }
4277
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004279 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00004280 if ((*Param)->isTemplateParameterPack()) {
4281 assert(!getExpandedPackSize(*Param) &&
4282 "Should have dealt with this already");
4283
4284 // A non-expanded parameter pack before the end of the parameter list
4285 // only occurs for an ill-formed template parameter list, unless we've
4286 // got a partial argument list for a function template, so just bail out.
4287 if (Param + 1 != ParamEnd)
4288 return true;
4289
Benjamin Kramercce63472015-08-05 09:40:22 +00004290 Converted.push_back(
4291 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004292 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00004293
4294 ++Param;
4295 continue;
4296 }
4297
Douglas Gregor8e072612012-02-03 07:34:46 +00004298 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00004299 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004300
Douglas Gregor84d49a22009-11-11 21:54:23 +00004301 // Retrieve the default template argument from the template
4302 // parameter. For each kind of template parameter, we substitute the
4303 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004304 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004305 // the default argument.
4306 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004307 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004308 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4309 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004310
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004311 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004312 Template,
4313 TemplateLoc,
4314 RAngleLoc,
4315 TTP,
4316 Converted);
4317 if (!ArgType)
4318 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319
Douglas Gregor84d49a22009-11-11 21:54:23 +00004320 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4321 ArgType);
4322 } else if (NonTypeTemplateParmDecl *NTTP
4323 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004324 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004325 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4326 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004327
John McCalldadc5752010-08-24 06:29:42 +00004328 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004329 TemplateLoc,
4330 RAngleLoc,
4331 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004332 Converted);
4333 if (E.isInvalid())
4334 return true;
4335
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004336 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004337 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4338 } else {
4339 TemplateTemplateParmDecl *TempParm
4340 = cast<TemplateTemplateParmDecl>(*Param);
4341
Richard Smith95d83952015-06-10 20:36:34 +00004342 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004343 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4344 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004345
Douglas Gregordf846d12011-03-02 18:46:51 +00004346 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004347 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348 TemplateLoc,
4349 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004350 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004351 Converted,
4352 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004353 if (Name.isNull())
4354 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004355
Douglas Gregor9d802122011-03-02 17:09:35 +00004356 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4357 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004358 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004359
Douglas Gregor84d49a22009-11-11 21:54:23 +00004360 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00004361 // the default template argument. We're not actually instantiating a
4362 // template here, we just create this object to put a note into the
4363 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004364 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4365 SourceRange(TemplateLoc, RAngleLoc));
4366 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004367 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004368
Douglas Gregor84d49a22009-11-11 21:54:23 +00004369 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004370 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004371 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004372 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004373
Richard Trieu15b66532015-01-24 02:48:32 +00004374 // Core issue 150 (assumed resolution): if this is a template template
4375 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004376 // template definition.
4377 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004378 NewArgs.addArgument(Arg);
4379
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004380 // Move to the next template parameter and argument.
4381 ++Param;
4382 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004384
Richard Smith07f79912014-06-06 16:00:50 +00004385 // If we're performing a partial argument substitution, allow any trailing
4386 // pack expansions; they might be empty. This can happen even if
4387 // PartialTemplateArgs is false (the list of arguments is complete but
4388 // still dependent).
4389 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4390 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004391 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4392 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004393 }
4394
Douglas Gregor8e072612012-02-03 07:34:46 +00004395 // If we have any leftover arguments, then there were too many arguments.
4396 // Complain and fail.
4397 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004398 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4399
4400 // No problems found with the new argument list, propagate changes back
4401 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00004402 if (UpdateArgsWithConversions)
4403 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004404
Richard Smith1fde8ec2012-09-07 02:06:42 +00004405 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004406}
4407
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004408namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004409 class UnnamedLocalNoLinkageFinder
4410 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004411 {
4412 Sema &S;
4413 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004414
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004415 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004416
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004417 public:
4418 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4419
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004420 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00004421 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004424#define TYPE(Class, Parent) \
4425 bool Visit##Class##Type(const Class##Type *);
4426#define ABSTRACT_TYPE(Class, Parent) \
4427 bool Visit##Class##Type(const Class##Type *) { return false; }
4428#define NON_CANONICAL_TYPE(Class, Parent) \
4429 bool Visit##Class##Type(const Class##Type *) { return false; }
4430#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004432 bool VisitTagDecl(const TagDecl *Tag);
4433 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4434 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004435} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004436
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004437bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004438 return false;
4439}
4440
4441bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4442 return Visit(T->getElementType());
4443}
4444
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004445bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004446 return Visit(T->getPointeeType());
4447}
4448
4449bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004450 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004451 return Visit(T->getPointeeType());
4452}
4453
4454bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004455 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004456 return Visit(T->getPointeeType());
4457}
4458
4459bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004461 return Visit(T->getPointeeType());
4462}
4463
4464bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004465 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004466 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4467}
4468
4469bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004470 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004471 return Visit(T->getElementType());
4472}
4473
4474bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004476 return Visit(T->getElementType());
4477}
4478
4479bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004480 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004481 return Visit(T->getElementType());
4482}
4483
4484bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004486 return Visit(T->getElementType());
4487}
4488
4489bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004490 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004491 return Visit(T->getElementType());
4492}
4493
4494bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4495 return Visit(T->getElementType());
4496}
4497
4498bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4499 return Visit(T->getElementType());
4500}
4501
4502bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4503 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004504 for (const auto &A : T->param_types()) {
4505 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004506 return true;
4507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004508
Alp Toker314cc812014-01-25 16:55:45 +00004509 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004510}
4511
4512bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4513 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004514 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004515}
4516
4517bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4518 const UnresolvedUsingType*) {
4519 return false;
4520}
4521
4522bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4523 return false;
4524}
4525
4526bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4527 return Visit(T->getUnderlyingType());
4528}
4529
4530bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4531 return false;
4532}
4533
Alexis Hunte852b102011-05-24 22:41:36 +00004534bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4535 const UnaryTransformType*) {
4536 return false;
4537}
4538
Richard Smith30482bc2011-02-20 03:19:35 +00004539bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4540 return Visit(T->getDeducedType());
4541}
4542
Richard Smith600b5262017-01-26 20:40:47 +00004543bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
4544 const DeducedTemplateSpecializationType *T) {
4545 return Visit(T->getDeducedType());
4546}
4547
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004548bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4549 return VisitTagDecl(T->getDecl());
4550}
4551
4552bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4553 return VisitTagDecl(T->getDecl());
4554}
4555
4556bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4557 const TemplateTypeParmType*) {
4558 return false;
4559}
4560
Douglas Gregorada4b792011-01-14 02:55:32 +00004561bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4562 const SubstTemplateTypeParmPackType *) {
4563 return false;
4564}
4565
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004566bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4567 const TemplateSpecializationType*) {
4568 return false;
4569}
4570
4571bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4572 const InjectedClassNameType* T) {
4573 return VisitTagDecl(T->getDecl());
4574}
4575
4576bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4577 const DependentNameType* T) {
4578 return VisitNestedNameSpecifier(T->getQualifier());
4579}
4580
4581bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4582 const DependentTemplateSpecializationType* T) {
4583 return VisitNestedNameSpecifier(T->getQualifier());
4584}
4585
Douglas Gregord2fa7662010-12-20 02:24:11 +00004586bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4587 const PackExpansionType* T) {
4588 return Visit(T->getPattern());
4589}
4590
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004591bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4592 return false;
4593}
4594
4595bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4596 const ObjCInterfaceType *) {
4597 return false;
4598}
4599
4600bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4601 const ObjCObjectPointerType *) {
4602 return false;
4603}
4604
Eli Friedman0dfb8892011-10-06 23:00:33 +00004605bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4606 return Visit(T->getValueType());
4607}
4608
Xiuli Pan9c14e282016-01-09 12:53:17 +00004609bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4610 return false;
4611}
4612
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004613bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4614 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004615 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004616 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004617 diag::warn_cxx98_compat_template_arg_local_type :
4618 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004619 << S.Context.getTypeDeclType(Tag) << SR;
4620 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621 }
4622
John McCall5ea95772013-03-09 00:54:27 +00004623 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004624 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004625 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004626 diag::warn_cxx98_compat_template_arg_unnamed_type :
4627 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004628 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4629 return true;
4630 }
4631
4632 return false;
4633}
4634
4635bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4636 NestedNameSpecifier *NNS) {
4637 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4638 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004639
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004640 switch (NNS->getKind()) {
4641 case NestedNameSpecifier::Identifier:
4642 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004643 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004644 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004645 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004646 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004647
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004648 case NestedNameSpecifier::TypeSpec:
4649 case NestedNameSpecifier::TypeSpecWithTemplate:
4650 return Visit(QualType(NNS->getAsType(), 0));
4651 }
David Blaikie8a40f702012-01-17 06:56:22 +00004652 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004653}
4654
Douglas Gregord32e0282009-02-09 23:23:08 +00004655/// \brief Check a template argument against its corresponding
4656/// template type parameter.
4657///
4658/// This routine implements the semantics of C++ [temp.arg.type]. It
4659/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004660bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004661 TypeSourceInfo *ArgInfo) {
4662 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004663 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004664 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004665
4666 if (Arg->isVariablyModifiedType()) {
4667 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004668 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004669 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004670 }
4671
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004672 // C++03 [temp.arg.type]p2:
4673 // A local type, a type with no linkage, an unnamed type or a type
4674 // compounded from any of these types shall not be used as a
4675 // template-argument for a template type-parameter.
4676 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004677 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004678 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00004679 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004680 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4681 (void)Finder.Visit(Context.getCanonicalType(Arg));
4682 }
4683
Douglas Gregord32e0282009-02-09 23:23:08 +00004684 return false;
4685}
4686
Douglas Gregor20fdef32012-04-10 17:08:25 +00004687enum NullPointerValueKind {
4688 NPV_NotNullPointer,
4689 NPV_NullPointer,
4690 NPV_Error
4691};
4692
4693/// \brief Determine whether the given template argument is a null pointer
4694/// value of the appropriate type.
4695static NullPointerValueKind
4696isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4697 QualType ParamType, Expr *Arg) {
4698 if (Arg->isValueDependent() || Arg->isTypeDependent())
4699 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004700
Richard Smithdb0ac552015-12-18 22:40:25 +00004701 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004702 llvm_unreachable(
4703 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004704
David Majnemer5c734ad2014-08-14 00:49:23 +00004705 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004706 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00004707
Douglas Gregor20fdef32012-04-10 17:08:25 +00004708 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004709 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4710 if (ArgRV.isInvalid())
4711 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004712 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00004713
Douglas Gregor20fdef32012-04-10 17:08:25 +00004714 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004715 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004716 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004717 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004718 EvalResult.HasSideEffects) {
4719 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00004720
Douglas Gregor350880c2012-04-10 19:03:30 +00004721 // If our only note is the usual "invalid subexpression" note, just point
4722 // the caret at its location rather than producing an essentially
4723 // redundant note.
4724 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4725 diag::note_invalid_subexpr_in_const_expr) {
4726 DiagLoc = Notes[0].first;
4727 Notes.clear();
4728 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004729
Douglas Gregor350880c2012-04-10 19:03:30 +00004730 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4731 << Arg->getType() << Arg->getSourceRange();
4732 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4733 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004734
Douglas Gregor350880c2012-04-10 19:03:30 +00004735 S.Diag(Param->getLocation(), diag::note_template_param_here);
4736 return NPV_Error;
4737 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004738
Douglas Gregor20fdef32012-04-10 17:08:25 +00004739 // C++11 [temp.arg.nontype]p1:
4740 // - an address constant expression of type std::nullptr_t
4741 if (Arg->getType()->isNullPtrType())
4742 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00004743
Douglas Gregor20fdef32012-04-10 17:08:25 +00004744 // - a constant expression that evaluates to a null pointer value (4.10); or
4745 // - a constant expression that evaluates to a null member pointer value
4746 // (4.11); or
4747 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4748 (EvalResult.Val.isMemberPointer() &&
4749 !EvalResult.Val.getMemberPointerDecl())) {
4750 // If our expression has an appropriate type, we've succeeded.
4751 bool ObjCLifetimeConversion;
4752 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4753 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4754 ObjCLifetimeConversion))
4755 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00004756
Douglas Gregor20fdef32012-04-10 17:08:25 +00004757 // The types didn't match, but we know we got a null pointer; complain,
4758 // then recover as if the types were correct.
4759 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4760 << Arg->getType() << ParamType << Arg->getSourceRange();
4761 S.Diag(Param->getLocation(), diag::note_template_param_here);
4762 return NPV_NullPointer;
4763 }
4764
4765 // If we don't have a null pointer value, but we do have a NULL pointer
4766 // constant, suggest a cast to the appropriate type.
4767 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4768 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4769 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004770 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4771 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4772 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004773 S.Diag(Param->getLocation(), diag::note_template_param_here);
4774 return NPV_NullPointer;
4775 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004776
Douglas Gregor20fdef32012-04-10 17:08:25 +00004777 // FIXME: If we ever want to support general, address-constant expressions
4778 // as non-type template arguments, we should return the ExprResult here to
4779 // be interpreted by the caller.
4780 return NPV_NotNullPointer;
4781}
4782
David Majnemer61c39a12013-08-23 05:39:39 +00004783/// \brief Checks whether the given template argument is compatible with its
4784/// template parameter.
4785static bool CheckTemplateArgumentIsCompatibleWithParameter(
4786 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4787 Expr *Arg, QualType ArgType) {
4788 bool ObjCLifetimeConversion;
4789 if (ParamType->isPointerType() &&
4790 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4791 S.IsQualificationConversion(ArgType, ParamType, false,
4792 ObjCLifetimeConversion)) {
4793 // For pointer-to-object types, qualification conversions are
4794 // permitted.
4795 } else {
4796 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4797 if (!ParamRef->getPointeeType()->isFunctionType()) {
4798 // C++ [temp.arg.nontype]p5b3:
4799 // For a non-type template-parameter of type reference to
4800 // object, no conversions apply. The type referred to by the
4801 // reference may be more cv-qualified than the (otherwise
4802 // identical) type of the template- argument. The
4803 // template-parameter is bound directly to the
4804 // template-argument, which shall be an lvalue.
4805
4806 // FIXME: Other qualifiers?
4807 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4808 unsigned ArgQuals = ArgType.getCVRQualifiers();
4809
4810 if ((ParamQuals | ArgQuals) != ParamQuals) {
4811 S.Diag(Arg->getLocStart(),
4812 diag::err_template_arg_ref_bind_ignores_quals)
4813 << ParamType << Arg->getType() << Arg->getSourceRange();
4814 S.Diag(Param->getLocation(), diag::note_template_param_here);
4815 return true;
4816 }
4817 }
4818 }
4819
4820 // At this point, the template argument refers to an object or
4821 // function with external linkage. We now need to check whether the
4822 // argument and parameter types are compatible.
4823 if (!S.Context.hasSameUnqualifiedType(ArgType,
4824 ParamType.getNonReferenceType())) {
4825 // We can't perform this conversion or binding.
4826 if (ParamType->isReferenceType())
4827 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4828 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4829 else
4830 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4831 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4832 S.Diag(Param->getLocation(), diag::note_template_param_here);
4833 return true;
4834 }
4835 }
4836
4837 return false;
4838}
4839
Douglas Gregorccb07762009-02-11 19:52:55 +00004840/// \brief Checks whether the given template argument is the address
4841/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004842static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004843CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4844 NonTypeTemplateParmDecl *Param,
4845 QualType ParamType,
4846 Expr *ArgIn,
4847 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004848 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004849 Expr *Arg = ArgIn;
4850 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004851
Douglas Gregorb242683d2010-04-01 18:32:35 +00004852 bool AddressTaken = false;
4853 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004854 if (S.getLangOpts().MicrosoftExt) {
4855 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4856 // dereference and address-of operators.
4857 Arg = Arg->IgnoreParenCasts();
4858
4859 bool ExtWarnMSTemplateArg = false;
4860 UnaryOperatorKind FirstOpKind;
4861 SourceLocation FirstOpLoc;
4862 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4863 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4864 if (UnOpKind == UO_Deref)
4865 ExtWarnMSTemplateArg = true;
4866 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4867 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4868 if (!AddrOpLoc.isValid()) {
4869 FirstOpKind = UnOpKind;
4870 FirstOpLoc = UnOp->getOperatorLoc();
4871 }
4872 } else
4873 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004874 }
David Majnemer61c39a12013-08-23 05:39:39 +00004875 if (FirstOpLoc.isValid()) {
4876 if (ExtWarnMSTemplateArg)
4877 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4878 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004879
David Majnemer61c39a12013-08-23 05:39:39 +00004880 if (FirstOpKind == UO_AddrOf)
4881 AddressTaken = true;
4882 else if (Arg->getType()->isPointerType()) {
4883 // We cannot let pointers get dereferenced here, that is obviously not a
4884 // constant expression.
4885 assert(FirstOpKind == UO_Deref);
4886 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4887 << Arg->getSourceRange();
4888 }
4889 }
4890 } else {
4891 // See through any implicit casts we added to fix the type.
4892 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004893
David Majnemer61c39a12013-08-23 05:39:39 +00004894 // C++ [temp.arg.nontype]p1:
4895 //
4896 // A template-argument for a non-type, non-template
4897 // template-parameter shall be one of: [...]
4898 //
4899 // -- the address of an object or function with external
4900 // linkage, including function templates and function
4901 // template-ids but excluding non-static class members,
4902 // expressed as & id-expression where the & is optional if
4903 // the name refers to a function or array, or if the
4904 // corresponding template-parameter is a reference; or
4905
4906 // In C++98/03 mode, give an extension warning on any extra parentheses.
4907 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4908 bool ExtraParens = false;
4909 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4910 if (!Invalid && !ExtraParens) {
4911 S.Diag(Arg->getLocStart(),
4912 S.getLangOpts().CPlusPlus11
4913 ? diag::warn_cxx98_compat_template_arg_extra_parens
4914 : diag::ext_template_arg_extra_parens)
4915 << Arg->getSourceRange();
4916 ExtraParens = true;
4917 }
4918
4919 Arg = Parens->getSubExpr();
4920 }
4921
4922 while (SubstNonTypeTemplateParmExpr *subst =
4923 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4924 Arg = subst->getReplacement()->IgnoreImpCasts();
4925
4926 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4927 if (UnOp->getOpcode() == UO_AddrOf) {
4928 Arg = UnOp->getSubExpr();
4929 AddressTaken = true;
4930 AddrOpLoc = UnOp->getOperatorLoc();
4931 }
4932 }
4933
4934 while (SubstNonTypeTemplateParmExpr *subst =
4935 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4936 Arg = subst->getReplacement()->IgnoreImpCasts();
4937 }
John McCall7c454bb2011-07-15 05:09:51 +00004938
David Majnemer07910d62014-06-26 07:48:46 +00004939 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4940 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4941
4942 // If our parameter has pointer type, check for a null template value.
4943 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4944 NullPointerValueKind NPV;
4945 // dllimport'd entities aren't constant but are available inside of template
4946 // arguments.
4947 if (Entity && Entity->hasAttr<DLLImportAttr>())
4948 NPV = NPV_NotNullPointer;
4949 else
4950 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4951 switch (NPV) {
4952 case NPV_NullPointer:
4953 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004954 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4955 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004956 return false;
4957
4958 case NPV_Error:
4959 return true;
4960
4961 case NPV_NotNullPointer:
4962 break;
4963 }
4964 }
4965
Chandler Carruth724a8a12010-01-31 10:01:20 +00004966 // Stop checking the precise nature of the argument if it is value dependent,
4967 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004968 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004969 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004970 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004971 }
David Majnemer61c39a12013-08-23 05:39:39 +00004972
4973 if (isa<CXXUuidofExpr>(Arg)) {
4974 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4975 ArgIn, Arg, ArgType))
4976 return true;
4977
4978 Converted = TemplateArgument(ArgIn);
4979 return false;
4980 }
4981
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004982 if (!DRE) {
4983 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4984 << Arg->getSourceRange();
4985 S.Diag(Param->getLocation(), diag::note_template_param_here);
4986 return true;
4987 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004988
Douglas Gregorccb07762009-02-11 19:52:55 +00004989 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004990 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004991 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004992 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004993 S.Diag(Param->getLocation(), diag::note_template_param_here);
4994 return true;
4995 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004996
4997 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004998 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004999 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005000 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00005001 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005002 S.Diag(Param->getLocation(), diag::note_template_param_here);
5003 return true;
5004 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005005 }
Mike Stump11289f42009-09-09 15:08:12 +00005006
Richard Smith9380e0e2012-04-04 21:11:30 +00005007 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5008 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00005009
Richard Smith9380e0e2012-04-04 21:11:30 +00005010 // A non-type template argument must refer to an object or function.
5011 if (!Func && !Var) {
5012 // We found something, but we don't know specifically what it is.
5013 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5014 << Arg->getSourceRange();
5015 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5016 return true;
5017 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005018
Richard Smith9380e0e2012-04-04 21:11:30 +00005019 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00005020 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005021 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00005022 diag::warn_cxx98_compat_template_arg_object_internal :
5023 diag::ext_template_arg_object_internal)
5024 << !Func << Entity << Arg->getSourceRange();
5025 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5026 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00005027 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005028 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5029 << !Func << Entity << Arg->getSourceRange();
5030 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5031 << !Func;
5032 return true;
5033 }
5034
5035 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005036 // If the template parameter has pointer type, the function decays.
5037 if (ParamType->isPointerType() && !AddressTaken)
5038 ArgType = S.Context.getPointerType(Func->getType());
5039 else if (AddressTaken && ParamType->isReferenceType()) {
5040 // If we originally had an address-of operator, but the
5041 // parameter has reference type, complain and (if things look
5042 // like they will work) drop the address-of operator.
5043 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5044 ParamType.getNonReferenceType())) {
5045 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5046 << ParamType;
5047 S.Diag(Param->getLocation(), diag::note_template_param_here);
5048 return true;
5049 }
5050
5051 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5052 << ParamType
5053 << FixItHint::CreateRemoval(AddrOpLoc);
5054 S.Diag(Param->getLocation(), diag::note_template_param_here);
5055
5056 ArgType = Func->getType();
5057 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005058 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005059 // A value of reference type is not an object.
5060 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005061 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00005062 diag::err_template_arg_reference_var)
5063 << Var->getType() << Arg->getSourceRange();
5064 S.Diag(Param->getLocation(), diag::note_template_param_here);
5065 return true;
5066 }
5067
Richard Smith9380e0e2012-04-04 21:11:30 +00005068 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005069 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005070 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5071 << Arg->getSourceRange();
5072 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5073 return true;
5074 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005075
5076 // If the template parameter has pointer type, we must have taken
5077 // the address of this object.
5078 if (ParamType->isReferenceType()) {
5079 if (AddressTaken) {
5080 // If we originally had an address-of operator, but the
5081 // parameter has reference type, complain and (if things look
5082 // like they will work) drop the address-of operator.
5083 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5084 ParamType.getNonReferenceType())) {
5085 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5086 << ParamType;
5087 S.Diag(Param->getLocation(), diag::note_template_param_here);
5088 return true;
5089 }
5090
5091 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5092 << ParamType
5093 << FixItHint::CreateRemoval(AddrOpLoc);
5094 S.Diag(Param->getLocation(), diag::note_template_param_here);
5095
5096 ArgType = Var->getType();
5097 }
5098 } else if (!AddressTaken && ParamType->isPointerType()) {
5099 if (Var->getType()->isArrayType()) {
5100 // Array-to-pointer decay.
5101 ArgType = S.Context.getArrayDecayedType(Var->getType());
5102 } else {
5103 // If the template parameter has pointer type but the address of
5104 // this object was not taken, complain and (possibly) recover by
5105 // taking the address of the entity.
5106 ArgType = S.Context.getPointerType(Var->getType());
5107 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5108 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5109 << ParamType;
5110 S.Diag(Param->getLocation(), diag::note_template_param_here);
5111 return true;
5112 }
5113
5114 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5115 << ParamType
5116 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5117
5118 S.Diag(Param->getLocation(), diag::note_template_param_here);
5119 }
5120 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005121 }
Mike Stump11289f42009-09-09 15:08:12 +00005122
David Majnemer61c39a12013-08-23 05:39:39 +00005123 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5124 Arg, ArgType))
5125 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005126
5127 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00005128 Converted =
5129 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00005130 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00005131 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005132}
5133
5134/// \brief Checks whether the given template argument is a pointer to
5135/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005136static bool CheckTemplateArgumentPointerToMember(Sema &S,
5137 NonTypeTemplateParmDecl *Param,
5138 QualType ParamType,
5139 Expr *&ResultArg,
5140 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005141 bool Invalid = false;
5142
Douglas Gregor20fdef32012-04-10 17:08:25 +00005143 // Check for a null pointer value.
5144 Expr *Arg = ResultArg;
5145 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
5146 case NPV_Error:
5147 return true;
5148 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005149 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005150 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5151 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00005152 return false;
5153 case NPV_NotNullPointer:
5154 break;
5155 }
5156
5157 bool ObjCLifetimeConversion;
5158 if (S.IsQualificationConversion(Arg->getType(),
5159 ParamType.getNonReferenceType(),
5160 false, ObjCLifetimeConversion)) {
5161 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005162 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00005163 ResultArg = Arg;
5164 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
5165 ParamType.getNonReferenceType())) {
5166 // We can't perform this conversion.
5167 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5168 << Arg->getType() << ParamType << Arg->getSourceRange();
5169 S.Diag(Param->getLocation(), diag::note_template_param_here);
5170 return true;
5171 }
5172
Douglas Gregorccb07762009-02-11 19:52:55 +00005173 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00005174 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00005175 Arg = Cast->getSubExpr();
5176
5177 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005178 //
Douglas Gregorccb07762009-02-11 19:52:55 +00005179 // A template-argument for a non-type, non-template
5180 // template-parameter shall be one of: [...]
5181 //
5182 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00005183 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00005184
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005185 // In C++98/03 mode, give an extension warning on any extra parentheses.
5186 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5187 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005188 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005189 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005190 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005191 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00005192 diag::warn_cxx98_compat_template_arg_extra_parens :
5193 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00005194 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005195 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00005196 }
5197
5198 Arg = Parens->getSubExpr();
5199 }
5200
John McCall7c454bb2011-07-15 05:09:51 +00005201 while (SubstNonTypeTemplateParmExpr *subst =
5202 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5203 Arg = subst->getReplacement()->IgnoreImpCasts();
5204
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005205 // A pointer-to-member constant written &Class::member.
5206 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00005207 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005208 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5209 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005210 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005211 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005212 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005213 // A constant of pointer-to-member type.
5214 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5215 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5216 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00005217 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005218 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005219 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005220 } else {
5221 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005222 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005223 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005224 return Invalid;
5225 }
5226 }
5227 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005228
Craig Topperc3ec1492014-05-26 06:22:03 +00005229 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005230 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005231
Douglas Gregorccb07762009-02-11 19:52:55 +00005232 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005233 return S.Diag(Arg->getLocStart(),
5234 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00005235 << Arg->getSourceRange();
5236
David Majnemer3ac84e62013-10-22 21:56:38 +00005237 if (isa<FieldDecl>(DRE->getDecl()) ||
5238 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5239 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005240 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00005241 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00005242 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5243 "Only non-static member pointers can make it here");
5244
5245 // Okay: this is the address of a non-static member, and therefore
5246 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00005247 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005248 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005249 } else {
5250 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005251 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005252 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005253 return Invalid;
5254 }
5255
5256 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005257 S.Diag(Arg->getLocStart(),
5258 diag::err_template_arg_not_pointer_to_member_form)
5259 << Arg->getSourceRange();
5260 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00005261 return true;
5262}
5263
Douglas Gregord32e0282009-02-09 23:23:08 +00005264/// \brief Check a template argument against its corresponding
5265/// non-type template parameter.
5266///
Douglas Gregor463421d2009-03-03 04:44:36 +00005267/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00005268/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00005269/// returns the converted template argument. \p ParamType is the
5270/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00005271ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00005272 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00005273 TemplateArgument &Converted,
5274 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005275 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00005276
Richard Smith5f274382016-09-28 23:55:27 +00005277 // If the parameter type somehow involves auto, deduce the type now.
5278 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
Richard Smith87d263e2016-12-25 08:05:23 +00005279 // When checking a deduced template argument, deduce from its type even if
5280 // the type is dependent, in order to check the types of non-type template
5281 // arguments line up properly in partial ordering.
5282 Optional<unsigned> Depth;
5283 if (CTAK != CTAK_Specified)
5284 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00005285 if (DeduceAutoType(
5286 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00005287 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00005288 Diag(Arg->getExprLoc(),
5289 diag::err_non_type_template_parm_type_deduction_failure)
5290 << Param->getDeclName() << Param->getType() << Arg->getType()
5291 << Arg->getSourceRange();
5292 Diag(Param->getLocation(), diag::note_template_param_here);
5293 return ExprError();
5294 }
5295 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5296 // an error. The error message normally references the parameter
5297 // declaration, but here we'll pass the argument location because that's
5298 // where the parameter type is deduced.
5299 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5300 if (ParamType.isNull()) {
5301 Diag(Param->getLocation(), diag::note_template_param_here);
5302 return ExprError();
5303 }
5304 }
5305
Richard Smithd663fdd2014-12-17 20:42:37 +00005306 // We should have already dropped all cv-qualifiers by now.
5307 assert(!ParamType.hasQualifiers() &&
5308 "non-type template parameter type cannot be qualified");
5309
5310 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00005311 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00005312 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00005313 // FIXME: If either type is dependent, we skip the check. This isn't
5314 // correct, since during deduction we're supposed to have replaced each
5315 // template parameter with some unique (non-dependent) placeholder.
5316 // FIXME: If the argument type contains 'auto', we carry on and fail the
5317 // type check in order to force specific types to be more specialized than
5318 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5319 // work.
5320 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5321 !Arg->getType()->getContainedAutoType()) {
5322 Converted = TemplateArgument(Arg);
5323 return Arg;
5324 }
5325 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5326 // we should actually be checking the type of the template argument in P,
5327 // not the type of the template argument deduced from A, against the
5328 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00005329 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00005330 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00005331 << ParamType.getUnqualifiedType();
5332 Diag(Param->getLocation(), diag::note_template_param_here);
5333 return ExprError();
5334 }
5335
Richard Smith87d263e2016-12-25 08:05:23 +00005336 // If either the parameter has a dependent type or the argument is
5337 // type-dependent, there's nothing we can check now.
5338 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5339 // FIXME: Produce a cloned, canonical expression?
5340 Converted = TemplateArgument(Arg);
5341 return Arg;
5342 }
5343
Richard Smithe5945872017-01-06 22:52:53 +00005344 // The initialization of the parameter from the argument is
5345 // a constant-evaluated context.
5346 EnterExpressionEvaluationContext ConstantEvaluated(*this,
5347 Sema::ConstantEvaluated);
5348
Richard Smith410cc892014-11-26 03:26:53 +00005349 if (getLangOpts().CPlusPlus1z) {
Richard Smith410cc892014-11-26 03:26:53 +00005350 // C++1z [temp.arg.nontype]p1:
5351 // A template-argument for a non-type template parameter shall be
5352 // a converted constant expression of the type of the template-parameter.
5353 APValue Value;
5354 ExprResult ArgResult = CheckConvertedConstantExpression(
5355 Arg, ParamType, Value, CCEK_TemplateArg);
5356 if (ArgResult.isInvalid())
5357 return ExprError();
5358
Richard Smith52e624f2016-12-21 21:42:57 +00005359 // For a value-dependent argument, CheckConvertedConstantExpression is
5360 // permitted (and expected) to be unable to determine a value.
5361 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00005362 Converted = TemplateArgument(ArgResult.get());
5363 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00005364 }
5365
Richard Smithd663fdd2014-12-17 20:42:37 +00005366 QualType CanonParamType = Context.getCanonicalType(ParamType);
5367
Richard Smith410cc892014-11-26 03:26:53 +00005368 // Convert the APValue to a TemplateArgument.
5369 switch (Value.getKind()) {
5370 case APValue::Uninitialized:
5371 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005372 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005373 break;
5374 case APValue::Int:
5375 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005376 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005377 break;
5378 case APValue::MemberPointer: {
5379 assert(ParamType->isMemberPointerType());
5380
5381 // FIXME: We need TemplateArgument representation and mangling for these.
5382 if (!Value.getMemberPointerPath().empty()) {
5383 Diag(Arg->getLocStart(),
5384 diag::err_template_arg_member_ptr_base_derived_not_supported)
5385 << Value.getMemberPointerDecl() << ParamType
5386 << Arg->getSourceRange();
5387 return ExprError();
5388 }
5389
5390 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005391 Converted = VD ? TemplateArgument(VD, CanonParamType)
5392 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005393 break;
5394 }
5395 case APValue::LValue: {
5396 // For a non-type template-parameter of pointer or reference type,
5397 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00005398 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5399 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00005400 // -- a temporary object
5401 // -- a string literal
5402 // -- the result of a typeid expression, or
5403 // -- a predefind __func__ variable
5404 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5405 if (isa<CXXUuidofExpr>(E)) {
5406 Converted = TemplateArgument(const_cast<Expr*>(E));
5407 break;
5408 }
5409 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5410 << Arg->getSourceRange();
5411 return ExprError();
5412 }
5413 auto *VD = const_cast<ValueDecl *>(
5414 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5415 // -- a subobject
5416 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5417 VD && VD->getType()->isArrayType() &&
5418 Value.getLValuePath()[0].ArrayIndex == 0 &&
5419 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5420 // Per defect report (no number yet):
5421 // ... other than a pointer to the first element of a complete array
5422 // object.
5423 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5424 Value.isLValueOnePastTheEnd()) {
5425 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5426 << Value.getAsString(Context, ParamType);
5427 return ExprError();
5428 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005429 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005430 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005431 assert((!VD || !ParamType->isNullPtrType()) &&
5432 "non-null value of type nullptr_t?");
5433 Converted = VD ? TemplateArgument(VD, CanonParamType)
5434 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005435 break;
5436 }
5437 case APValue::AddrLabelDiff:
5438 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5439 case APValue::Float:
5440 case APValue::ComplexInt:
5441 case APValue::ComplexFloat:
5442 case APValue::Vector:
5443 case APValue::Array:
5444 case APValue::Struct:
5445 case APValue::Union:
5446 llvm_unreachable("invalid kind for template argument");
5447 }
5448
5449 return ArgResult.get();
5450 }
5451
Douglas Gregor86560402009-02-10 23:36:10 +00005452 // C++ [temp.arg.nontype]p5:
5453 // The following conversions are performed on each expression used
5454 // as a non-type template-argument. If a non-type
5455 // template-argument cannot be converted to the type of the
5456 // corresponding template-parameter then the program is
5457 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005458 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005459 // C++11:
5460 // -- for a non-type template-parameter of integral or
5461 // enumeration type, conversions permitted in a converted
5462 // constant expression are applied.
5463 //
5464 // C++98:
5465 // -- for a non-type template-parameter of integral or
5466 // enumeration type, integral promotions (4.5) and integral
5467 // conversions (4.7) are applied.
5468
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005469 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005470 // C++ [temp.arg.nontype]p1:
5471 // A template-argument for a non-type, non-template template-parameter
5472 // shall be one of:
5473 //
5474 // -- for a non-type template-parameter of integral or enumeration
5475 // type, a converted constant expression of the type of the
5476 // template-parameter; or
5477 llvm::APSInt Value;
5478 ExprResult ArgResult =
5479 CheckConvertedConstantExpression(Arg, ParamType, Value,
5480 CCEK_TemplateArg);
5481 if (ArgResult.isInvalid())
5482 return ExprError();
5483
Richard Smith01bfa682016-12-27 02:02:09 +00005484 // We can't check arbitrary value-dependent arguments.
5485 if (ArgResult.get()->isValueDependent()) {
5486 Converted = TemplateArgument(ArgResult.get());
5487 return ArgResult;
5488 }
5489
Richard Smithf8379a02012-01-18 23:55:52 +00005490 // Widen the argument value to sizeof(parameter type). This is almost
5491 // always a no-op, except when the parameter type is bool. In
5492 // that case, this may extend the argument from 1 bit to 8 bits.
5493 QualType IntegerType = ParamType;
5494 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5495 IntegerType = Enum->getDecl()->getIntegerType();
5496 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5497
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005498 Converted = TemplateArgument(Context, Value,
5499 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005500 return ArgResult;
5501 }
5502
Richard Smith08b12f12011-10-27 22:11:44 +00005503 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5504 if (ArgResult.isInvalid())
5505 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005506 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005507
5508 QualType ArgType = Arg->getType();
5509
Douglas Gregor86560402009-02-10 23:36:10 +00005510 // C++ [temp.arg.nontype]p1:
5511 // A template-argument for a non-type, non-template
5512 // template-parameter shall be one of:
5513 //
5514 // -- an integral constant-expression of integral or enumeration
5515 // type; or
5516 // -- the name of a non-type template-parameter; or
5517 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005518 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005519 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005520 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005521 diag::err_template_arg_not_integral_or_enumeral)
5522 << ArgType << Arg->getSourceRange();
5523 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005524 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005525 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005526 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5527 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005528
Douglas Gregore2b37442012-05-04 22:38:52 +00005529 public:
5530 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005531
5532 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5533 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005534 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5535 }
5536 } Diagnoser(ArgType);
5537
5538 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005539 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005540 if (!Arg)
5541 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005542 }
5543
Richard Smithd663fdd2014-12-17 20:42:37 +00005544 // From here on out, all we care about is the unqualified form
5545 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005546 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005547
5548 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005549 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005550 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005551 } else if (ParamType->isBooleanType()) {
5552 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005553 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005554 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5555 !ParamType->isEnumeralType()) {
5556 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005557 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005558 } else {
5559 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005560 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005561 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005562 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005563 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005564 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005565 }
5566
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005567 // Add the value of this argument to the list of converted
5568 // arguments. We use the bitwidth and signedness of the template
5569 // parameter.
5570 if (Arg->isValueDependent()) {
5571 // The argument is value-dependent. Create a new
5572 // TemplateArgument with the converted expression.
5573 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005574 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005575 }
5576
Douglas Gregor52aba872009-03-14 00:20:21 +00005577 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005578 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005579 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005580
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005581 if (ParamType->isBooleanType()) {
5582 // Value must be zero or one.
5583 Value = Value != 0;
5584 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5585 if (Value.getBitWidth() != AllowedBits)
5586 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005587 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005588 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005589 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005590
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005591 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005592 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005593 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005594 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005595 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005596 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00005597
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005598 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005599 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005600 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005601 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005602 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5603 << Arg->getSourceRange();
5604 Diag(Param->getLocation(), diag::note_template_param_here);
5605 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005606
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005607 // Complain if we overflowed the template parameter's type.
5608 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005609 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005610 RequiredBits = OldValue.getActiveBits();
5611 else if (OldValue.isUnsigned())
5612 RequiredBits = OldValue.getActiveBits() + 1;
5613 else
5614 RequiredBits = OldValue.getMinSignedBits();
5615 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005616 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005617 diag::warn_template_arg_too_large)
5618 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5619 << Arg->getSourceRange();
5620 Diag(Param->getLocation(), diag::note_template_param_here);
5621 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005622 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005623
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005624 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00005625 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005626 ? Context.getCanonicalType(ParamType)
5627 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005628 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005629 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005630
Richard Smith08b12f12011-10-27 22:11:44 +00005631 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005632 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5633
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005634 // Handle pointer-to-function, reference-to-function, and
5635 // pointer-to-member-function all in (roughly) the same way.
5636 if (// -- For a non-type template-parameter of type pointer to
5637 // function, only the function-to-pointer conversion (4.3) is
5638 // applied. If the template-argument represents a set of
5639 // overloaded functions (or a pointer to such), the matching
5640 // function is selected from the set (13.4).
5641 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005642 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005643 // -- For a non-type template-parameter of type reference to
5644 // function, no conversions apply. If the template-argument
5645 // represents a set of overloaded functions, the matching
5646 // function is selected from the set (13.4).
5647 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005648 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005649 // -- For a non-type template-parameter of type pointer to
5650 // member function, no conversions apply. If the
5651 // template-argument represents a set of overloaded member
5652 // functions, the matching member function is selected from
5653 // the set (13.4).
5654 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005655 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005656 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005657
Douglas Gregor064fdb22010-04-14 23:11:21 +00005658 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005659 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005660 true,
5661 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005662 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005663 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005664
5665 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5666 ArgType = Arg->getType();
5667 } else
John Wiegley01296292011-04-08 18:41:53 +00005668 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670
John Wiegley01296292011-04-08 18:41:53 +00005671 if (!ParamType->isMemberPointerType()) {
5672 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5673 ParamType,
5674 Arg, Converted))
5675 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005676 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005677 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005678
Douglas Gregor20fdef32012-04-10 17:08:25 +00005679 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5680 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005681 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005682 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005683 }
5684
Chris Lattner696197c2009-02-20 21:37:53 +00005685 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005686 // -- for a non-type template-parameter of type pointer to
5687 // object, qualification conversions (4.4) and the
5688 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005689 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005690 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005691 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005692
John Wiegley01296292011-04-08 18:41:53 +00005693 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5694 ParamType,
5695 Arg, Converted))
5696 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005697 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005698 }
Mike Stump11289f42009-09-09 15:08:12 +00005699
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005700 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005701 // -- For a non-type template-parameter of type reference to
5702 // object, no conversions apply. The type referred to by the
5703 // reference may be more cv-qualified than the (otherwise
5704 // identical) type of the template-argument. The
5705 // template-parameter is bound directly to the
5706 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005707 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005708 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005709
Douglas Gregor064fdb22010-04-14 23:11:21 +00005710 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005711 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5712 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005713 true,
5714 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005715 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005716 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005717
5718 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5719 ArgType = Arg->getType();
5720 } else
John Wiegley01296292011-04-08 18:41:53 +00005721 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005723
John Wiegley01296292011-04-08 18:41:53 +00005724 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5725 ParamType,
5726 Arg, Converted))
5727 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005728 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005729 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005730
Douglas Gregor20fdef32012-04-10 17:08:25 +00005731 // Deal with parameters of type std::nullptr_t.
5732 if (ParamType->isNullPtrType()) {
5733 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5734 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005735 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005736 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005737
Douglas Gregor20fdef32012-04-10 17:08:25 +00005738 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5739 case NPV_NotNullPointer:
5740 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5741 << Arg->getType() << ParamType;
5742 Diag(Param->getLocation(), diag::note_template_param_here);
5743 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005744
Douglas Gregor20fdef32012-04-10 17:08:25 +00005745 case NPV_Error:
5746 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005747
Douglas Gregor20fdef32012-04-10 17:08:25 +00005748 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005749 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005750 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5751 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005752 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005753 }
5754 }
5755
Douglas Gregor0e558532009-02-11 16:16:59 +00005756 // -- For a non-type template-parameter of type pointer to data
5757 // member, qualification conversions (4.4) are applied.
5758 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5759
Douglas Gregor20fdef32012-04-10 17:08:25 +00005760 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5761 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005762 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005763 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005764}
5765
Richard Smith26b86ea2016-12-31 21:41:23 +00005766static void DiagnoseTemplateParameterListArityMismatch(
5767 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
5768 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
5769
Douglas Gregord32e0282009-02-09 23:23:08 +00005770/// \brief Check a template argument against its corresponding
5771/// template template parameter.
5772///
5773/// This routine implements the semantics of C++ [temp.arg.template].
5774/// It returns true if an error occurred, and false otherwise.
5775bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005776 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005777 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005778 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005779 TemplateDecl *Template = Name.getAsTemplateDecl();
5780 if (!Template) {
5781 // Any dependent template name is fine.
5782 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5783 return false;
5784 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005785
Richard Smith26b86ea2016-12-31 21:41:23 +00005786 if (Template->isInvalidDecl())
5787 return true;
5788
Richard Smith3f1b5d02011-05-05 21:57:07 +00005789 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005790 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005791 // the name of a class template or an alias template, expressed as an
5792 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005793 // primary class templates are considered when matching the
5794 // template template argument with the corresponding parameter;
5795 // partial specializations are not considered even if their
5796 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005797 //
5798 // Note that we also allow template template parameters here, which
5799 // will happen when we are dealing with, e.g., class template
5800 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005801 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005802 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00005803 !isa<TypeAliasTemplateDecl>(Template) &&
5804 !isa<BuiltinTemplateDecl>(Template)) {
5805 assert(isa<FunctionTemplateDecl>(Template) &&
5806 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00005807 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00005808 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5809 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00005810 }
5811
Richard Smith1fde8ec2012-09-07 02:06:42 +00005812 TemplateParameterList *Params = Param->getTemplateParameters();
5813 if (Param->isExpandedParameterPack())
5814 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5815
Richard Smith26b86ea2016-12-31 21:41:23 +00005816 // C++1z [temp.arg.template]p3: (DR 150)
5817 // A template-argument matches a template template-parameter P when P
5818 // is at least as specialized as the template-argument A.
5819 if (getLangOpts().RelaxedTemplateTemplateArgs) {
5820 // Quick check for the common case:
5821 // If P contains a parameter pack, then A [...] matches P if each of A's
5822 // template parameters matches the corresponding template parameter in
5823 // the template-parameter-list of P.
5824 if (TemplateParameterListsAreEqual(
5825 Template->getTemplateParameters(), Params, false,
5826 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
5827 return false;
5828
5829 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
5830 Arg.getLocation()))
5831 return false;
5832 // FIXME: Produce better diagnostics for deduction failures.
5833 }
5834
Douglas Gregor85e0f662009-02-10 00:24:35 +00005835 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005836 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005837 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005838 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005839 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005840}
5841
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005842/// \brief Given a non-type template argument that refers to a
5843/// declaration and the type of its corresponding non-type template
5844/// parameter, produce an expression that properly refers to that
5845/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005846ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005847Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5848 QualType ParamType,
5849 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005850 // C++ [temp.param]p8:
5851 //
5852 // A non-type template-parameter of type "array of T" or
5853 // "function returning T" is adjusted to be of type "pointer to
5854 // T" or "pointer to function returning T", respectively.
5855 if (ParamType->isArrayType())
5856 ParamType = Context.getArrayDecayedType(ParamType);
5857 else if (ParamType->isFunctionType())
5858 ParamType = Context.getPointerType(ParamType);
5859
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005860 // For a NULL non-type template argument, return nullptr casted to the
5861 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005862 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005863 return ImpCastExprToType(
5864 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5865 ParamType,
5866 ParamType->getAs<MemberPointerType>()
5867 ? CK_NullToMemberPointer
5868 : CK_NullToPointer);
5869 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005870 assert(Arg.getKind() == TemplateArgument::Declaration &&
5871 "Only declaration template arguments permitted here");
5872
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005873 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5874
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005875 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005876 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5877 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005878 // If the value is a class member, we might have a pointer-to-member.
5879 // Determine whether the non-type template template parameter is of
5880 // pointer-to-member type. If so, we need to build an appropriate
5881 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5882 // would refer to the member itself.
5883 if (ParamType->isMemberPointerType()) {
5884 QualType ClassType
5885 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5886 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005887 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005888 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005889 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005890 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005891
5892 // The actual value-ness of this is unimportant, but for
5893 // internal consistency's sake, references to instance methods
5894 // are r-values.
5895 ExprValueKind VK = VK_LValue;
5896 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5897 VK = VK_RValue;
5898
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005899 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005900 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005901 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005902 Loc,
5903 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005904 if (RefExpr.isInvalid())
5905 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005906
John McCalle3027922010-08-25 11:45:40 +00005907 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005908
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005909 // We might need to perform a trailing qualification conversion, since
5910 // the element type on the parameter could be more qualified than the
5911 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005912 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005913 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005914 ParamType.getUnqualifiedType(), false,
5915 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005916 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005917
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005918 assert(!RefExpr.isInvalid() &&
5919 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005920 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005921 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005922 }
5923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005924
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005925 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005926
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005927 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005928 // When the non-type template parameter is a pointer, take the
5929 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005930 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005931 if (RefExpr.isInvalid())
5932 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005933
Richard Smithfc6fca12017-01-28 00:38:35 +00005934 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
5935 (T->isFunctionType() || T->isArrayType())) {
5936 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005937 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005938 if (RefExpr.isInvalid())
5939 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005940
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005941 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005943
Douglas Gregorb242683d2010-04-01 18:32:35 +00005944 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005945 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005946 }
5947
John McCall7decc9e2010-11-18 06:31:45 +00005948 ExprValueKind VK = VK_RValue;
5949
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005950 // If the non-type template parameter has reference type, qualify the
5951 // resulting declaration reference with the extra qualifiers on the
5952 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005953 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5954 VK = VK_LValue;
5955 T = Context.getQualifiedType(T,
5956 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005957 } else if (isa<FunctionDecl>(VD)) {
5958 // References to functions are always lvalues.
5959 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005960 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005961
John McCall7decc9e2010-11-18 06:31:45 +00005962 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005963}
5964
5965/// \brief Construct a new expression that refers to the given
5966/// integral template argument with the given source-location
5967/// information.
5968///
5969/// This routine takes care of the mapping from an integral template
5970/// argument (which may have any integral type) to the appropriate
5971/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005972ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005973Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5974 SourceLocation Loc) {
5975 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005976 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005977 QualType OrigT = Arg.getIntegralType();
5978
5979 // If this is an enum type that we're instantiating, we need to use an integer
5980 // type the same size as the enumerator. We don't want to build an
5981 // IntegerLiteral with enum type. The integer type of an enum type can be of
5982 // any integral type with C++11 enum classes, make sure we create the right
5983 // type of literal for it.
5984 QualType T = OrigT;
5985 if (const EnumType *ET = OrigT->getAs<EnumType>())
5986 T = ET->getDecl()->getIntegerType();
5987
5988 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005989 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005990 // This does not need to handle u8 character literals because those are
5991 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005992 CharacterLiteral::CharacterKind Kind;
5993 if (T->isWideCharType())
5994 Kind = CharacterLiteral::Wide;
5995 else if (T->isChar16Type())
5996 Kind = CharacterLiteral::UTF16;
5997 else if (T->isChar32Type())
5998 Kind = CharacterLiteral::UTF32;
5999 else
6000 Kind = CharacterLiteral::Ascii;
6001
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006002 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6003 Kind, T, Loc);
6004 } else if (T->isBooleanType()) {
6005 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6006 T, Loc);
6007 } else if (T->isNullPtrType()) {
6008 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6009 } else {
6010 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00006011 }
6012
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006013 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00006014 // FIXME: This is a hack. We need a better way to handle substituted
6015 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00006016 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6017 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006018 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00006019 Loc, Loc);
6020 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006021
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006022 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006023}
6024
Richard Smith43a833b2017-01-09 23:54:33 +00006025static bool isDependentOnOuter(NonTypeTemplateParmDecl *NTTP) {
6026 if (NTTP->getDepth() == 0 || !NTTP->getType()->isDependentType())
6027 return false;
6028 DependencyChecker Checker(NTTP->getDepth(), /*IgnoreNonTypeDependent*/ false,
6029 /*FindLessThanDepth*/ true);
6030 Checker.TraverseType(NTTP->getType());
6031 return Checker.Match;
6032}
6033
Douglas Gregor641040a2011-01-12 23:45:44 +00006034/// \brief Match two template parameters within template parameter lists.
6035static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6036 bool Complain,
6037 Sema::TemplateParameterListEqualKind Kind,
6038 SourceLocation TemplateArgLoc) {
6039 // Check the actual kind (type, non-type, template).
6040 if (Old->getKind() != New->getKind()) {
6041 if (Complain) {
6042 unsigned NextDiag = diag::err_template_param_different_kind;
6043 if (TemplateArgLoc.isValid()) {
6044 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6045 NextDiag = diag::note_template_param_different_kind;
6046 }
6047 S.Diag(New->getLocation(), NextDiag)
6048 << (Kind != Sema::TPL_TemplateMatch);
6049 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6050 << (Kind != Sema::TPL_TemplateMatch);
6051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006052
Douglas Gregor641040a2011-01-12 23:45:44 +00006053 return false;
6054 }
6055
Richard Smith26b86ea2016-12-31 21:41:23 +00006056 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006057 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006058 // template template parameter, the template template parameter can have
6059 // a parameter pack where the template template argument does not.
6060 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6061 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6062 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006063 if (Complain) {
6064 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6065 if (TemplateArgLoc.isValid()) {
6066 S.Diag(TemplateArgLoc,
6067 diag::err_template_arg_template_params_mismatch);
6068 NextDiag = diag::note_template_parameter_pack_non_pack;
6069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006070
Douglas Gregor641040a2011-01-12 23:45:44 +00006071 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6072 : isa<NonTypeTemplateParmDecl>(New)? 1
6073 : 2;
6074 S.Diag(New->getLocation(), NextDiag)
6075 << ParamKind << New->isParameterPack();
6076 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6077 << ParamKind << Old->isParameterPack();
6078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006079
Douglas Gregor641040a2011-01-12 23:45:44 +00006080 return false;
6081 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006082
Douglas Gregor641040a2011-01-12 23:45:44 +00006083 // For non-type template parameters, check the type of the parameter.
6084 if (NonTypeTemplateParmDecl *OldNTTP
6085 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6086 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006087
Douglas Gregor641040a2011-01-12 23:45:44 +00006088 // If we are matching a template template argument to a template
6089 // template parameter and one of the non-type template parameter types
Richard Smith43a833b2017-01-09 23:54:33 +00006090 // is dependent on an outer template's parameter, then we must wait until
6091 // template instantiation time to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00006092 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith43a833b2017-01-09 23:54:33 +00006093 (isDependentOnOuter(OldNTTP) || isDependentOnOuter(NewNTTP)))
Douglas Gregor641040a2011-01-12 23:45:44 +00006094 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006095
Douglas Gregor641040a2011-01-12 23:45:44 +00006096 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6097 if (Complain) {
6098 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6099 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006100 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00006101 diag::err_template_arg_template_params_mismatch);
6102 NextDiag = diag::note_template_nontype_parm_different_type;
6103 }
6104 S.Diag(NewNTTP->getLocation(), NextDiag)
6105 << NewNTTP->getType()
6106 << (Kind != Sema::TPL_TemplateMatch);
6107 S.Diag(OldNTTP->getLocation(),
6108 diag::note_template_nontype_parm_prev_declaration)
6109 << OldNTTP->getType();
6110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006111
Douglas Gregor641040a2011-01-12 23:45:44 +00006112 return false;
6113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006114
Douglas Gregor641040a2011-01-12 23:45:44 +00006115 return true;
6116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006117
Douglas Gregor641040a2011-01-12 23:45:44 +00006118 // For template template parameters, check the template parameter types.
6119 // The template parameter lists of template template
6120 // parameters must agree.
6121 if (TemplateTemplateParmDecl *OldTTP
6122 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006123 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00006124 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6125 OldTTP->getTemplateParameters(),
6126 Complain,
6127 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006128 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00006129 : Kind),
6130 TemplateArgLoc);
6131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006132
Douglas Gregor641040a2011-01-12 23:45:44 +00006133 return true;
6134}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006135
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006136/// \brief Diagnose a known arity mismatch when comparing template argument
6137/// lists.
6138static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006139void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006140 TemplateParameterList *New,
6141 TemplateParameterList *Old,
6142 Sema::TemplateParameterListEqualKind Kind,
6143 SourceLocation TemplateArgLoc) {
6144 unsigned NextDiag = diag::err_template_param_list_different_arity;
6145 if (TemplateArgLoc.isValid()) {
6146 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6147 NextDiag = diag::note_template_param_list_different_arity;
6148 }
6149 S.Diag(New->getTemplateLoc(), NextDiag)
6150 << (New->size() > Old->size())
6151 << (Kind != Sema::TPL_TemplateMatch)
6152 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6153 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6154 << (Kind != Sema::TPL_TemplateMatch)
6155 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6156}
6157
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006158/// \brief Determine whether the given template parameter lists are
6159/// equivalent.
6160///
Mike Stump11289f42009-09-09 15:08:12 +00006161/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006162/// source code as part of a new template declaration.
6163///
6164/// \param Old The old template parameter list, typically found via
6165/// name lookup of the template declared with this template parameter
6166/// list.
6167///
6168/// \param Complain If true, this routine will produce a diagnostic if
6169/// the template parameter lists are not equivalent.
6170///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006171/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00006172///
6173/// \param TemplateArgLoc If this source location is valid, then we
6174/// are actually checking the template parameter list of a template
6175/// argument (New) against the template parameter list of its
6176/// corresponding template template parameter (Old). We produce
6177/// slightly different diagnostics in this scenario.
6178///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006179/// \returns True if the template parameter lists are equal, false
6180/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00006181bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006182Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6183 TemplateParameterList *Old,
6184 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006185 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00006186 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006187 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6188 if (Complain)
6189 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6190 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006191
6192 return false;
6193 }
6194
Douglas Gregor641040a2011-01-12 23:45:44 +00006195 // C++0x [temp.arg.template]p3:
6196 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006197 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00006198 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006199 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006200 // template-parameter-list of P. [...]
6201 TemplateParameterList::iterator NewParm = New->begin();
6202 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006203 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006204 OldParmEnd = Old->end();
6205 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00006206 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6207 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006208 if (NewParm == NewParmEnd) {
6209 if (Complain)
6210 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6211 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006212
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006213 return false;
6214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006215
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006216 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6217 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006218 return false;
6219
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006220 ++NewParm;
6221 continue;
6222 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006223
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006224 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006225 // [...] When P's template- parameter-list contains a template parameter
6226 // pack (14.5.3), the template parameter pack will match zero or more
6227 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006228 // template-parameter-list of A with the same type and form as the
6229 // template parameter pack in P (ignoring whether those template
6230 // parameters are template parameter packs).
6231 for (; NewParm != NewParmEnd; ++NewParm) {
6232 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6233 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006234 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006235 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006237
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006238 // Make sure we exhausted all of the arguments.
6239 if (NewParm != NewParmEnd) {
6240 if (Complain)
6241 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6242 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006243
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006244 return false;
6245 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006246
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006247 return true;
6248}
6249
6250/// \brief Check whether a template can be declared within this scope.
6251///
6252/// If the template declaration is valid in this scope, returns
6253/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00006254bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006255Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00006256 if (!S)
6257 return false;
6258
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006259 // Find the nearest enclosing declaration scope.
6260 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6261 (S->getFlags() & Scope::TemplateParamScope) != 0)
6262 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006263
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006264 // C++ [temp]p4:
6265 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00006266 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00006267 if (Ctx && Ctx->isExternCContext()) {
6268 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6269 << TemplateParams->getSourceRange();
6270 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6271 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6272 return true;
6273 }
Richard Smith8df390f2016-09-08 23:14:54 +00006274 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006275
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006276 // C++ [temp]p2:
6277 // A template-declaration can appear only as a namespace scope or
6278 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00006279 if (Ctx) {
6280 if (Ctx->isFileContext())
6281 return false;
6282 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6283 // C++ [temp.mem]p2:
6284 // A local class shall not have member templates.
6285 if (RD->isLocalClass())
6286 return Diag(TemplateParams->getTemplateLoc(),
6287 diag::err_template_inside_local_class)
6288 << TemplateParams->getSourceRange();
6289 else
6290 return false;
6291 }
6292 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006293
Mike Stump11289f42009-09-09 15:08:12 +00006294 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006295 diag::err_template_outside_namespace_or_class_scope)
6296 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006297}
Douglas Gregor67a65642009-02-17 23:15:12 +00006298
Douglas Gregor54888652009-10-07 00:13:32 +00006299/// \brief Determine what kind of template specialization the given declaration
6300/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006301static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00006302 if (!D)
6303 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006304
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006305 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6306 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00006307 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6308 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006309 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6310 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006311
Douglas Gregor54888652009-10-07 00:13:32 +00006312 return TSK_Undeclared;
6313}
6314
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006315/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006316/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00006317///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006318/// This routine determines whether a template specialization can be declared
6319/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00006320///
6321/// \param S the semantic analysis object for which this check is being
6322/// performed.
6323///
6324/// \param Specialized the entity being specialized or instantiated, which
6325/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006326/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00006327/// member class).
6328///
6329/// \param PrevDecl the previous declaration of this entity, if any.
6330///
6331/// \param Loc the location of the explicit specialization or instantiation of
6332/// this entity.
6333///
6334/// \param IsPartialSpecialization whether this is a partial specialization of
6335/// a class template.
6336///
Douglas Gregor54888652009-10-07 00:13:32 +00006337/// \returns true if there was an error that we cannot recover from, false
6338/// otherwise.
6339static bool CheckTemplateSpecializationScope(Sema &S,
6340 NamedDecl *Specialized,
6341 NamedDecl *PrevDecl,
6342 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006343 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00006344 // Keep these "kind" numbers in sync with the %select statements in the
6345 // various diagnostics emitted by this routine.
6346 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006347 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006348 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006349 else if (isa<VarTemplateDecl>(Specialized))
6350 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006351 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006352 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006353 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006354 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006355 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00006356 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006357 else if (isa<RecordDecl>(Specialized))
6358 EntityKind = 7;
6359 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6360 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00006361 else {
Richard Smith7d137e32012-03-23 03:33:32 +00006362 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006363 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006364 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00006365 return true;
6366 }
6367
Douglas Gregorf47b9112009-02-25 22:02:03 +00006368 // C++ [temp.expl.spec]p2:
6369 // An explicit specialization shall be declared in the namespace
6370 // of which the template is a member, or, for member templates, in
6371 // the namespace of which the enclosing class or enclosing class
6372 // template is a member. An explicit specialization of a member
6373 // function, member class or static data member of a class
6374 // template shall be declared in the namespace of which the class
6375 // template is a member. Such a declaration may also be a
6376 // definition. If the declaration is not a definition, the
6377 // specialization may be defined later in the name- space in which
6378 // the explicit specialization was declared, or in a namespace
6379 // that encloses the one in which the explicit specialization was
6380 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00006381 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00006382 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006383 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006384 return true;
6385 }
Douglas Gregore4b05162009-10-07 17:21:34 +00006386
Douglas Gregor40fb7442009-10-07 17:30:37 +00006387 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006388 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006389 // Do not warn for class scope explicit specialization during
6390 // instantiation, warning was already emitted during pattern
6391 // semantic analysis.
6392 if (!S.ActiveTemplateInstantiations.size())
6393 S.Diag(Loc, diag::ext_function_specialization_in_class)
6394 << Specialized;
6395 } else {
6396 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6397 << Specialized;
6398 return true;
6399 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006401
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006402 if (S.CurContext->isRecord() &&
6403 !S.CurContext->Equals(Specialized->getDeclContext())) {
6404 // Make sure that we're specializing in the right record context.
6405 // Otherwise, things can go horribly wrong.
6406 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6407 << Specialized;
6408 return true;
6409 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006410
Douglas Gregore4b05162009-10-07 17:21:34 +00006411 // C++ [temp.class.spec]p6:
6412 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006413 // in any namespace scope in which its definition may be defined (14.5.1
6414 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00006415 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00006416 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00006417 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00006418
6419 // Make sure that this redeclaration (or definition) occurs in an enclosing
6420 // namespace.
6421 // Note that HandleDeclarator() performs this check for explicit
6422 // specializations of function templates, static data members, and member
6423 // functions, so we skip the check here for those kinds of entities.
6424 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6425 // Should we refactor that check, so that it occurs later?
6426 if (!DC->Encloses(SpecializedContext) &&
6427 !(isa<FunctionTemplateDecl>(Specialized) ||
6428 isa<FunctionDecl>(Specialized) ||
6429 isa<VarTemplateDecl>(Specialized) ||
6430 isa<VarDecl>(Specialized))) {
6431 if (isa<TranslationUnitDecl>(SpecializedContext))
6432 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6433 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00006434 else if (isa<NamespaceDecl>(SpecializedContext)) {
6435 int Diag = diag::err_template_spec_redecl_out_of_scope;
6436 if (S.getLangOpts().MicrosoftExt)
6437 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6438 S.Diag(Loc, Diag) << EntityKind << Specialized
6439 << cast<NamedDecl>(SpecializedContext);
6440 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00006441 llvm_unreachable("unexpected namespace context for specialization");
6442
6443 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6444 } else if ((!PrevDecl ||
6445 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6446 getTemplateSpecializationKind(PrevDecl) ==
6447 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006448 // C++ [temp.exp.spec]p2:
6449 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006450 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006451 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006452 // An explicit specialization of a member function, member class or
6453 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006454 // namespace of which the class template is a member.
6455 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006456 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006457 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006458 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006459 // C++11 [temp.explicit]p3:
6460 // An explicit instantiation shall appear in an enclosing namespace of its
6461 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006462 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006463 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006464 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006465 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006466 "DC encloses TU but isn't in enclosing namespace set");
6467 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006468 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006469 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6470 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006471 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006472 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006473 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006474 Diag = diag::ext_template_spec_decl_out_of_scope;
6475 else
6476 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6477 S.Diag(Loc, Diag)
6478 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006480
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006481 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006482 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006483 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006484
Douglas Gregorf47b9112009-02-25 22:02:03 +00006485 return false;
6486}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006487
Richard Smith57aae072016-12-28 02:37:25 +00006488static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
6489 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00006490 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006491 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006492 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00006493 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006494 return E->getSourceRange();
6495 return Checker.MatchLoc;
6496}
6497
6498static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6499 if (!TL.getType()->isDependentType())
6500 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006501 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006502 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00006503 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006504 return TL.getSourceRange();
6505 return Checker.MatchLoc;
6506}
6507
Larisse Voufo39a1e502013-08-06 01:03:05 +00006508/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006509/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006510static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006511 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6512 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006513 for (unsigned I = 0; I != NumArgs; ++I) {
6514 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006515 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006516 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6517 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006518 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006519
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006520 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006522
Eli Friedmanb826a002012-09-26 02:36:12 +00006523 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006524 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006525
6526 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006527
Douglas Gregor98318c22011-01-03 21:37:45 +00006528 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006529 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6530 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006531
6532 // Strip off any implicit casts we added as part of type checking.
6533 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6534 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006535
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006536 // C++ [temp.class.spec]p8:
6537 // A non-type argument is non-specialized if it is the name of a
6538 // non-type parameter. All other non-type arguments are
6539 // specialized.
6540 //
6541 // Below, we check the two conditions that only apply to
6542 // specialized non-type arguments, so skip any non-specialized
6543 // arguments.
6544 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006545 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006546 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006547
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006548 // C++ [temp.class.spec]p9:
6549 // Within the argument list of a class template partial
6550 // specialization, the following restrictions apply:
6551 // -- A partially specialized non-type argument expression
6552 // shall not involve a template parameter of the partial
6553 // specialization except when the argument expression is a
6554 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00006555 // -- The type of a template parameter corresponding to a
6556 // specialized non-type argument shall not be dependent on a
6557 // parameter of the specialization.
6558 // DR1315 removes the first bullet, leaving an incoherent set of rules.
6559 // We implement a compromise between the original rules and DR1315:
6560 // -- A specialized non-type template argument shall not be
6561 // type-dependent and the corresponding template parameter
6562 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00006563 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00006564 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00006565 if (ParamUseRange.isValid()) {
6566 if (IsDefaultArgument) {
6567 S.Diag(TemplateNameLoc,
6568 diag::err_dependent_non_type_arg_in_partial_spec);
6569 S.Diag(ParamUseRange.getBegin(),
6570 diag::note_dependent_non_type_default_arg_in_partial_spec)
6571 << ParamUseRange;
6572 } else {
6573 S.Diag(ParamUseRange.getBegin(),
6574 diag::err_dependent_non_type_arg_in_partial_spec)
6575 << ParamUseRange;
6576 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006577 return true;
6578 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006579
Richard Smith6056d5e2014-02-09 00:54:43 +00006580 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00006581 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00006582 if (ParamUseRange.isValid()) {
6583 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6584 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Richard Smith57aae072016-12-28 02:37:25 +00006585 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00006586 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00006587 << (IsDefaultArgument ? ParamUseRange : SourceRange())
6588 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006589 return true;
6590 }
6591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006592
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006593 return false;
6594}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006595
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006596/// \brief Check the non-type template arguments of a class template
6597/// partial specialization according to C++ [temp.class.spec]p9.
6598///
Richard Smith6056d5e2014-02-09 00:54:43 +00006599/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00006600/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006601/// template.
6602/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006603/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006604/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006605///
Richard Smith6056d5e2014-02-09 00:54:43 +00006606/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00006607bool Sema::CheckTemplatePartialSpecializationArgs(
6608 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
6609 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
6610 // We have to be conservative when checking a template in a dependent
6611 // context.
6612 if (PrimaryTemplate->getDeclContext()->isDependentContext())
6613 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006614
Richard Smith57aae072016-12-28 02:37:25 +00006615 TemplateParameterList *TemplateParams =
6616 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006617 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6618 NonTypeTemplateParmDecl *Param
6619 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6620 if (!Param)
6621 continue;
6622
Richard Smith57aae072016-12-28 02:37:25 +00006623 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
6624 Param, &TemplateArgs[I],
6625 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006626 return true;
6627 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006628
6629 return false;
6630}
6631
John McCall48871652010-08-21 09:40:31 +00006632DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006633Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6634 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006635 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006636 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006637 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006638 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006639 MultiTemplateParamsArg
6640 TemplateParameterLists,
6641 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006642 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006643
Richard Smith4b55a9c2014-04-17 03:29:33 +00006644 CXXScopeSpec &SS = TemplateId.SS;
6645
Abramo Bagnara60804e12011-03-18 15:16:37 +00006646 // NOTE: KWLoc is the location of the tag keyword. This will instead
6647 // store the location of the outermost template keyword in the declaration.
6648 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006649 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6650 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6651 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6652 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006653
Douglas Gregor67a65642009-02-17 23:15:12 +00006654 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006655 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006656 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006657 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6658
6659 if (!ClassTemplate) {
6660 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006661 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006662 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6663 return true;
6664 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006665
Richard Smithf445f192017-02-09 21:04:43 +00006666 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006667 bool isPartialSpecialization = false;
6668
Douglas Gregorf47b9112009-02-25 22:02:03 +00006669 // Check the validity of the template headers that introduce this
6670 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006671 // FIXME: We probably shouldn't complain about these headers for
6672 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006673 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006674 TemplateParameterList *TemplateParams =
6675 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006676 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00006677 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006678 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006679 if (Invalid)
6680 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006681
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006682 if (TemplateParams && TemplateParams->size() > 0) {
6683 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006684
Douglas Gregorec9518b2010-12-21 08:14:57 +00006685 if (TUK == TUK_Friend) {
6686 Diag(KWLoc, diag::err_partial_specialization_friend)
6687 << SourceRange(LAngleLoc, RAngleLoc);
6688 return true;
6689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006690
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006691 // C++ [temp.class.spec]p10:
6692 // The template parameter list of a specialization shall not
6693 // contain default template argument values.
6694 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6695 Decl *Param = TemplateParams->getParam(I);
6696 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6697 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006698 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006699 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006700 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006701 }
6702 } else if (NonTypeTemplateParmDecl *NTTP
6703 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6704 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006705 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006706 diag::err_default_arg_in_partial_spec)
6707 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006708 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006709 }
6710 } else {
6711 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006712 if (TTP->hasDefaultArgument()) {
6713 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006714 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006715 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006716 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006717 }
6718 }
6719 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006720 } else if (TemplateParams) {
6721 if (TUK == TUK_Friend)
6722 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006723 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006724 SourceRange(TemplateParams->getTemplateLoc(),
6725 TemplateParams->getRAngleLoc()))
6726 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00006727 } else {
6728 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006729 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006730
Douglas Gregor67a65642009-02-17 23:15:12 +00006731 // Check that the specialization uses the same tag kind as the
6732 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006733 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6734 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006735 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006736 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006737 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006738 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006739 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006740 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006741 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006742 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006743 diag::note_previous_use);
6744 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6745 }
6746
Douglas Gregorc40290e2009-03-09 23:48:35 +00006747 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006748 TemplateArgumentListInfo TemplateArgs =
6749 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006750
Douglas Gregor14406932011-01-03 20:35:03 +00006751 // Check for unexpanded parameter packs in any of the template arguments.
6752 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006753 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006754 UPPC_PartialSpecialization))
6755 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006756
Douglas Gregor67a65642009-02-17 23:15:12 +00006757 // Check that the template argument list is well-formed for this
6758 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006759 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006760 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6761 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006762 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006763
Douglas Gregor2373c592009-05-31 09:31:02 +00006764 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006765 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006766 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00006767 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
6768 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006769 return true;
6770
Richard Smith57aae072016-12-28 02:37:25 +00006771 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
6772 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00006773 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006774 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006775 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00006776 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006777 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6778 << ClassTemplate->getDeclName();
6779 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006780 }
6781 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006782
Craig Topperc3ec1492014-05-26 06:22:03 +00006783 void *InsertPos = nullptr;
6784 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006785
6786 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006787 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006788 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006789 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006790 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006791
Craig Topperc3ec1492014-05-26 06:22:03 +00006792 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006793
Douglas Gregorf47b9112009-02-25 22:02:03 +00006794 // Check whether we can declare a class template specialization in
6795 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006796 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006797 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6798 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006799 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006800 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006801
Douglas Gregor15301382009-07-30 17:40:51 +00006802 // The canonical type
6803 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006804 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006805 // Build the canonical type that describes the converted template
6806 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006807 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6808 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00006809 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006810
6811 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006812 ClassTemplate->getInjectedClassNameSpecialization())) {
6813 // C++ [temp.class.spec]p9b3:
6814 //
6815 // -- The argument list of the specialization shall not be identical
6816 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00006817 //
6818 // This rule has since been removed, because it's redundant given DR1495,
6819 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006820 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006821 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006822 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006823 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6824 ClassTemplate->getIdentifier(),
6825 TemplateNameLoc,
6826 Attr,
6827 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006828 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006829 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006830 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006831 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006832 }
Douglas Gregor15301382009-07-30 17:40:51 +00006833
Douglas Gregor2373c592009-05-31 09:31:02 +00006834 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006835 ClassTemplatePartialSpecializationDecl *PrevPartial
6836 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006837 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006838 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006839 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006840 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006841 TemplateParams,
6842 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006843 Converted,
John McCall6b51f282009-11-23 01:53:49 +00006844 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006845 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006846 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006847 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006848 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006849 Partial->setTemplateParameterListsInfo(
6850 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006851 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006852
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006853 if (!PrevPartial)
6854 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006855 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006856
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006857 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006858 // template specialization, make a note of that.
6859 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6860 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006861
Richard Smith57aae072016-12-28 02:37:25 +00006862 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00006863 } else {
6864 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006865 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006866 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006867 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006868 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006869 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006870 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006871 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00006872 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006873 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006874 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006875 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006876 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006877 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006878
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006879 if (!PrevDecl)
6880 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006881
David Majnemer678f50b2015-11-18 19:49:19 +00006882 if (CurContext->isDependentContext()) {
6883 // -fms-extensions permits specialization of nested classes without
6884 // fully specializing the outer class(es).
6885 assert(getLangOpts().MicrosoftExt &&
6886 "Only possible with -fms-extensions!");
6887 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6888 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00006889 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00006890 } else {
6891 CanonType = Context.getTypeDeclType(Specialization);
6892 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006893 }
6894
Douglas Gregor06db9f52009-10-12 20:18:28 +00006895 // C++ [temp.expl.spec]p6:
6896 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006897 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006898 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006899 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006900 // use occurs; no diagnostic is required.
6901 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006902 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006903 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006904 // Is there any previous explicit specialization declaration?
6905 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6906 Okay = true;
6907 break;
6908 }
6909 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006910
Douglas Gregorc854c662010-02-26 06:03:23 +00006911 if (!Okay) {
6912 SourceRange Range(TemplateNameLoc, RAngleLoc);
6913 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6914 << Context.getTypeDeclType(Specialization) << Range;
6915
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006916 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006917 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006918 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006919 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006920 return true;
6921 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006923
Douglas Gregor2208a292009-09-26 20:57:03 +00006924 // If this is not a friend, note that this is an explicit specialization.
6925 if (TUK != TUK_Friend)
6926 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006927
6928 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006929 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006930 RecordDecl *Def = Specialization->getDefinition();
6931 NamedDecl *Hidden = nullptr;
6932 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6933 SkipBody->ShouldSkip = true;
6934 makeMergedDefinitionVisible(Hidden, KWLoc);
6935 // From here on out, treat this as just a redeclaration.
6936 TUK = TUK_Declaration;
6937 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006938 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00006939 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006940 Diag(Def->getLocation(), diag::note_previous_definition);
6941 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006942 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006943 }
6944 }
6945
John McCall659a3372010-12-18 03:30:47 +00006946 if (Attr)
6947 ProcessDeclAttributeList(S, Specialization, Attr);
6948
Richard Smith034b94a2012-08-17 03:20:55 +00006949 // Add alignment attributes if necessary; these attributes are checked when
6950 // the ASTContext lays out the structure.
6951 if (TUK == TUK_Definition) {
6952 AddAlignmentAttributesForRecord(Specialization);
6953 AddMsStructLayoutForRecord(Specialization);
6954 }
6955
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006956 if (ModulePrivateLoc.isValid())
6957 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6958 << (isPartialSpecialization? 1 : 0)
6959 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00006960
Douglas Gregord56a91e2009-02-26 22:19:44 +00006961 // Build the fully-sugared type for this class template
6962 // specialization as the user wrote in the specialization
6963 // itself. This means that we'll pretty-print the type retrieved
6964 // from the specialization's declaration the way that the user
6965 // actually wrote the specialization, rather than formatting the
6966 // name based on the "canonical" representation used to store the
6967 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006968 TypeSourceInfo *WrittenTy
6969 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6970 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006971 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006972 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006973 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006974 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006975
Douglas Gregor1e249f82009-02-25 22:18:32 +00006976 // C++ [temp.expl.spec]p9:
6977 // A template explicit specialization is in the scope of the
6978 // namespace in which the template was defined.
6979 //
6980 // We actually implement this paragraph where we set the semantic
6981 // context (in the creation of the ClassTemplateSpecializationDecl),
6982 // but we also maintain the lexical context where the actual
6983 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006984 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006985
Douglas Gregor67a65642009-02-17 23:15:12 +00006986 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006987 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006988 Specialization->startDefinition();
6989
Douglas Gregor2208a292009-09-26 20:57:03 +00006990 if (TUK == TUK_Friend) {
6991 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6992 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006993 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006994 /*FIXME:*/KWLoc);
6995 Friend->setAccess(AS_public);
6996 CurContext->addDecl(Friend);
6997 } else {
6998 // Add the specialization into its lexical context, so that it can
6999 // be seen when iterating through the list of declarations in that
7000 // context. However, specializations are not found by name lookup.
7001 CurContext->addDecl(Specialization);
7002 }
John McCall48871652010-08-21 09:40:31 +00007003 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007004}
Douglas Gregor333489b2009-03-27 23:10:48 +00007005
John McCall48871652010-08-21 09:40:31 +00007006Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007007 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007008 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007009 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007010 ActOnDocumentableDecl(NewDecl);
7011 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007012}
7013
John McCall4f7ced62010-02-11 01:33:53 +00007014/// \brief Strips various properties off an implicit instantiation
7015/// that has just been explicitly specialized.
7016static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007017 D->dropAttr<DLLImportAttr>();
7018 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007019
Nico Webere4974382014-12-19 23:52:45 +00007020 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007021 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007022}
7023
Nico Webera8f80b32012-01-09 19:52:25 +00007024/// \brief Compute the diagnostic location for an explicit instantiation
7025// declaration or definition.
7026static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007027 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007028 // Explicit instantiations following a specialization have no effect and
7029 // hence no PointOfInstantiation. In that case, walk decl backwards
7030 // until a valid name loc is found.
7031 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007032 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7033 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007034 PrevDiagLoc = Prev->getLocation();
7035 }
7036 assert(PrevDiagLoc.isValid() &&
7037 "Explicit instantiation without point of instantiation?");
7038 return PrevDiagLoc;
7039}
7040
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007041/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007042/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007043/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007044/// new specialization/instantiation will have any effect.
7045///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007046/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007047/// instantiation.
7048///
7049/// \param NewTSK the kind of the new explicit specialization or instantiation.
7050///
7051/// \param PrevDecl the previous declaration of the entity.
7052///
7053/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7054///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007055/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007056/// declaration was instantiated (either implicitly or explicitly).
7057///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007058/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007059/// specialization or instantiation has no effect and should be ignored.
7060///
7061/// \returns true if there was an error that should prevent the introduction of
7062/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007063bool
7064Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7065 TemplateSpecializationKind NewTSK,
7066 NamedDecl *PrevDecl,
7067 TemplateSpecializationKind PrevTSK,
7068 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007069 bool &HasNoEffect) {
7070 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007071
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007072 switch (NewTSK) {
7073 case TSK_Undeclared:
7074 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007075 assert(
7076 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7077 "previous declaration must be implicit!");
7078 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007079
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007080 case TSK_ExplicitSpecialization:
7081 switch (PrevTSK) {
7082 case TSK_Undeclared:
7083 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007084 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007085 // explicitly specialized or has merely been mentioned without any
7086 // instantiation.
7087 return false;
7088
7089 case TSK_ImplicitInstantiation:
7090 if (PrevPointOfInstantiation.isInvalid()) {
7091 // The declaration itself has not actually been instantiated, so it is
7092 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007093 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007094 return false;
7095 }
7096 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007097
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007098 case TSK_ExplicitInstantiationDeclaration:
7099 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007100 assert((PrevTSK == TSK_ImplicitInstantiation ||
7101 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007102 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007103
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007104 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007105 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007106 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007107 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007108 // implicit instantiation to take place, in every translation unit in
7109 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007110 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007111 // Is there any previous explicit specialization declaration?
7112 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7113 return false;
7114 }
7115
Douglas Gregor1d957a32009-10-27 18:42:08 +00007116 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007117 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007118 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007119 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007120
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007121 return true;
7122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007123
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007124 case TSK_ExplicitInstantiationDeclaration:
7125 switch (PrevTSK) {
7126 case TSK_ExplicitInstantiationDeclaration:
7127 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007128 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007129 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007130
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007131 case TSK_Undeclared:
7132 case TSK_ImplicitInstantiation:
7133 // We're explicitly instantiating something that may have already been
7134 // implicitly instantiated; that's fine.
7135 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007136
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007137 case TSK_ExplicitSpecialization:
7138 // C++0x [temp.explicit]p4:
7139 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007140 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007141 // specialization for that template, the explicit instantiation has no
7142 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007143 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007144 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007145
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007146 case TSK_ExplicitInstantiationDefinition:
7147 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007148 // If an entity is the subject of both an explicit instantiation
7149 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007150 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007151 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007152 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007153
7154 // Explicit instantiations following a specialization have no effect and
7155 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7156 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007157 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7158 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007159 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007160 return false;
7161 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007162
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007163 case TSK_ExplicitInstantiationDefinition:
7164 switch (PrevTSK) {
7165 case TSK_Undeclared:
7166 case TSK_ImplicitInstantiation:
7167 // We're explicitly instantiating something that may have already been
7168 // implicitly instantiated; that's fine.
7169 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007170
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007171 case TSK_ExplicitSpecialization:
7172 // C++ DR 259, C++0x [temp.explicit]p4:
7173 // For a given set of template parameters, if an explicit
7174 // instantiation of a template appears after a declaration of
7175 // an explicit specialization for that template, the explicit
7176 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00007177 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007178 << PrevDecl;
7179 Diag(PrevDecl->getLocation(),
7180 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007181 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007182 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007183
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007184 case TSK_ExplicitInstantiationDeclaration:
7185 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007186 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00007187
7188 // C++0x [temp.explicit]p4:
7189 // For a given set of template parameters, if an explicit instantiation
7190 // of a template appears after a declaration of an explicit
7191 // specialization for that template, the explicit instantiation has no
7192 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007193 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00007194 // Is there any previous explicit specialization declaration?
7195 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7196 HasNoEffect = true;
7197 break;
7198 }
7199 }
7200
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007201 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007202
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007203 case TSK_ExplicitInstantiationDefinition:
7204 // C++0x [temp.spec]p5:
7205 // For a given template and a given set of template-arguments,
7206 // - an explicit instantiation definition shall appear at most once
7207 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007208
7209 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7210 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00007211 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007212 : diag::err_explicit_instantiation_duplicate)
7213 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00007214 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00007215 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007216 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007217 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007218 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007219 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007220
David Blaikie83d382b2011-09-23 05:06:16 +00007221 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007222}
7223
John McCallb9c78482010-04-08 09:05:18 +00007224/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00007225/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00007226///
James Dennettf14a6e52012-06-15 22:23:43 +00007227/// The only possible way to get a dependent function template specialization
7228/// is with a friend declaration, like so:
7229///
7230/// \code
7231/// template \<class T> void foo(T);
7232/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00007233/// friend void foo<>(T);
7234/// };
James Dennettf14a6e52012-06-15 22:23:43 +00007235/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00007236///
7237/// There really isn't any useful analysis we can do here, so we
7238/// just store the information.
7239bool
7240Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7241 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7242 LookupResult &Previous) {
7243 // Remove anything from Previous that isn't a function template in
7244 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00007245 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00007246 LookupResult::Filter F = Previous.makeFilter();
7247 while (F.hasNext()) {
7248 NamedDecl *D = F.next()->getUnderlyingDecl();
7249 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00007250 !FDLookupContext->InEnclosingNamespaceSetOf(
7251 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00007252 F.erase();
7253 }
7254 F.done();
7255
7256 // Should this be diagnosed here?
7257 if (Previous.empty()) return true;
7258
7259 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7260 ExplicitTemplateArgs);
7261 return false;
7262}
7263
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007264/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007265/// specialization.
7266///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007267/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007268/// explicit function template specialization. On successful completion,
7269/// the function declaration \p FD will become a function template
7270/// specialization.
7271///
7272/// \param FD the function declaration, which will be updated to become a
7273/// function template specialization.
7274///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007275/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7276/// if any. Note that this may be valid info even when 0 arguments are
7277/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7278/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007279///
Francois Pichet3a44e432011-07-08 06:21:47 +00007280/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007281/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007282bool Sema::CheckFunctionTemplateSpecialization(
7283 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7284 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007285 // The set of function template specializations that could match this
7286 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00007287 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007288 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7289 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007290
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007291 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7292 ConvertedTemplateArgs;
7293
Sebastian Redl50c68252010-08-31 00:36:30 +00007294 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00007295 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7296 I != E; ++I) {
7297 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7298 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007299 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007300 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007301 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7302 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007303 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007304
Richard Smith574f4f62013-01-14 05:37:29 +00007305 // When matching a constexpr member function template specialization
7306 // against the primary template, we don't yet know whether the
7307 // specialization has an implicit 'const' (because we don't know whether
7308 // it will be a static member function until we know which template it
7309 // specializes), so adjust it now assuming it specializes this template.
7310 QualType FT = FD->getType();
7311 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007312 CXXMethodDecl *OldMD =
7313 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00007314 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007315 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00007316 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7317 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007318 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007319 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00007320 }
7321 }
7322
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007323 TemplateArgumentListInfo Args;
7324 if (ExplicitTemplateArgs)
7325 Args = *ExplicitTemplateArgs;
7326
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007327 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007328 // A trailing template-argument can be left unspecified in the
7329 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007330 // provided it can be deduced from the function argument type.
7331 // Perform template argument deduction to determine whether we may be
7332 // specializing this template.
7333 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00007334 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007335 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00007336 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7337 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00007338 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7339 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007340 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007341 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00007342 FailedCandidates.addCandidate().set(
7343 I.getPair(), FunTmpl->getTemplatedDecl(),
7344 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007345 (void)TDK;
7346 continue;
7347 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007348
Artem Belevich64135c32016-12-08 19:38:13 +00007349 // Target attributes are part of the cuda function signature, so
7350 // the deduced template's cuda target must match that of the
7351 // specialization. Given that C++ template deduction does not
7352 // take target attributes into account, we reject candidates
7353 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007354 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00007355 IdentifyCUDATarget(Specialization,
7356 /* IgnoreImplicitHDAttributes = */ true) !=
7357 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007358 FailedCandidates.addCandidate().set(
7359 I.getPair(), FunTmpl->getTemplatedDecl(),
7360 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7361 continue;
7362 }
7363
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007364 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007365 if (ExplicitTemplateArgs)
7366 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00007367 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007368 }
7369 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007370
Douglas Gregor5de279c2009-09-26 03:41:46 +00007371 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007372 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007373 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007374 FD->getLocation(),
7375 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7376 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00007377 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007378 PDiag(diag::note_function_template_spec_matched));
7379
John McCall58cc69d2010-01-27 01:50:18 +00007380 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007381 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007382
7383 // Ignore access information; it doesn't figure into redeclaration checking.
7384 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007385
Nathan Wilson83839122016-04-09 02:55:27 +00007386 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7387 // an explicit specialization (14.8.3) [...] of a concept definition.
7388 if (Specialization->getPrimaryTemplate()->isConcept()) {
7389 Diag(FD->getLocation(), diag::err_concept_specialized)
7390 << 0 /*function*/ << 1 /*explicitly specialized*/;
7391 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7392 return true;
7393 }
7394
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007395 FunctionTemplateSpecializationInfo *SpecInfo
7396 = Specialization->getTemplateSpecializationInfo();
7397 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007398
7399 // Note: do not overwrite location info if previous template
7400 // specialization kind was explicit.
7401 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00007402 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00007403 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00007404 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7405 // function can differ from the template declaration with respect to
7406 // the constexpr specifier.
7407 Specialization->setConstexpr(FD->isConstexpr());
7408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007409
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007410 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00007411 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00007412
7413 // If this is a friend declaration, then we're not really declaring
7414 // an explicit specialization.
7415 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007416
Douglas Gregor54888652009-10-07 00:13:32 +00007417 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00007418 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007419 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00007420 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007421 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007422 false))
Douglas Gregor54888652009-10-07 00:13:32 +00007423 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007424
7425 // C++ [temp.expl.spec]p6:
7426 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007427 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007428 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007429 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007430 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007431 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007432 if (!isFriend &&
7433 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007434 TSK_ExplicitSpecialization,
7435 Specialization,
7436 SpecInfo->getTemplateSpecializationKind(),
7437 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007438 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007439 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00007440
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007441 // Mark the prior declaration as an explicit specialization, so that later
7442 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007443 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007444 // Since explicit specializations do not inherit '=delete' from their
7445 // primary function template - check if the 'specialization' that was
7446 // implicitly generated (during template argument deduction for partial
7447 // ordering) from the most specialized of all the function templates that
7448 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7449 // first check that it was implicitly generated during template argument
7450 // deduction by making sure it wasn't referenced, and then reset the deleted
7451 // flag to not-deleted, so that we can inherit that information from 'FD'.
7452 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7453 !Specialization->getCanonicalDecl()->isReferenced()) {
7454 assert(
7455 Specialization->getCanonicalDecl() == Specialization &&
7456 "This must be the only existing declaration of this specialization");
7457 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007458 }
John McCall816d75b2010-03-24 07:46:06 +00007459 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007460 MarkUnusedFileScopedDecl(Specialization);
7461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007462
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007463 // Turn the given function declaration into a function template
7464 // specialization, with the template arguments from the previous
7465 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007466 // Take copies of (semantic and syntactic) template argument lists.
7467 const TemplateArgumentList* TemplArgs = new (Context)
7468 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007469 FD->setFunctionTemplateSpecialization(
7470 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7471 SpecInfo->getTemplateSpecializationKind(),
7472 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007473
Artem Belevich64135c32016-12-08 19:38:13 +00007474 // A function template specialization inherits the target attributes
7475 // of its template. (We require the attributes explicitly in the
7476 // code to match, but a template may have implicit attributes by
7477 // virtue e.g. of being constexpr, and it passes these implicit
7478 // attributes on to its specializations.)
7479 if (LangOpts.CUDA)
7480 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
7481
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007482 // The "previous declaration" for this function template specialization is
7483 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007484 Previous.clear();
7485 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007486 return false;
7487}
7488
Douglas Gregor86d142a2009-10-08 07:24:58 +00007489/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007490/// specialization.
7491///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007492/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007493/// explicit member function specialization. On successful completion,
7494/// the function declaration \p FD will become a member function
7495/// specialization.
7496///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007497/// \param Member the member declaration, which will be updated to become a
7498/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007499///
John McCall1f82f242009-11-18 22:49:29 +00007500/// \param Previous the set of declarations, one of which may be specialized
7501/// by this function specialization; the set will be modified to contain the
7502/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007503bool
John McCall1f82f242009-11-18 22:49:29 +00007504Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007505 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007506
Douglas Gregor86d142a2009-10-08 07:24:58 +00007507 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007508 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007509 NamedDecl *Instantiation = nullptr;
7510 NamedDecl *InstantiatedFrom = nullptr;
7511 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007512
John McCall1f82f242009-11-18 22:49:29 +00007513 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007514 // Nowhere to look anyway.
7515 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007516 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7517 I != E; ++I) {
7518 NamedDecl *D = (*I)->getUnderlyingDecl();
7519 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007520 QualType Adjusted = Function->getType();
7521 if (!hasExplicitCallingConv(Adjusted))
7522 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7523 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007524 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007525 Instantiation = Method;
7526 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007527 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007528 break;
7529 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007530 }
7531 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007532 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007533 VarDecl *PrevVar;
7534 if (Previous.isSingleResult() &&
7535 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007536 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007537 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007538 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007539 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007540 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007541 }
7542 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007543 CXXRecordDecl *PrevRecord;
7544 if (Previous.isSingleResult() &&
7545 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007546 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007547 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007548 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007549 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007550 }
Richard Smith7d137e32012-03-23 03:33:32 +00007551 } else if (isa<EnumDecl>(Member)) {
7552 EnumDecl *PrevEnum;
7553 if (Previous.isSingleResult() &&
7554 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007555 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007556 Instantiation = PrevEnum;
7557 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7558 MSInfo = PrevEnum->getMemberSpecializationInfo();
7559 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007560 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007561
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007562 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007563 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007564 // specializations are always out-of-line, the caller will complain about
7565 // this mismatch later.
7566 return false;
7567 }
John McCalle820e5e2010-04-13 20:37:33 +00007568
7569 // If this is a friend, just bail out here before we start turning
7570 // things into explicit specializations.
7571 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7572 // Preserve instantiation information.
7573 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7574 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7575 cast<CXXMethodDecl>(InstantiatedFrom),
7576 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7577 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7578 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7579 cast<CXXRecordDecl>(InstantiatedFrom),
7580 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7581 }
7582
7583 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007584 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007585 return false;
7586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007587
Douglas Gregor86d142a2009-10-08 07:24:58 +00007588 // Make sure that this is a specialization of a member.
7589 if (!InstantiatedFrom) {
7590 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7591 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007592 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7593 return true;
7594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007595
Douglas Gregor06db9f52009-10-12 20:18:28 +00007596 // C++ [temp.expl.spec]p6:
7597 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007598 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007599 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007600 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007601 // use occurs; no diagnostic is required.
7602 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007603
Abramo Bagnara8075c852010-06-12 07:44:57 +00007604 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007605 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7606 TSK_ExplicitSpecialization,
7607 Instantiation,
7608 MSInfo->getTemplateSpecializationKind(),
7609 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007610 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007611 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007612
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007613 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007614 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007615 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007616 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007617 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007618 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007619
Douglas Gregor86d142a2009-10-08 07:24:58 +00007620 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007621 // the original declaration to note that it is an explicit specialization
7622 // (if it was previously an implicit instantiation). This latter step
7623 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007624 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007625 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7626 if (InstantiationFunction->getTemplateSpecializationKind() ==
7627 TSK_ImplicitInstantiation) {
7628 InstantiationFunction->setTemplateSpecializationKind(
7629 TSK_ExplicitSpecialization);
7630 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007631 // Explicit specializations of member functions of class templates do not
7632 // inherit '=delete' from the member function they are specializing.
7633 if (InstantiationFunction->isDeleted()) {
7634 assert(InstantiationFunction->getCanonicalDecl() ==
7635 InstantiationFunction);
Richard Smith5f274382016-09-28 23:55:27 +00007636 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007637 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007639
Douglas Gregor86d142a2009-10-08 07:24:58 +00007640 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7641 cast<CXXMethodDecl>(InstantiatedFrom),
7642 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007643 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007644 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007645 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7646 if (InstantiationVar->getTemplateSpecializationKind() ==
7647 TSK_ImplicitInstantiation) {
7648 InstantiationVar->setTemplateSpecializationKind(
7649 TSK_ExplicitSpecialization);
7650 InstantiationVar->setLocation(Member->getLocation());
7651 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007652
Larisse Voufo39a1e502013-08-06 01:03:05 +00007653 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7654 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007655 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007656 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007657 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7658 if (InstantiationClass->getTemplateSpecializationKind() ==
7659 TSK_ImplicitInstantiation) {
7660 InstantiationClass->setTemplateSpecializationKind(
7661 TSK_ExplicitSpecialization);
7662 InstantiationClass->setLocation(Member->getLocation());
7663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007664
Douglas Gregor86d142a2009-10-08 07:24:58 +00007665 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007666 cast<CXXRecordDecl>(InstantiatedFrom),
7667 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007668 } else {
7669 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7670 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7671 if (InstantiationEnum->getTemplateSpecializationKind() ==
7672 TSK_ImplicitInstantiation) {
7673 InstantiationEnum->setTemplateSpecializationKind(
7674 TSK_ExplicitSpecialization);
7675 InstantiationEnum->setLocation(Member->getLocation());
7676 }
7677
7678 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7679 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007680 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007681
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007682 // Save the caller the trouble of having to figure out which declaration
7683 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007684 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007685 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007686 return false;
7687}
7688
Douglas Gregore47f5a72009-10-14 23:41:34 +00007689/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007690///
7691/// \returns true if a serious error occurs, false otherwise.
7692static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007693 SourceLocation InstLoc,
7694 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007695 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7696 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007697
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007698 if (CurContext->isRecord()) {
7699 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7700 << D;
7701 return true;
7702 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007703
Richard Smith050d2612011-10-18 02:28:33 +00007704 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007705 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007706 // template. If the name declared in the explicit instantiation is an
7707 // unqualified name, the explicit instantiation shall appear in the
7708 // namespace where its template is declared or, if that namespace is inline
7709 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007710 //
7711 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007712 if (WasQualifiedName) {
7713 if (CurContext->Encloses(OrigContext))
7714 return false;
7715 } else {
7716 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7717 return false;
7718 }
7719
7720 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7721 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007722 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007723 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007724 diag::err_explicit_instantiation_out_of_scope :
7725 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007726 << D << NS;
7727 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007728 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007729 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007730 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7731 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7732 << D << NS;
7733 } else
7734 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007735 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007736 diag::err_explicit_instantiation_must_be_global :
7737 diag::warn_explicit_instantiation_must_be_global_0x)
7738 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007739 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007740 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007741}
7742
7743/// \brief Determine whether the given scope specifier has a template-id in it.
7744static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7745 if (!SS.isSet())
7746 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007747
Richard Smith050d2612011-10-18 02:28:33 +00007748 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007749 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007750 // or a static data member of a class template specialization, the name of
7751 // the class template specialization in the qualified-id for the member
7752 // name shall be a simple-template-id.
7753 //
7754 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007755 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7756 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007757 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007758 if (isa<TemplateSpecializationType>(T))
7759 return true;
7760
7761 return false;
7762}
7763
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007764/// Make a dllexport or dllimport attr on a class template specialization take
7765/// effect.
7766static void dllExportImportClassTemplateSpecialization(
7767 Sema &S, ClassTemplateSpecializationDecl *Def) {
7768 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
7769 assert(A && "dllExportImportClassTemplateSpecialization called "
7770 "on Def without dllexport or dllimport");
7771
7772 // We reject explicit instantiations in class scope, so there should
7773 // never be any delayed exported classes to worry about.
7774 assert(S.DelayedDllExportClasses.empty() &&
7775 "delayed exports present at explicit instantiation");
7776 S.checkClassLevelDLLAttribute(Def);
7777
7778 // Propagate attribute to base class templates.
7779 for (auto &B : Def->bases()) {
7780 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7781 B.getType()->getAsCXXRecordDecl()))
7782 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7783 }
7784
7785 S.referenceDLLExportedClassMethods();
7786}
7787
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007788// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007789DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007790Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007791 SourceLocation ExternLoc,
7792 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007793 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007794 SourceLocation KWLoc,
7795 const CXXScopeSpec &SS,
7796 TemplateTy TemplateD,
7797 SourceLocation TemplateNameLoc,
7798 SourceLocation LAngleLoc,
7799 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007800 SourceLocation RAngleLoc,
7801 AttributeList *Attr) {
7802 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007803 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007804 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007805 // Check that the specialization uses the same tag kind as the
7806 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007807 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7808 assert(Kind != TTK_Enum &&
7809 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007810
Richard Trieu265c3442016-04-05 21:13:54 +00007811 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7812
7813 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00007814 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
7815 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00007816 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00007817 return true;
7818 }
7819
Douglas Gregord9034f02009-05-14 16:41:31 +00007820 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007821 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007822 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007823 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007824 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007825 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007826 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007827 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007828 diag::note_previous_use);
7829 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7830 }
7831
Douglas Gregore47f5a72009-10-14 23:41:34 +00007832 // C++0x [temp.explicit]p2:
7833 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007834 // definition and an explicit instantiation declaration. An explicit
7835 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007836 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7837 ? TSK_ExplicitInstantiationDefinition
7838 : TSK_ExplicitInstantiationDeclaration;
7839
7840 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7841 // Check for dllexport class template instantiation declarations.
7842 for (AttributeList *A = Attr; A; A = A->getNext()) {
7843 if (A->getKind() == AttributeList::AT_DLLExport) {
7844 Diag(ExternLoc,
7845 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7846 Diag(A->getLoc(), diag::note_attribute);
7847 break;
7848 }
7849 }
7850
7851 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7852 Diag(ExternLoc,
7853 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7854 Diag(A->getLocation(), diag::note_attribute);
7855 }
7856 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007857
Hans Wennborga86a83b2016-05-26 19:42:56 +00007858 // In MSVC mode, dllimported explicit instantiation definitions are treated as
7859 // instantiation declarations for most purposes.
7860 bool DLLImportExplicitInstantiationDef = false;
7861 if (TSK == TSK_ExplicitInstantiationDefinition &&
7862 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7863 // Check for dllimport class template instantiation definitions.
7864 bool DLLImport =
7865 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7866 for (AttributeList *A = Attr; A; A = A->getNext()) {
7867 if (A->getKind() == AttributeList::AT_DLLImport)
7868 DLLImport = true;
7869 if (A->getKind() == AttributeList::AT_DLLExport) {
7870 // dllexport trumps dllimport here.
7871 DLLImport = false;
7872 break;
7873 }
7874 }
7875 if (DLLImport) {
7876 TSK = TSK_ExplicitInstantiationDeclaration;
7877 DLLImportExplicitInstantiationDef = true;
7878 }
7879 }
7880
Douglas Gregora1f49972009-05-13 00:25:59 +00007881 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007882 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007883 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007884
7885 // Check that the template argument list is well-formed for this
7886 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007887 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007888 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7889 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007890 return true;
7891
Douglas Gregora1f49972009-05-13 00:25:59 +00007892 // Find the class template specialization declaration that
7893 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007894 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007895 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007896 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007897
Abramo Bagnara8075c852010-06-12 07:44:57 +00007898 TemplateSpecializationKind PrevDecl_TSK
7899 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7900
Douglas Gregor54888652009-10-07 00:13:32 +00007901 // C++0x [temp.explicit]p2:
7902 // [...] An explicit instantiation shall appear in an enclosing
7903 // namespace of its template. [...]
7904 //
7905 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007906 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7907 SS.isSet()))
7908 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007909
Craig Topperc3ec1492014-05-26 06:22:03 +00007910 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007911
Abramo Bagnara8075c852010-06-12 07:44:57 +00007912 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007913 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007914 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007915 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007916 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007917 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007918 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007919
Abramo Bagnara8075c852010-06-12 07:44:57 +00007920 // Even though HasNoEffect == true means that this explicit instantiation
7921 // has no effect on semantics, we go on to put its syntax in the AST.
7922
7923 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7924 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007925 // Since the only prior class template specialization with these
7926 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007927 // declaration node as our own, updating the source location
7928 // for the template name to reflect our new declaration.
7929 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007930 Specialization = PrevDecl;
7931 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007932 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007933 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00007934
7935 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7936 DLLImportExplicitInstantiationDef) {
7937 // The new specialization might add a dllimport attribute.
7938 HasNoEffect = false;
7939 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007940 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007941
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007942 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007943 // Create a new class template specialization declaration node for
7944 // this explicit specialization.
7945 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007946 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007947 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007948 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007949 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007950 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007951 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007952 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007953
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007954 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007955 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007956 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007957 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007958 }
7959
7960 // Build the fully-sugared type for this explicit instantiation as
7961 // the user wrote in the explicit instantiation itself. This means
7962 // that we'll pretty-print the type retrieved from the
7963 // specialization's declaration the way that the user actually wrote
7964 // the explicit instantiation, rather than formatting the name based
7965 // on the "canonical" representation used to store the template
7966 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007967 TypeSourceInfo *WrittenTy
7968 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7969 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007970 Context.getTypeDeclType(Specialization));
7971 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007972
Abramo Bagnara8075c852010-06-12 07:44:57 +00007973 // Set source locations for keywords.
7974 Specialization->setExternLoc(ExternLoc);
7975 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00007976 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007977
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00007978 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Rafael Espindola0b062072012-01-03 06:04:21 +00007979 if (Attr)
7980 ProcessDeclAttributeList(S, Specialization, Attr);
7981
Abramo Bagnara8075c852010-06-12 07:44:57 +00007982 // Add the explicit instantiation into its lexical context. However,
7983 // since explicit instantiations are never found by name lookup, we
7984 // just put it into the declaration context directly.
7985 Specialization->setLexicalDeclContext(CurContext);
7986 CurContext->addDecl(Specialization);
7987
7988 // Syntax is now OK, so return if it has no other effect on semantics.
7989 if (HasNoEffect) {
7990 // Set the template specialization kind.
7991 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007992 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007993 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007994
7995 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007996 // A definition of a class template or class member template
7997 // shall be in scope at the point of the explicit instantiation of
7998 // the class template or class member template.
7999 //
8000 // This check comes when we actually try to perform the
8001 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008002 ClassTemplateSpecializationDecl *Def
8003 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008004 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008005 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00008006 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008007 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008008 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008009 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8010 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008011
Douglas Gregor1d957a32009-10-27 18:42:08 +00008012 // Instantiate the members of this class template specialization.
8013 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008014 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00008015 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008016 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008017 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8018 // TSK_ExplicitInstantiationDefinition
8019 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00008020 (TSK == TSK_ExplicitInstantiationDefinition ||
8021 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00008022 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008023 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008024
Hans Wennborgc0875502015-06-09 00:39:05 +00008025 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00008026 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8027 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00008028 // In the MS ABI, an explicit instantiation definition can add a dll
8029 // attribute to a template with a previous instantiation declaration.
8030 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008031 auto *A = cast<InheritableAttr>(
8032 getDLLAttr(Specialization)->clone(getASTContext()));
8033 A->setInherited(true);
8034 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008035 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008036 }
8037 }
8038
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008039 // Fix a TSK_ImplicitInstantiation followed by a
8040 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008041 bool NewlyDLLExported =
8042 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8043 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008044 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8045 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8046 // In the MS ABI, an explicit instantiation definition can add a dll
8047 // attribute to a template with a previous implicit instantiation.
8048 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8049 // avoid potentially strange codegen behavior. For example, if we extend
8050 // this conditional to dllimport, and we have a source file calling a
8051 // method on an implicitly instantiated template class instance and then
8052 // declaring a dllimport explicit instantiation definition for the same
8053 // template class, the codegen for the method call will not respect the
8054 // dllimport, while it will with cl. The Def will already have the DLL
8055 // attribute, since the Def and Specialization will be the same in the
8056 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8057 // attribute to the Specialization; we just need to make it take effect.
8058 assert(Def == Specialization &&
8059 "Def and Specialization should match for implicit instantiation");
8060 dllExportImportClassTemplateSpecialization(*this, Def);
8061 }
8062
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008063 // Set the template specialization kind. Make sure it is set before
8064 // instantiating the members which will trigger ASTConsumer callbacks.
8065 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008066 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008067 } else {
8068
8069 // Set the template specialization kind.
8070 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008071 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008072
John McCall48871652010-08-21 09:40:31 +00008073 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008074}
8075
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008076// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008077DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008078Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008079 SourceLocation ExternLoc,
8080 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008081 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008082 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008083 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008084 IdentifierInfo *Name,
8085 SourceLocation NameLoc,
8086 AttributeList *Attr) {
8087
Douglas Gregord6ab8742009-05-28 23:31:59 +00008088 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008089 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008090 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008091 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008092 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008093 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008094 SourceLocation(), false, TypeResult(),
8095 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00008096 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8097
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008098 if (!TagD)
8099 return true;
8100
John McCall48871652010-08-21 09:40:31 +00008101 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00008102 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008103
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008104 if (Tag->isInvalidDecl())
8105 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008106
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008107 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8108 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8109 if (!Pattern) {
8110 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8111 << Context.getTypeDeclType(Record);
8112 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8113 return true;
8114 }
8115
Douglas Gregore47f5a72009-10-14 23:41:34 +00008116 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008117 // If the explicit instantiation is for a class or member class, the
8118 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00008119 // simple-template-id.
8120 //
8121 // C++98 has the same restriction, just worded differently.
8122 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00008123 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008124 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008125
Douglas Gregore47f5a72009-10-14 23:41:34 +00008126 // C++0x [temp.explicit]p2:
8127 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008128 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00008129 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00008130 TemplateSpecializationKind TSK
8131 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8132 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008133
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008134 // C++0x [temp.explicit]p2:
8135 // [...] An explicit instantiation shall appear in an enclosing
8136 // namespace of its template. [...]
8137 //
8138 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008139 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008140
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008141 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008142 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00008143 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008144 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00008145 PrevDecl = Record;
8146 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008147 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008148 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008149 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008150 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008151 PrevDecl,
8152 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008153 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008154 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008155 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00008156 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008157 return TagD;
8158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008159
Douglas Gregor12e49d32009-10-15 22:53:21 +00008160 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008161 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008162 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00008163 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008164 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00008165 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008166 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008167 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00008168 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00008169 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8170 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00008171 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8172 << Pattern;
8173 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008174 } else {
8175 if (InstantiateClass(NameLoc, Record, Def,
8176 getTemplateInstantiationArgs(Record),
8177 TSK))
8178 return true;
8179
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008180 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00008181 if (!RecordDef)
8182 return true;
8183 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008184 }
8185
Douglas Gregor1d957a32009-10-27 18:42:08 +00008186 // Instantiate all of the members of the class.
8187 InstantiateClassMembers(NameLoc, RecordDef,
8188 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008189
Douglas Gregor88d292c2010-05-13 16:44:06 +00008190 if (TSK == TSK_ExplicitInstantiationDefinition)
8191 MarkVTableUsed(NameLoc, RecordDef, true);
8192
Mike Stump87c57ac2009-05-16 07:39:55 +00008193 // FIXME: We don't have any representation for explicit instantiations of
8194 // member classes. Such a representation is not needed for compilation, but it
8195 // should be available for clients that want to see all of the declarations in
8196 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008197 return TagD;
8198}
8199
John McCallfaf5fb42010-08-26 23:41:50 +00008200DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8201 SourceLocation ExternLoc,
8202 SourceLocation TemplateLoc,
8203 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008204 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008205 // TODO: check if/when DNInfo should replace Name.
8206 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8207 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00008208 if (!Name) {
8209 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008210 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008211 diag::err_explicit_instantiation_requires_name)
8212 << D.getDeclSpec().getSourceRange()
8213 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008214
Douglas Gregor450f00842009-09-25 18:43:00 +00008215 return true;
8216 }
8217
8218 // The scope passed in may not be a decl scope. Zip up the scope tree until
8219 // we find one that is.
8220 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8221 (S->getFlags() & Scope::TemplateParamScope) != 0)
8222 S = S->getParent();
8223
8224 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00008225 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8226 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00008227 if (R.isNull())
8228 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008229
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008230 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00008231 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008232 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00008233 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008234 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8235 << Name;
8236 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008237 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008238 != DeclSpec::SCS_unspecified) {
8239 // Complain about then remove the storage class specifier.
8240 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8241 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008242
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008243 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00008244 }
8245
Douglas Gregor3c74d412009-10-14 20:14:33 +00008246 // C++0x [temp.explicit]p1:
8247 // [...] An explicit instantiation of a function template shall not use the
8248 // inline or constexpr specifiers.
8249 // Presumably, this also applies to member functions of class templates as
8250 // well.
Richard Smith83c19292011-10-18 03:44:03 +00008251 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008252 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008253 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00008254 diag::err_explicit_instantiation_inline :
8255 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00008256 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00008257 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00008258 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8259 // not already specified.
8260 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8261 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008262
Nathan Wilsonde498452016-02-08 05:34:00 +00008263 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8264 // applied only to the definition of a function template or variable template,
8265 // declared in namespace scope.
8266 if (D.getDeclSpec().isConceptSpecified()) {
8267 Diag(D.getDeclSpec().getConceptSpecLoc(),
8268 diag::err_concept_specified_specialization) << 0;
8269 return true;
8270 }
8271
Richard Smith19a311a2017-02-09 22:47:51 +00008272 // A deduction guide is not on the list of entities that can be explicitly
8273 // instantiated.
8274 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8275 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8276 << /*explicit instantiation*/ 0;
8277 return true;
8278 }
8279
Douglas Gregore47f5a72009-10-14 23:41:34 +00008280 // C++0x [temp.explicit]p2:
8281 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008282 // definition and an explicit instantiation declaration. An explicit
8283 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00008284 TemplateSpecializationKind TSK
8285 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8286 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008287
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008288 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00008289 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00008290
8291 if (!R->isFunctionType()) {
8292 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008293 // A [...] static data member of a class template can be explicitly
8294 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008295 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008296 // C++1y [temp.explicit]p1:
8297 // A [...] variable [...] template specialization can be explicitly
8298 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00008299 if (Previous.isAmbiguous())
8300 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008301
John McCall67c00872009-12-02 08:25:40 +00008302 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00008303 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008304
Larisse Voufo39a1e502013-08-06 01:03:05 +00008305 if (!PrevTemplate) {
8306 if (!Prev || !Prev->isStaticDataMember()) {
8307 // We expect to see a data data member here.
8308 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8309 << Name;
8310 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8311 P != PEnd; ++P)
8312 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8313 return true;
8314 }
8315
8316 if (!Prev->getInstantiatedFromStaticDataMember()) {
8317 // FIXME: Check for explicit specialization?
8318 Diag(D.getIdentifierLoc(),
8319 diag::err_explicit_instantiation_data_member_not_instantiated)
8320 << Prev;
8321 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8322 // FIXME: Can we provide a note showing where this was declared?
8323 return true;
8324 }
8325 } else {
8326 // Explicitly instantiate a variable template.
8327
8328 // C++1y [dcl.spec.auto]p6:
8329 // ... A program that uses auto or decltype(auto) in a context not
8330 // explicitly allowed in this section is ill-formed.
8331 //
8332 // This includes auto-typed variable template instantiations.
8333 if (R->isUndeducedType()) {
8334 Diag(T->getTypeLoc().getLocStart(),
8335 diag::err_auto_not_allowed_var_inst);
8336 return true;
8337 }
8338
Richard Smithef985ac2013-09-18 02:10:12 +00008339 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8340 // C++1y [temp.explicit]p3:
8341 // If the explicit instantiation is for a variable, the unqualified-id
8342 // in the declaration shall be a template-id.
8343 Diag(D.getIdentifierLoc(),
8344 diag::err_explicit_instantiation_without_template_id)
8345 << PrevTemplate;
8346 Diag(PrevTemplate->getLocation(),
8347 diag::note_explicit_instantiation_here);
8348 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00008349 }
8350
Nathan Wilson83839122016-04-09 02:55:27 +00008351 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8352 // explicit instantiation (14.8.2) [...] of a concept definition.
8353 if (PrevTemplate->isConcept()) {
8354 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8355 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8356 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8357 return true;
8358 }
8359
Richard Smithef985ac2013-09-18 02:10:12 +00008360 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00008361 TemplateArgumentListInfo TemplateArgs =
8362 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00008363
Larisse Voufo39a1e502013-08-06 01:03:05 +00008364 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8365 D.getIdentifierLoc(), TemplateArgs);
8366 if (Res.isInvalid())
8367 return true;
8368
8369 // Ignore access control bits, we don't need them for redeclaration
8370 // checking.
8371 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00008372 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008373
Douglas Gregore47f5a72009-10-14 23:41:34 +00008374 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008375 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008376 // or a static data member of a class template specialization, the name of
8377 // the class template specialization in the qualified-id for the member
8378 // name shall be a simple-template-id.
8379 //
8380 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008381 //
Richard Smith5977d872013-09-18 21:55:14 +00008382 // This does not apply to variable template specializations, where the
8383 // template-id is in the unqualified-id instead.
8384 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008385 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008386 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008387 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008388
Douglas Gregore47f5a72009-10-14 23:41:34 +00008389 // Check the scope of this explicit instantiation.
8390 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008391
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008392 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00008393 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8394 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008395 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008396 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00008397 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008398 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008399
Larisse Voufo39a1e502013-08-06 01:03:05 +00008400 if (!HasNoEffect) {
8401 // Instantiate static data member or variable template.
8402
8403 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8404 if (PrevTemplate) {
8405 // Merge attributes.
8406 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8407 ProcessDeclAttributeList(S, Prev, Attr);
8408 }
8409 if (TSK == TSK_ExplicitInstantiationDefinition)
8410 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8411 }
8412
8413 // Check the new variable specialization against the parsed input.
8414 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8415 Diag(T->getTypeLoc().getLocStart(),
8416 diag::err_invalid_var_template_spec_type)
8417 << 0 << PrevTemplate << R << Prev->getType();
8418 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8419 << 2 << PrevTemplate->getDeclName();
8420 return true;
8421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008422
Douglas Gregor450f00842009-09-25 18:43:00 +00008423 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00008424 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008426
8427 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00008428 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00008429 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00008430 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00008431 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00008432 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00008433 HasExplicitTemplateArgs = true;
8434 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008435
Douglas Gregor450f00842009-09-25 18:43:00 +00008436 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008437 // A [...] function [...] can be explicitly instantiated from its template.
8438 // A member function [...] of a class template can be explicitly
8439 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008440 // template.
John McCall58cc69d2010-01-27 01:50:18 +00008441 UnresolvedSet<8> Matches;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008442 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008443 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00008444 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8445 P != PEnd; ++P) {
8446 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00008447 if (!HasExplicitTemplateArgs) {
8448 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00008449 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
8450 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00008451 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00008452 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008453
John McCall58cc69d2010-01-27 01:50:18 +00008454 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008455 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8456 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00008457 }
Douglas Gregor450f00842009-09-25 18:43:00 +00008458 }
8459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008460
Douglas Gregor450f00842009-09-25 18:43:00 +00008461 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8462 if (!FunTmpl)
8463 continue;
8464
Larisse Voufo98b20f12013-07-19 23:00:19 +00008465 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008466 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008467 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008468 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00008469 (HasExplicitTemplateArgs ? &TemplateArgs
8470 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00008471 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008472 // Keep track of almost-matches.
8473 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00008474 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008475 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008476 (void)TDK;
8477 continue;
8478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008479
Artem Belevich64135c32016-12-08 19:38:13 +00008480 // Target attributes are part of the cuda function signature, so
8481 // the cuda target of the instantiated function must match that of its
8482 // template. Given that C++ template deduction does not take
8483 // target attributes into account, we reject candidates here that
8484 // have a different target.
8485 if (LangOpts.CUDA &&
8486 IdentifyCUDATarget(Specialization,
8487 /* IgnoreImplicitHDAttributes = */ true) !=
8488 IdentifyCUDATarget(Attr)) {
8489 FailedCandidates.addCandidate().set(
8490 P.getPair(), FunTmpl->getTemplatedDecl(),
8491 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8492 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008493 }
8494
John McCall58cc69d2010-01-27 01:50:18 +00008495 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008497
Douglas Gregor450f00842009-09-25 18:43:00 +00008498 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008499 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008500 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008501 D.getIdentifierLoc(),
8502 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8503 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8504 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008505
John McCall58cc69d2010-01-27 01:50:18 +00008506 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008507 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008508
8509 // Ignore access control bits, we don't need them for redeclaration checking.
8510 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008511
Alexey Bataev73983912014-11-06 10:10:50 +00008512 // C++11 [except.spec]p4
8513 // In an explicit instantiation an exception-specification may be specified,
8514 // but is not required.
8515 // If an exception-specification is specified in an explicit instantiation
8516 // directive, it shall be compatible with the exception-specifications of
8517 // other declarations of that function.
8518 if (auto *FPT = R->getAs<FunctionProtoType>())
8519 if (FPT->hasExceptionSpec()) {
8520 unsigned DiagID =
8521 diag::err_mismatched_exception_spec_explicit_instantiation;
8522 if (getLangOpts().MicrosoftExt)
8523 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8524 bool Result = CheckEquivalentExceptionSpec(
8525 PDiag(DiagID) << Specialization->getType(),
8526 PDiag(diag::note_explicit_instantiation_here),
8527 Specialization->getType()->getAs<FunctionProtoType>(),
8528 Specialization->getLocation(), FPT, D.getLocStart());
8529 // In Microsoft mode, mismatching exception specifications just cause a
8530 // warning.
8531 if (!getLangOpts().MicrosoftExt && Result)
8532 return true;
8533 }
8534
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008535 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008536 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008537 diag::err_explicit_instantiation_member_function_not_instantiated)
8538 << Specialization
8539 << (Specialization->getTemplateSpecializationKind() ==
8540 TSK_ExplicitSpecialization);
8541 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8542 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008543 }
8544
Douglas Gregorec9fd132012-01-14 16:38:05 +00008545 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008546 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8547 PrevDecl = Specialization;
8548
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008549 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008550 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008551 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008552 PrevDecl,
8553 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008554 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008555 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008556 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008557
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008558 // FIXME: We may still want to build some representation of this
8559 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008560 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008561 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008562 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008563
8564 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008565 if (Attr)
8566 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008567
Richard Smitheb36ddf2014-04-24 22:45:46 +00008568 if (Specialization->isDefined()) {
8569 // Let the ASTConsumer know that this function has been explicitly
8570 // instantiated now, and its linkage might have changed.
8571 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8572 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008573 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008574
Douglas Gregore47f5a72009-10-14 23:41:34 +00008575 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008576 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008577 // or a static data member of a class template specialization, the name of
8578 // the class template specialization in the qualified-id for the member
8579 // name shall be a simple-template-id.
8580 //
8581 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008582 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008583 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008584 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008585 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008586 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008587 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008588 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008589
Nathan Wilson83839122016-04-09 02:55:27 +00008590 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8591 // explicit instantiation (14.8.2) [...] of a concept definition.
8592 if (FunTmpl && FunTmpl->isConcept() &&
8593 !D.getDeclSpec().isConceptSpecified()) {
8594 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8595 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8596 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8597 return true;
8598 }
8599
Douglas Gregore47f5a72009-10-14 23:41:34 +00008600 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008601 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008602 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008603 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008604 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008605
Douglas Gregor450f00842009-09-25 18:43:00 +00008606 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008607 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008608}
8609
John McCallfaf5fb42010-08-26 23:41:50 +00008610TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008611Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8612 const CXXScopeSpec &SS, IdentifierInfo *Name,
8613 SourceLocation TagLoc, SourceLocation NameLoc) {
8614 // This has to hold, because SS is expected to be defined.
8615 assert(Name && "Expected a name in a dependent tag");
8616
Aaron Ballman4a979672014-01-03 13:56:08 +00008617 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008618 if (!NNS)
8619 return true;
8620
Abramo Bagnara6150c882010-05-11 21:36:43 +00008621 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008622
Douglas Gregorba41d012010-04-24 16:38:41 +00008623 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8624 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008625 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008626 return true;
8627 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008628
Douglas Gregore7c20652011-03-02 00:47:37 +00008629 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008630 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008631 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008632
Douglas Gregore7c20652011-03-02 00:47:37 +00008633 // Create type-source location information for this type.
8634 TypeLocBuilder TLB;
8635 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008636 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008637 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8638 TL.setNameLoc(NameLoc);
8639 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008640}
8641
John McCallfaf5fb42010-08-26 23:41:50 +00008642TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008643Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8644 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008645 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008646 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008647 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008648
Richard Smith0bf8a4922011-10-18 20:49:44 +00008649 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8650 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008651 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008652 diag::warn_cxx98_compat_typename_outside_of_template :
8653 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008654 << FixItHint::CreateRemoval(TypenameLoc);
8655
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008656 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008657 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8658 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008659 if (T.isNull())
8660 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008661
8662 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8663 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008664 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008665 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008666 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008667 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008668 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008669 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008670 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008671 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008672 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008673 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008674
John McCallba7bf592010-08-24 05:47:05 +00008675 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008676}
8677
John McCallfaf5fb42010-08-26 23:41:50 +00008678TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008679Sema::ActOnTypenameType(Scope *S,
8680 SourceLocation TypenameLoc,
8681 const CXXScopeSpec &SS,
8682 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008683 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00008684 IdentifierInfo *TemplateII,
8685 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008686 SourceLocation LAngleLoc,
8687 ASTTemplateArgsPtr TemplateArgsIn,
8688 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008689 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8690 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008691 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008692 diag::warn_cxx98_compat_typename_outside_of_template :
8693 diag::ext_typename_outside_of_template)
8694 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008695
Richard Smith74f02342017-01-19 21:00:13 +00008696 // Strangely, non-type results are not ignored by this lookup, so the
8697 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00008698 if (TypenameLoc.isValid()) {
8699 auto *LookupRD =
8700 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
8701 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
8702 Diag(TemplateIILoc,
8703 diag::ext_out_of_line_qualified_id_type_names_constructor)
8704 << TemplateII << 0 /*injected-class-name used as template name*/
8705 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
8706 }
Richard Smith74f02342017-01-19 21:00:13 +00008707 }
8708
Douglas Gregorb09518c2011-02-27 22:46:49 +00008709 // Translate the parser's template argument list in our AST format.
8710 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8711 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008712
Douglas Gregorb09518c2011-02-27 22:46:49 +00008713 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008714 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8715 // Construct a dependent template specialization type.
8716 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008717 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008718 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8719 DTN->getQualifier(),
8720 DTN->getIdentifier(),
8721 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008722
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008723 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008724 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008725 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008726 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008727 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8728 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008729 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00008730 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008731 SpecTL.setLAngleLoc(LAngleLoc);
8732 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008733 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8734 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008735 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008736 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00008737
Richard Smith74f02342017-01-19 21:00:13 +00008738 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008739 if (T.isNull())
8740 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008741
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008742 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008743 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008744 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008745 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008746 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00008747 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008748 SpecTL.setLAngleLoc(LAngleLoc);
8749 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008750 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8751 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008752
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008753 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8754 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008755 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008756 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00008757
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008758 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8759 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008760}
8761
Douglas Gregorb09518c2011-02-27 22:46:49 +00008762
Richard Smith6f8d2c62012-05-09 05:17:00 +00008763/// Determine whether this failed name lookup should be treated as being
8764/// disabled by a usage of std::enable_if.
8765static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8766 SourceRange &CondRange) {
8767 // We must be looking for a ::type...
8768 if (!II.isStr("type"))
8769 return false;
8770
8771 // ... within an explicitly-written template specialization...
8772 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8773 return false;
8774 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008775 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8776 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8777 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008778 return false;
8779 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008780 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008781
8782 // ... which names a complete class template declaration...
8783 const TemplateDecl *EnableIfDecl =
8784 EnableIfTST->getTemplateName().getAsTemplateDecl();
8785 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8786 return false;
8787
8788 // ... called "enable_if".
8789 const IdentifierInfo *EnableIfII =
8790 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8791 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8792 return false;
8793
8794 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008795 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008796 return true;
8797}
8798
Douglas Gregor333489b2009-03-27 23:10:48 +00008799/// \brief Build the type that describes a C++ typename specifier,
8800/// e.g., "typename T::type".
8801QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00008802Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008803 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00008804 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008805 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008806 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008807 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008808 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008809
John McCall0b66eb32010-05-01 00:40:08 +00008810 DeclContext *Ctx = computeDeclContext(SS);
8811 if (!Ctx) {
8812 // If the nested-name-specifier is dependent and couldn't be
8813 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008814 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008815 return Context.getDependentNameType(Keyword,
8816 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008817 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008818 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008819
John McCall0b66eb32010-05-01 00:40:08 +00008820 // If the nested-name-specifier refers to the current instantiation,
8821 // the "typename" keyword itself is superfluous. In C++03, the
8822 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8823 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008824 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008825
John McCall0b66eb32010-05-01 00:40:08 +00008826 if (RequireCompleteDeclContext(SS, Ctx))
8827 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008828
8829 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008830 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008831 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008832 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008833 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008834 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008835 case LookupResult::NotFound: {
8836 // If we're looking up 'type' within a template named 'enable_if', produce
8837 // a more specific diagnostic.
8838 SourceRange CondRange;
8839 if (isEnableIf(QualifierLoc, II, CondRange)) {
8840 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8841 << Ctx << CondRange;
8842 return QualType();
8843 }
8844
Douglas Gregore40876a2009-10-13 21:16:44 +00008845 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008846 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008847 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008848
8849 case LookupResult::FoundUnresolvedValue: {
8850 // We found a using declaration that is a value. Most likely, the using
8851 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008852 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008853 IILoc);
8854 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8855 << Name << Ctx << FullRange;
8856 if (UnresolvedUsingValueDecl *Using
8857 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008858 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008859 Diag(Loc, diag::note_using_value_decl_missing_typename)
8860 << FixItHint::CreateInsertion(Loc, "typename ");
8861 }
8862 }
8863 // Fall through to create a dependent typename type, from which we can recover
8864 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008865
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008866 case LookupResult::NotFoundInCurrentInstantiation:
8867 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00008868 return Context.getDependentNameType(Keyword,
8869 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008870 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008871
8872 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008873 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00008874 // C++ [class.qual]p2:
8875 // In a lookup in which function names are not ignored and the
8876 // nested-name-specifier nominates a class C, if the name specified
8877 // after the nested-name-specifier, when looked up in C, is the
8878 // injected-class-name of C [...] then the name is instead considered
8879 // to name the constructor of class C.
8880 //
8881 // Unlike in an elaborated-type-specifier, function names are not ignored
8882 // in typename-specifier lookup. However, they are ignored in all the
8883 // contexts where we form a typename type with no keyword (that is, in
8884 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
8885 //
8886 // FIXME: That's not strictly true: mem-initializer-id lookup does not
8887 // ignore functions, but that appears to be an oversight.
8888 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
8889 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
8890 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
8891 FoundRD->isInjectedClassName() &&
8892 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
8893 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
8894 << &II << 1 << 0 /*'typename' keyword used*/;
8895
Abramo Bagnara6150c882010-05-11 21:36:43 +00008896 // We found a type. Build an ElaboratedType, since the
8897 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008898 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00008899 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008900 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008901 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008902 }
8903
Richard Smithee579842017-01-30 20:39:26 +00008904 // C++ [dcl.type.simple]p2:
8905 // A type-specifier of the form
8906 // typename[opt] nested-name-specifier[opt] template-name
8907 // is a placeholder for a deduced class type [...].
8908 if (getLangOpts().CPlusPlus1z) {
8909 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
8910 return Context.getElaboratedType(
8911 Keyword, QualifierLoc.getNestedNameSpecifier(),
8912 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
8913 QualType(), false));
8914 }
8915 }
Richard Smith600b5262017-01-26 20:40:47 +00008916
Douglas Gregor333489b2009-03-27 23:10:48 +00008917 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008918 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008919 break;
8920
8921 case LookupResult::FoundOverloaded:
8922 DiagID = diag::err_typename_nested_not_type;
8923 Referenced = *Result.begin();
8924 break;
8925
John McCall6538c932009-10-10 05:48:19 +00008926 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008927 return QualType();
8928 }
8929
8930 // If we get here, it's because name lookup did not find a
8931 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008932 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008933 IILoc);
8934 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008935 if (Referenced)
8936 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8937 << Name;
8938 return QualType();
8939}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008940
8941namespace {
8942 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008943 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008944 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008945 SourceLocation Loc;
8946 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008947
Douglas Gregor15acfb92009-08-06 16:20:37 +00008948 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008949 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008950
Mike Stump11289f42009-09-09 15:08:12 +00008951 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008952 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008953 DeclarationName Entity)
8954 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008955 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008956
8957 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008958 /// transformed.
8959 ///
8960 /// For the purposes of type reconstruction, a type has already been
8961 /// transformed if it is NULL or if it is not dependent.
8962 bool AlreadyTransformed(QualType T) {
8963 return T.isNull() || !T->isDependentType();
8964 }
Mike Stump11289f42009-09-09 15:08:12 +00008965
8966 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008967 /// rebuilt.
8968 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008969
Douglas Gregor15acfb92009-08-06 16:20:37 +00008970 /// \brief Returns the name of the entity whose type is being rebuilt.
8971 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008972
Douglas Gregoref6ab412009-10-27 06:26:26 +00008973 /// \brief Sets the "base" location and entity when that
8974 /// information is known based on another transformation.
8975 void setBase(SourceLocation Loc, DeclarationName Entity) {
8976 this->Loc = Loc;
8977 this->Entity = Entity;
8978 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00008979
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008980 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8981 // Lambdas never need to be transformed.
8982 return E;
8983 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008984 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008985} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008986
Douglas Gregor15acfb92009-08-06 16:20:37 +00008987/// \brief Rebuilds a type within the context of the current instantiation.
8988///
Mike Stump11289f42009-09-09 15:08:12 +00008989/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008990/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008991/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008992/// partial specialization thereof). This routine will rebuild that type now
8993/// that we have entered the declarator's scope, which may produce different
8994/// canonical types, e.g.,
8995///
8996/// \code
8997/// template<typename T>
8998/// struct X {
8999/// typedef T* pointer;
9000/// pointer data();
9001/// };
9002///
9003/// template<typename T>
9004/// typename X<T>::pointer X<T>::data() { ... }
9005/// \endcode
9006///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00009007/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009008/// since we do not know that we can look into X<T> when we parsed the type.
9009/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00009010/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00009011/// as the canonical type of T*, allowing the return types of the out-of-line
9012/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00009013TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9014 SourceLocation Loc,
9015 DeclarationName Name) {
9016 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00009017 return T;
Mike Stump11289f42009-09-09 15:08:12 +00009018
Douglas Gregor15acfb92009-08-06 16:20:37 +00009019 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9020 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00009021}
Douglas Gregorbe999392009-09-15 16:23:51 +00009022
John McCalldadc5752010-08-24 06:29:42 +00009023ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00009024 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9025 DeclarationName());
9026 return Rebuilder.TransformExpr(E);
9027}
9028
John McCall99b2fe52010-04-29 23:50:39 +00009029bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00009030 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009031 return true;
John McCall2408e322010-04-27 00:57:59 +00009032
Douglas Gregor10176412011-02-25 16:07:42 +00009033 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009034 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9035 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009036 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009037 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009038 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009039 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009040
Douglas Gregor10176412011-02-25 16:07:42 +00009041 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009042 return false;
John McCall2408e322010-04-27 00:57:59 +00009043}
9044
Douglas Gregor041b0842011-10-14 15:31:12 +00009045/// \brief Rebuild the template parameters now that we know we're in a current
9046/// instantiation.
9047bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9048 TemplateParameterList *Params) {
9049 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9050 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009051
Douglas Gregor041b0842011-10-14 15:31:12 +00009052 // There is nothing to rebuild in a type parameter.
9053 if (isa<TemplateTypeParmDecl>(Param))
9054 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009055
Douglas Gregor041b0842011-10-14 15:31:12 +00009056 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009057 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009058 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9059 if (RebuildTemplateParamsInCurrentInstantiation(
9060 TTP->getTemplateParameters()))
9061 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009062
Douglas Gregor041b0842011-10-14 15:31:12 +00009063 continue;
9064 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009065
Douglas Gregor041b0842011-10-14 15:31:12 +00009066 // Rebuild the type of a non-type template parameter.
9067 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009068 TypeSourceInfo *NewTSI
9069 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9070 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009071 NTTP->getDeclName());
9072 if (!NewTSI)
9073 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009074
Douglas Gregor041b0842011-10-14 15:31:12 +00009075 if (NewTSI != NTTP->getTypeSourceInfo()) {
9076 NTTP->setTypeSourceInfo(NewTSI);
9077 NTTP->setType(NewTSI->getType());
9078 }
9079 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009080
Douglas Gregor041b0842011-10-14 15:31:12 +00009081 return false;
9082}
9083
Douglas Gregorbe999392009-09-15 16:23:51 +00009084/// \brief Produces a formatted string that describes the binding of
9085/// template parameters to template arguments.
9086std::string
9087Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9088 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009089 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00009090}
9091
9092std::string
9093Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9094 const TemplateArgument *Args,
9095 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009096 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00009097 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00009098
Douglas Gregore62e6a02009-11-11 19:13:48 +00009099 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009100 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009101
Douglas Gregorbe999392009-09-15 16:23:51 +00009102 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00009103 if (I >= NumArgs)
9104 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009105
Douglas Gregorbe999392009-09-15 16:23:51 +00009106 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009107 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00009108 else
Douglas Gregor0192c232010-12-20 16:52:59 +00009109 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009110
Douglas Gregorbe999392009-09-15 16:23:51 +00009111 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00009112 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00009113 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00009114 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00009115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009116
Douglas Gregor0192c232010-12-20 16:52:59 +00009117 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00009118 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00009119 }
Douglas Gregor0192c232010-12-20 16:52:59 +00009120
9121 Out << ']';
9122 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00009123}
Francois Pichet1c229c02011-04-22 22:18:13 +00009124
Richard Smithe40f2ba2013-08-07 21:41:30 +00009125void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9126 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00009127 if (!FD)
9128 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00009129
Justin Lebar28f09c52016-10-10 16:26:08 +00009130 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00009131
9132 // Take tokens to avoid allocations
9133 LPT->Toks.swap(Toks);
9134 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00009135 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00009136
9137 FD->setLateTemplateParsed(true);
9138}
9139
9140void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9141 if (!FD)
9142 return;
9143 FD->setLateTemplateParsed(false);
9144}
Francois Pichet1c229c02011-04-22 22:18:13 +00009145
9146bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9147 DeclContext *DC = CurContext;
9148
9149 while (DC) {
9150 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9151 const FunctionDecl *FD = RD->isLocalClass();
9152 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9153 } else if (DC->isTranslationUnit() || DC->isNamespace())
9154 return false;
9155
9156 DC = DC->getParent();
9157 }
9158 return false;
9159}
Richard Smith6739a102016-05-05 00:56:12 +00009160
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009161namespace {
Richard Smith6739a102016-05-05 00:56:12 +00009162/// \brief Walk the path from which a declaration was instantiated, and check
9163/// that every explicit specialization along that path is visible. This enforces
9164/// C++ [temp.expl.spec]/6:
9165///
9166/// If a template, a member template or a member of a class template is
9167/// explicitly specialized then that specialization shall be declared before
9168/// the first use of that specialization that would cause an implicit
9169/// instantiation to take place, in every translation unit in which such a
9170/// use occurs; no diagnostic is required.
9171///
9172/// and also C++ [temp.class.spec]/1:
9173///
9174/// A partial specialization shall be declared before the first use of a
9175/// class template specialization that would make use of the partial
9176/// specialization as the result of an implicit or explicit instantiation
9177/// in every translation unit in which such a use occurs; no diagnostic is
9178/// required.
9179class ExplicitSpecializationVisibilityChecker {
9180 Sema &S;
9181 SourceLocation Loc;
9182 llvm::SmallVector<Module *, 8> Modules;
9183
9184public:
9185 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9186 : S(S), Loc(Loc) {}
9187
9188 void check(NamedDecl *ND) {
9189 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9190 return checkImpl(FD);
9191 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9192 return checkImpl(RD);
9193 if (auto *VD = dyn_cast<VarDecl>(ND))
9194 return checkImpl(VD);
9195 if (auto *ED = dyn_cast<EnumDecl>(ND))
9196 return checkImpl(ED);
9197 }
9198
9199private:
9200 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9201 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9202 : Sema::MissingImportKind::ExplicitSpecialization;
9203 const bool Recover = true;
9204
9205 // If we got a custom set of modules (because only a subset of the
9206 // declarations are interesting), use them, otherwise let
9207 // diagnoseMissingImport intelligently pick some.
9208 if (Modules.empty())
9209 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9210 else
9211 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9212 }
9213
9214 // Check a specific declaration. There are three problematic cases:
9215 //
9216 // 1) The declaration is an explicit specialization of a template
9217 // specialization.
9218 // 2) The declaration is an explicit specialization of a member of an
9219 // templated class.
9220 // 3) The declaration is an instantiation of a template, and that template
9221 // is an explicit specialization of a member of a templated class.
9222 //
9223 // We don't need to go any deeper than that, as the instantiation of the
9224 // surrounding class / etc is not triggered by whatever triggered this
9225 // instantiation, and thus should be checked elsewhere.
9226 template<typename SpecDecl>
9227 void checkImpl(SpecDecl *Spec) {
9228 bool IsHiddenExplicitSpecialization = false;
9229 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9230 IsHiddenExplicitSpecialization =
9231 Spec->getMemberSpecializationInfo()
9232 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9233 : !S.hasVisibleDeclaration(Spec);
9234 } else {
9235 checkInstantiated(Spec);
9236 }
9237
9238 if (IsHiddenExplicitSpecialization)
9239 diagnose(Spec->getMostRecentDecl(), false);
9240 }
9241
9242 void checkInstantiated(FunctionDecl *FD) {
9243 if (auto *TD = FD->getPrimaryTemplate())
9244 checkTemplate(TD);
9245 }
9246
9247 void checkInstantiated(CXXRecordDecl *RD) {
9248 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9249 if (!SD)
9250 return;
9251
9252 auto From = SD->getSpecializedTemplateOrPartial();
9253 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9254 checkTemplate(TD);
9255 else if (auto *TD =
9256 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9257 if (!S.hasVisibleDeclaration(TD))
9258 diagnose(TD, true);
9259 checkTemplate(TD);
9260 }
9261 }
9262
9263 void checkInstantiated(VarDecl *RD) {
9264 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9265 if (!SD)
9266 return;
9267
9268 auto From = SD->getSpecializedTemplateOrPartial();
9269 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9270 checkTemplate(TD);
9271 else if (auto *TD =
9272 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9273 if (!S.hasVisibleDeclaration(TD))
9274 diagnose(TD, true);
9275 checkTemplate(TD);
9276 }
9277 }
9278
9279 void checkInstantiated(EnumDecl *FD) {}
9280
9281 template<typename TemplDecl>
9282 void checkTemplate(TemplDecl *TD) {
9283 if (TD->isMemberSpecialization()) {
9284 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9285 diagnose(TD->getMostRecentDecl(), false);
9286 }
9287 }
9288};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009289} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00009290
9291void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
9292 if (!getLangOpts().Modules)
9293 return;
9294
9295 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9296}
9297
9298/// \brief Check whether a template partial specialization that we've discovered
9299/// is hidden, and produce suitable diagnostics if so.
9300void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
9301 NamedDecl *Spec) {
9302 llvm::SmallVector<Module *, 8> Modules;
9303 if (!hasVisibleDeclaration(Spec, &Modules))
9304 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9305 MissingImportKind::PartialSpecialization,
9306 /*Recover*/true);
9307}