blob: e110a8cc814444ca79fc5491c6c3a4b7cae58c28 [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
Richard Smith42bc73a2017-05-10 02:30:28 +0000458void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
459 SourceLocation Less,
460 SourceLocation Greater) {
461 if (TemplateName.isInvalid())
462 return;
463
464 DeclarationNameInfo NameInfo;
465 CXXScopeSpec SS;
466 LookupNameKind LookupKind;
467
468 DeclContext *LookupCtx = nullptr;
469 NamedDecl *Found = nullptr;
470
471 // Figure out what name we looked up.
472 if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
473 NameInfo = ME->getMemberNameInfo();
474 SS.Adopt(ME->getQualifierLoc());
475 LookupKind = LookupMemberName;
476 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
477 Found = ME->getMemberDecl();
478 } else {
479 auto *DRE = cast<DeclRefExpr>(TemplateName.get());
480 NameInfo = DRE->getNameInfo();
481 SS.Adopt(DRE->getQualifierLoc());
482 LookupKind = LookupOrdinaryName;
483 Found = DRE->getFoundDecl();
484 }
485
486 // Try to correct the name by looking for templates and C++ named casts.
487 struct TemplateCandidateFilter : CorrectionCandidateCallback {
488 TemplateCandidateFilter() {
489 WantTypeSpecifiers = false;
490 WantExpressionKeywords = false;
491 WantRemainingKeywords = false;
492 WantCXXNamedCasts = true;
493 };
494 bool ValidateCandidate(const TypoCorrection &Candidate) override {
495 if (auto *ND = Candidate.getCorrectionDecl())
496 return isAcceptableTemplateName(ND->getASTContext(), ND, true);
497 return Candidate.isKeyword();
498 }
499 };
500
501 DeclarationName Name = NameInfo.getName();
502 if (TypoCorrection Corrected =
503 CorrectTypo(NameInfo, LookupKind, S, &SS,
504 llvm::make_unique<TemplateCandidateFilter>(),
505 CTK_ErrorRecovery, LookupCtx)) {
506 auto *ND = Corrected.getFoundDecl();
507 if (ND)
508 ND = isAcceptableTemplateName(Context, ND,
509 /*AllowFunctionTemplates*/ true);
510 if (ND || Corrected.isKeyword()) {
511 if (LookupCtx) {
512 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
513 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
514 Name.getAsString() == CorrectedStr;
515 diagnoseTypo(Corrected,
516 PDiag(diag::err_non_template_in_member_template_id_suggest)
517 << Name << LookupCtx << DroppedSpecifier
Richard Smith52f8d192017-05-10 21:32:16 +0000518 << SS.getRange(), false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000519 } else {
520 diagnoseTypo(Corrected,
521 PDiag(diag::err_non_template_in_template_id_suggest)
Richard Smith52f8d192017-05-10 21:32:16 +0000522 << Name, false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000523 }
524 if (Found)
525 Diag(Found->getLocation(),
526 diag::note_non_template_in_template_id_found);
527 return;
528 }
529 }
530
531 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
532 << Name << SourceRange(Less, Greater);
533 if (Found)
534 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
535}
536
John McCallcd4b4772009-12-02 03:53:29 +0000537/// ActOnDependentIdExpression - Handle a dependent id-expression that
538/// was just parsed. This is only possible with an explicit scope
539/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000540ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000541Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000542 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000543 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000544 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000545 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000546 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547
Reid Kleckner1af391df2016-03-11 18:59:12 +0000548 // C++11 [expr.prim.general]p12:
549 // An id-expression that denotes a non-static data member or non-static
550 // member function of a class can only be used:
551 // (...)
552 // - if that id-expression denotes a non-static data member and it
553 // appears in an unevaluated operand.
554 //
555 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
556 // CXXDependentScopeMemberExpr. The former can instantiate to either
557 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
558 // always a MemberExpr.
559 bool MightBeCxx11UnevalField =
560 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
561
Akira Hatanakad644e022016-12-16 03:19:41 +0000562 // Check if the nested name specifier is an enum type.
563 bool IsEnum = false;
564 if (NestedNameSpecifier *NNS = SS.getScopeRep())
565 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
566
567 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000568 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000569 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570
John McCalle66edc12009-11-24 19:00:30 +0000571 // Since the 'this' expression is synthesized, we don't need to
572 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000573 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000574
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000575 return CXXDependentScopeMemberExpr::Create(
576 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
577 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
578 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000579 }
580
Abramo Bagnara7945c982012-01-27 09:46:47 +0000581 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000582}
583
John McCalldadc5752010-08-24 06:29:42 +0000584ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000585Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000586 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000587 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000588 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000589 return DependentScopeDeclRefExpr::Create(
590 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
591 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000592}
593
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000594
595/// Determine whether we would be unable to instantiate this template (because
596/// it either has no definition, or is in the process of being instantiated).
597bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
598 NamedDecl *Instantiation,
599 bool InstantiatedFromMember,
600 const NamedDecl *Pattern,
601 const NamedDecl *PatternDef,
602 TemplateSpecializationKind TSK,
603 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000604 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
605 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000606
Richard Smithedbc6e92016-10-14 21:41:24 +0000607 bool IsEntityBeingDefined = false;
608 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
609 IsEntityBeingDefined = TD->isBeingDefined();
610
611 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000612 NamedDecl *SuggestedDef = nullptr;
613 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
614 /*OnlyNeedComplete*/false)) {
615 // If we're allowed to diagnose this and recover, do so.
616 bool Recover = Complain && !isSFINAEContext();
617 if (Complain)
618 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
619 Sema::MissingImportKind::Definition, Recover);
620 return !Recover;
621 }
622 return false;
623 }
624
Richard Smith6f4e2e02016-08-23 19:41:39 +0000625 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
626 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000627
Richard Smithedbc6e92016-10-14 21:41:24 +0000628 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000629 QualType InstantiationTy;
630 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
631 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000632 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000633 Diag(PointOfInstantiation,
634 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000635 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000636 << InstantiationTy;
637 // Not much point in noting the template declaration here, since
638 // we're lexically inside it.
639 Instantiation->setInvalidDecl();
640 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000641 if (isa<FunctionDecl>(Instantiation)) {
642 Diag(PointOfInstantiation,
643 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000644 << /*member function*/ 1 << Instantiation->getDeclName()
645 << Instantiation->getDeclContext();
646 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000647 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000648 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000649 Diag(PointOfInstantiation,
650 diag::err_implicit_instantiate_member_undefined)
651 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000652 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000653 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000654 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000655 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000656 Diag(PointOfInstantiation,
657 diag::err_explicit_instantiation_undefined_func_template)
658 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000659 Note = diag::note_explicit_instantiation_here;
660 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000661 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
662 << (TSK != TSK_ImplicitInstantiation)
663 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000664 Note = diag::note_template_decl_here;
665 } else {
666 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
667 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
668 Diag(PointOfInstantiation,
669 diag::err_explicit_instantiation_undefined_var_template)
670 << Instantiation;
671 Instantiation->setInvalidDecl();
672 } else
673 Diag(PointOfInstantiation,
674 diag::err_explicit_instantiation_undefined_member)
675 << /*static data member*/ 2 << Instantiation->getDeclName()
676 << Instantiation->getDeclContext();
677 Note = diag::note_explicit_instantiation_here;
678 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000679 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000680 if (Note) // Diagnostics were emitted.
681 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000682
683 // In general, Instantiation isn't marked invalid to get more than one
684 // error for multiple undefined instantiations. But the code that does
685 // explicit declaration -> explicit definition conversion can't handle
686 // invalid declarations, so mark as invalid in that case.
687 if (TSK == TSK_ExplicitInstantiationDeclaration)
688 Instantiation->setInvalidDecl();
689 return true;
690}
691
Douglas Gregor5101c242008-12-05 18:15:24 +0000692/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
693/// that the template parameter 'PrevDecl' is being shadowed by a new
694/// declaration at location Loc. Returns true to indicate that this is
695/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000696void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000697 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000698
699 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000700 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000701 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000702
703 // C++ [temp.local]p4:
704 // A template-parameter shall not be redeclared within its
705 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000706 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000707 << cast<NamedDecl>(PrevDecl)->getDeclName();
708 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000709}
710
Douglas Gregor463421d2009-03-03 04:44:36 +0000711/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000712/// the parameter D to reference the templated declaration and return a pointer
713/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000714TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
715 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
716 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000717 return Temp;
718 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000719 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000720}
721
Douglas Gregoreb29d182011-01-05 17:40:24 +0000722ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
723 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000725 "Only template template arguments can be pack expansions here");
726 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
727 "Template template argument pack expansion without packs");
728 ParsedTemplateArgument Result(*this);
729 Result.EllipsisLoc = EllipsisLoc;
730 return Result;
731}
732
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000733static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
734 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000736 switch (Arg.getKind()) {
737 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000738 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000739 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000740 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000741 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000742 return TemplateArgumentLoc(TemplateArgument(T), DI);
743 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000744
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000745 case ParsedTemplateArgument::NonType: {
746 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
747 return TemplateArgumentLoc(TemplateArgument(E), E);
748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000749
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000750 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000751 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000752 TemplateArgument TArg;
753 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000754 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000755 else
756 TArg = Template;
757 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000758 Arg.getScopeSpec().getWithLocInContext(
759 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000760 Arg.getLocation(),
761 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000762 }
763 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000765 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000766}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000767
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000768/// \brief Translates template arguments as provided by the parser
769/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000770void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
771 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000772 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000773 TemplateArgs.addArgument(translateTemplateArgument(*this,
774 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000775}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000776
Richard Smithb80d5402013-06-25 22:21:36 +0000777static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
778 SourceLocation Loc,
779 IdentifierInfo *Name) {
780 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
Richard Smithbecb92d2017-10-10 22:33:17 +0000781 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
Richard Smithb80d5402013-06-25 22:21:36 +0000782 if (PrevDecl && PrevDecl->isTemplateParameter())
783 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
784}
785
Douglas Gregor5101c242008-12-05 18:15:24 +0000786/// ActOnTypeParameter - Called when a C++ template type parameter
787/// (e.g., "typename T") has been parsed. Typename specifies whether
788/// the keyword "typename" was used to declare the type parameter
789/// (otherwise, "class" was used), and KeyLoc is the location of the
790/// "class" or "typename" keyword. ParamName is the name of the
791/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000792/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000793/// If the type parameter has a default argument, it will be added
794/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000795Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000796 SourceLocation EllipsisLoc,
797 SourceLocation KeyLoc,
798 IdentifierInfo *ParamName,
799 SourceLocation ParamNameLoc,
800 unsigned Depth, unsigned Position,
801 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000802 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000803 assert(S->isTemplateParamScope() &&
804 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000805
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000806 SourceLocation Loc = ParamNameLoc;
807 if (!ParamName)
808 Loc = KeyLoc;
809
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000810 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000811 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000812 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000813 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000814 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000815 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000816
817 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000818 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
819
Douglas Gregor5101c242008-12-05 18:15:24 +0000820 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000821 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000822 IdResolver.AddDecl(Param);
823 }
824
Douglas Gregorf5500772011-01-05 15:48:55 +0000825 // C++0x [temp.param]p9:
826 // A default template-argument may be specified for any kind of
827 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000828 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000829 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000830 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000831 }
832
Douglas Gregordc13ded2010-07-01 00:00:45 +0000833 // Handle the default argument, if provided.
834 if (DefaultArg) {
835 TypeSourceInfo *DefaultTInfo;
836 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000837
Douglas Gregordc13ded2010-07-01 00:00:45 +0000838 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000840 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000841 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000842 UPPC_DefaultArgument))
843 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844
Douglas Gregordc13ded2010-07-01 00:00:45 +0000845 // Check the template argument itself.
846 if (CheckTemplateArgument(Param, DefaultTInfo)) {
847 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000848 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000849 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850
Richard Smith1469b912015-06-10 00:29:03 +0000851 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000853
John McCall48871652010-08-21 09:40:31 +0000854 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000855}
856
Douglas Gregor463421d2009-03-03 04:44:36 +0000857/// \brief Check that the type of a non-type template parameter is
858/// well-formed.
859///
860/// \returns the (possibly-promoted) parameter type if valid;
861/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000862QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
863 SourceLocation Loc) {
864 if (TSI->getType()->isUndeducedType()) {
865 // C++1z [temp.dep.expr]p3:
866 // An id-expression is type-dependent if it contains
867 // - an identifier associated by name lookup with a non-type
868 // template-parameter declared with a type that contains a
869 // placeholder type (7.1.7.4),
870 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
871 }
872
873 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
874}
875
876QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
877 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000878 // We don't allow variably-modified types as the type of non-type template
879 // parameters.
880 if (T->isVariablyModifiedType()) {
881 Diag(Loc, diag::err_variably_modified_nontype_template_param)
882 << T;
883 return QualType();
884 }
885
Douglas Gregor463421d2009-03-03 04:44:36 +0000886 // C++ [temp.param]p4:
887 //
888 // A non-type template-parameter shall have one of the following
889 // (optionally cv-qualified) types:
890 //
891 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000892 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000893 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000894 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000895 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000896 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000897 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000898 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000899 // -- std::nullptr_t.
900 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000901 // If T is a dependent type, we can't do the check now, so we
902 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +0000903 T->isDependentType() ||
904 // Allow use of auto in template parameter declarations.
905 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +0000906 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
907 // are ignored when determining its type.
908 return T.getUnqualifiedType();
909 }
910
Douglas Gregor463421d2009-03-03 04:44:36 +0000911 // C++ [temp.param]p8:
912 //
913 // A non-type template-parameter of type "array of T" or
914 // "function returning T" is adjusted to be of type "pointer to
915 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000916 else if (T->isArrayType() || T->isFunctionType())
917 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000918
Douglas Gregor463421d2009-03-03 04:44:36 +0000919 Diag(Loc, diag::err_template_nontype_parm_bad_type)
920 << T;
921
922 return QualType();
923}
924
John McCall48871652010-08-21 09:40:31 +0000925Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
926 unsigned Depth,
927 unsigned Position,
928 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000929 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000930 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +0000931
932 if (TInfo->getType()->isUndeducedType()) {
933 Diag(D.getIdentifierLoc(),
934 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
935 << QualType(TInfo->getType()->getContainedAutoType(), 0);
936 }
Douglas Gregor5101c242008-12-05 18:15:24 +0000937
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000938 assert(S->isTemplateParamScope() &&
939 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000940 bool Invalid = false;
941
Richard Smith15361a22016-12-28 06:27:18 +0000942 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000943 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000944 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000945 Invalid = true;
946 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000947
Richard Smithb80d5402013-06-25 22:21:36 +0000948 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000949 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000950 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000951 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000952 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000953 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000955 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000956 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000957
Douglas Gregor5101c242008-12-05 18:15:24 +0000958 if (Invalid)
959 Param->setInvalidDecl();
960
Richard Smithb80d5402013-06-25 22:21:36 +0000961 if (ParamName) {
962 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
963 ParamName);
964
Douglas Gregor5101c242008-12-05 18:15:24 +0000965 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000966 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000967 IdResolver.AddDecl(Param);
968 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969
Douglas Gregorf5500772011-01-05 15:48:55 +0000970 // C++0x [temp.param]p9:
971 // A default template-argument may be specified for any kind of
972 // template-parameter that is not a template parameter pack.
973 if (Default && IsParameterPack) {
974 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000975 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000976 }
977
Douglas Gregordc13ded2010-07-01 00:00:45 +0000978 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000979 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000980 // Check for unexpanded parameter packs.
981 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
982 return Param;
983
Douglas Gregordc13ded2010-07-01 00:00:45 +0000984 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000985 ExprResult DefaultRes =
986 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000987 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000988 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000989 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000990 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000991 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000992
Richard Smith1469b912015-06-10 00:29:03 +0000993 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000994 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000995
John McCall48871652010-08-21 09:40:31 +0000996 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000997}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000998
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000999/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +00001000/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001001/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +00001002Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1003 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00001004 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +00001005 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +00001006 IdentifierInfo *Name,
1007 SourceLocation NameLoc,
1008 unsigned Depth,
1009 unsigned Position,
1010 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +00001011 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001012 assert(S->isTemplateParamScope() &&
1013 "Template template parameter not in template parameter scope!");
1014
1015 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +00001016 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001017 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +00001018 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001019 NameLoc.isInvalid()? TmpLoc : NameLoc,
1020 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +00001021 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001022 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001023
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001024 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +00001025 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001026 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +00001027 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1028
John McCall48871652010-08-21 09:40:31 +00001029 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001030 IdResolver.AddDecl(Param);
1031 }
1032
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001033 if (Params->size() == 0) {
1034 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1035 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1036 Param->setInvalidDecl();
1037 }
1038
Douglas Gregorf5500772011-01-05 15:48:55 +00001039 // C++0x [temp.param]p9:
1040 // A default template-argument may be specified for any kind of
1041 // template-parameter that is not a template parameter pack.
1042 if (IsParameterPack && !Default.isInvalid()) {
1043 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1044 Default = ParsedTemplateArgument();
1045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001046
Douglas Gregordc13ded2010-07-01 00:00:45 +00001047 if (!Default.isInvalid()) {
1048 // Check only that we have a template template argument. We don't want to
1049 // try to check well-formedness now, because our template template parameter
1050 // might have dependent types in its template parameters, which we wouldn't
1051 // be able to match now.
1052 //
1053 // If none of the template template parameter's template arguments mention
1054 // other template parameters, we could actually perform more checking here.
1055 // However, it isn't worth doing.
1056 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1057 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +00001058 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +00001059 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00001060 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001062
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001063 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001064 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001065 DefaultArg.getArgument().getAsTemplate(),
1066 UPPC_DefaultArgument))
1067 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001068
Richard Smith1469b912015-06-10 00:29:03 +00001069 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +00001070 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001071
John McCall48871652010-08-21 09:40:31 +00001072 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +00001073}
1074
Hubert Tongf608c052016-04-29 18:05:37 +00001075/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1076/// constrained by RequiresClause, that contains the template parameters in
1077/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +00001078TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001079Sema::ActOnTemplateParameterList(unsigned Depth,
1080 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001081 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001082 SourceLocation LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001083 ArrayRef<NamedDecl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001084 SourceLocation RAngleLoc,
1085 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001086 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001087 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001088
David Majnemer902f8c62015-12-27 07:16:27 +00001089 return TemplateParameterList::Create(
1090 Context, TemplateLoc, LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001091 llvm::makeArrayRef(Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001092 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001093}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001094
John McCall3e11ebe2010-03-15 10:12:16 +00001095static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1096 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +00001097 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00001098}
1099
John McCallfaf5fb42010-08-26 23:41:50 +00001100DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00001101Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001102 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001103 IdentifierInfo *Name, SourceLocation NameLoc,
1104 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001105 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00001106 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001107 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001108 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +00001109 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +00001110 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001111 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001112 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001113 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001114 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001115
1116 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001117 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001118 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001119
Abramo Bagnara6150c882010-05-11 21:36:43 +00001120 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1121 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001122
1123 // There is no such thing as an unnamed class template.
1124 if (!Name) {
1125 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001126 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001127 }
1128
Richard Smith6483d222012-04-21 01:27:54 +00001129 // Find any previous declaration with this name. For a friend with no
1130 // scope explicitly specified, we only look for tag declarations (per
1131 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001132 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001133 LookupResult Previous(*this, Name, NameLoc,
1134 (SS.isEmpty() && TUK == TUK_Friend)
1135 ? LookupTagName : LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001136 forRedeclarationInCurContext());
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001137 if (SS.isNotEmpty() && !SS.isInvalid()) {
1138 SemanticContext = computeDeclContext(SS, true);
1139 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001140 // FIXME: Horrible, horrible hack! We can't currently represent this
1141 // in the AST, and historically we have just ignored such friend
1142 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001143 Diag(NameLoc, TUK == TUK_Friend
1144 ? diag::warn_template_qualified_friend_ignored
1145 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001146 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001147 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001148 }
Mike Stump11289f42009-09-09 15:08:12 +00001149
John McCall0b66eb32010-05-01 00:40:08 +00001150 if (RequireCompleteDeclContext(SS, SemanticContext))
1151 return true;
1152
Simon Pilgrim6905d222016-12-30 22:55:33 +00001153 // If we're adding a template to a dependent context, we may need to
1154 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001155 // now that we know what the current instantiation is.
1156 if (SemanticContext->isDependentContext()) {
1157 ContextRAII SavedContext(*this, SemanticContext);
1158 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1159 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001160 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1161 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +00001162
John McCall27b18f82009-11-17 02:14:36 +00001163 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001164 } else {
1165 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001166
1167 // C++14 [class.mem]p14:
1168 // If T is the name of a class, then each of the following shall have a
1169 // name different from T:
1170 // -- every member template of class T
1171 if (TUK != TUK_Friend &&
1172 DiagnoseClassNameShadow(SemanticContext,
1173 DeclarationNameInfo(Name, NameLoc)))
1174 return true;
1175
John McCall27b18f82009-11-17 02:14:36 +00001176 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001177 }
Mike Stump11289f42009-09-09 15:08:12 +00001178
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001179 if (Previous.isAmbiguous())
1180 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181
Craig Topperc3ec1492014-05-26 06:22:03 +00001182 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001183 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001184 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001185
Serge Pavlove50bf752016-06-10 04:39:07 +00001186 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1187 // Maybe we will complain about the shadowed template parameter.
1188 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1189 // Just pretend that we didn't see the previous declaration.
1190 PrevDecl = nullptr;
1191 }
1192
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001193 // If there is a previous declaration with the same name, check
1194 // whether this is a valid redeclaration.
Richard Smithbecb92d2017-10-10 22:33:17 +00001195 ClassTemplateDecl *PrevClassTemplate =
1196 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001197
1198 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001199 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001200 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001201 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001202 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1203 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001204 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001205 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1206 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1207 PrevClassTemplate
1208 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1209 ->getSpecializedTemplate();
1210 }
1211 }
1212
John McCalld43784f2009-12-18 11:25:59 +00001213 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001214 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001215 // [...] When looking for a prior declaration of a class or a function
1216 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001217 // function is neither a qualified name nor a template-id, scopes outside
1218 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001219 if (!SS.isSet()) {
1220 DeclContext *OutermostContext = CurContext;
1221 while (!OutermostContext->isFileContext())
1222 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001223
Richard Smith61e582f2012-04-20 07:12:26 +00001224 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001225 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1226 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1227 SemanticContext = PrevDecl->getDeclContext();
1228 } else {
1229 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001230 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001231 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001232 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001233 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001234
1235 // Check that the chosen semantic context doesn't already contain a
1236 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001237 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001238 DeclContext *LookupContext = SemanticContext;
1239 while (LookupContext->isTransparentContext())
1240 LookupContext = LookupContext->getLookupParent();
1241 LookupQualifiedName(Previous, LookupContext);
1242
1243 if (Previous.isAmbiguous())
1244 return true;
1245
1246 if (Previous.begin() != Previous.end())
1247 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001248 }
John McCall90d3bb92009-12-17 23:21:11 +00001249 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001250 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001251 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1252 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001253 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001254
Richard Smithfc805ca2015-07-06 04:43:58 +00001255 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1256 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1257 if (SS.isEmpty() &&
1258 !(PrevClassTemplate &&
1259 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1260 SemanticContext->getRedeclContext()))) {
1261 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1262 Diag(Shadow->getTargetDecl()->getLocation(),
1263 diag::note_using_decl_target);
1264 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1265 // Recover by ignoring the old declaration.
1266 PrevDecl = PrevClassTemplate = nullptr;
1267 }
1268 }
1269
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001270 // TODO Memory management; associated constraints are not always stored.
1271 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1272
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001273 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001274 // Ensure that the template parameter lists are compatible. Skip this check
1275 // for a friend in a dependent context: the template parameter list itself
1276 // could be dependent.
1277 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1278 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001279 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001280 /*Complain=*/true,
1281 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001282 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001283
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001284 // Check for matching associated constraints on redeclarations.
1285 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1286 const bool RedeclACMismatch = [&] {
1287 if (!(CurAC || PrevAC))
1288 return false; // Nothing to check; no mismatch.
1289 if (CurAC && PrevAC) {
1290 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1291 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1292 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1293 if (CurACInfo == PrevACInfo)
1294 return false; // All good; no mismatch.
1295 }
1296 return true;
1297 }();
1298
1299 if (RedeclACMismatch) {
1300 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1301 diag::err_template_different_associated_constraints);
1302 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1303 diag::note_template_prev_declaration) << /*declaration*/0;
1304 return true;
1305 }
1306
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001307 // C++ [temp.class]p4:
1308 // In a redeclaration, partial specialization, explicit
1309 // specialization or explicit instantiation of a class template,
1310 // the class-key shall agree in kind with the original class
1311 // template declaration (7.1.5.3).
1312 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001313 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001314 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001315 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001316 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001317 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001318 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001319 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001320 }
1321
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001322 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001323 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001324 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001325 // If we have a prior definition that is not visible, treat this as
1326 // simply making that previous definition visible.
1327 NamedDecl *Hidden = nullptr;
1328 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001329 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001330 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1331 assert(Tmpl && "original definition of a class template is not a "
1332 "class template?");
Richard Smith858e0e02017-05-11 23:11:16 +00001333 makeMergedDefinitionVisible(Hidden);
1334 makeMergedDefinitionVisible(Tmpl);
Richard Smithbe3980b2015-03-27 00:41:57 +00001335 return Def;
1336 }
1337
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001338 Diag(NameLoc, diag::err_redefinition) << Name;
1339 Diag(Def->getLocation(), diag::note_previous_definition);
1340 // FIXME: Would it make sense to try to "forget" the previous
1341 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001342 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001343 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001344 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001345 } else if (PrevDecl) {
1346 // C++ [temp]p5:
1347 // A class template shall not have the same name as any other
1348 // template, class, function, object, enumeration, enumerator,
1349 // namespace, or type in the same scope (3.3), except as specified
1350 // in (14.5.4).
1351 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1352 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001353 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001354 }
1355
Douglas Gregordba32632009-02-10 19:49:53 +00001356 // Check the template parameter list of this declaration, possibly
1357 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001358 // template declaration. Skip this check for a friend in a dependent
1359 // context, because the template parameter list might be dependent.
1360 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001361 CheckTemplateParameterList(
1362 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001363 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1364 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001365 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1366 SemanticContext->isDependentContext())
1367 ? TPC_ClassTemplateMember
1368 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1369 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001370 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001371
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001372 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001373 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001374 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001375 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1376 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001377 : diag::err_member_decl_does_not_match)
1378 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001379 Invalid = true;
1380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001381 }
1382
Vassil Vassilev352e4412017-01-12 09:16:26 +00001383 // If this is a templated friend in a dependent context we should not put it
1384 // on the redecl chain. In some cases, the templated friend can be the most
1385 // recent declaration tricking the template instantiator to make substitutions
1386 // there.
1387 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1388 bool ShouldAddRedecl
1389 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1390
Mike Stump11289f42009-09-09 15:08:12 +00001391 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001392 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001393 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001394 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001395 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001396 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001397 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001398 NewClass->setTemplateParameterListsInfo(
1399 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1400 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001401
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001402 // Add alignment attributes if necessary; these attributes are checked when
1403 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001404 if (TUK == TUK_Definition) {
1405 AddAlignmentAttributesForRecord(NewClass);
1406 AddMsStructLayoutForRecord(NewClass);
1407 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001408
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001409 // Attach the associated constraints when the declaration will not be part of
1410 // a decl chain.
1411 Expr *const ACtoAttach =
1412 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1413
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001414 ClassTemplateDecl *NewTemplate
1415 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1416 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001417 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001418
1419 if (ShouldAddRedecl)
1420 NewTemplate->setPreviousDecl(PrevClassTemplate);
1421
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001422 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001423
Douglas Gregor21823bf2011-12-20 18:11:52 +00001424 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001425 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001426
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001427 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001428 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001429 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001430 assert(T->isDependentType() && "Class template type is not dependent?");
1431 (void)T;
1432
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001433 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001434 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001435 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001436 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1437 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001438
Anders Carlsson137108d2009-03-26 01:24:28 +00001439 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001440 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001441 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001442
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001443 // Set the lexical context of these templates
1444 NewClass->setLexicalDeclContext(CurContext);
1445 NewTemplate->setLexicalDeclContext(CurContext);
1446
John McCall9bb74a52009-07-31 02:45:11 +00001447 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001448 NewClass->startDefinition();
1449
1450 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001451 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001452
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001453 if (PrevClassTemplate)
1454 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1455
Rafael Espindola385c0422012-07-13 18:04:45 +00001456 AddPushedVisibilityAttribute(NewClass);
1457
Richard Smith234ff472014-08-23 00:49:01 +00001458 if (TUK != TUK_Friend) {
1459 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1460 Scope *Outer = S;
1461 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1462 Outer = Outer->getParent();
1463 PushOnScopeChains(NewTemplate, Outer);
1464 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001465 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001466 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001467 NewClass->setAccess(PrevClassTemplate->getAccess());
1468 }
John McCall27b5c252009-09-14 21:59:20 +00001469
Richard Smith64017682013-07-17 23:53:16 +00001470 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001471
John McCall27b5c252009-09-14 21:59:20 +00001472 // Friend templates are visible in fairly strange ways.
1473 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001474 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001475 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001476 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1477 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001478 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001480
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001481 FriendDecl *Friend = FriendDecl::Create(
1482 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001483 Friend->setAccess(AS_public);
1484 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001485 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001486
Richard Smithbecb92d2017-10-10 22:33:17 +00001487 if (PrevClassTemplate)
1488 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1489
Douglas Gregordba32632009-02-10 19:49:53 +00001490 if (Invalid) {
1491 NewTemplate->setInvalidDecl();
1492 NewClass->setInvalidDecl();
1493 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001494
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001495 ActOnDocumentableDecl(NewTemplate);
1496
John McCall48871652010-08-21 09:40:31 +00001497 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001498}
1499
Richard Smith32918772017-02-14 00:25:28 +00001500namespace {
1501/// Transform to convert portions of a constructor declaration into the
1502/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1503struct ConvertConstructorToDeductionGuideTransform {
1504 ConvertConstructorToDeductionGuideTransform(Sema &S,
1505 ClassTemplateDecl *Template)
1506 : SemaRef(S), Template(Template) {}
1507
1508 Sema &SemaRef;
1509 ClassTemplateDecl *Template;
1510
1511 DeclContext *DC = Template->getDeclContext();
1512 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1513 DeclarationName DeductionGuideName =
1514 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1515
1516 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1517
1518 // Index adjustment to apply to convert depth-1 template parameters into
1519 // depth-0 template parameters.
1520 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1521
1522 /// Transform a constructor declaration into a deduction guide.
Richard Smithbc491202017-02-17 20:05:37 +00001523 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1524 CXXConstructorDecl *CD) {
Richard Smith32918772017-02-14 00:25:28 +00001525 SmallVector<TemplateArgument, 16> SubstArgs;
1526
Richard Smithb4f96252017-02-21 06:30:38 +00001527 LocalInstantiationScope Scope(SemaRef);
1528
Richard Smith32918772017-02-14 00:25:28 +00001529 // C++ [over.match.class.deduct]p1:
1530 // -- For each constructor of the class template designated by the
1531 // template-name, a function template with the following properties:
1532
1533 // -- The template parameters are the template parameters of the class
1534 // template followed by the template parameters (including default
1535 // template arguments) of the constructor, if any.
1536 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1537 if (FTD) {
1538 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1539 SmallVector<NamedDecl *, 16> AllParams;
1540 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1541 AllParams.insert(AllParams.begin(),
1542 TemplateParams->begin(), TemplateParams->end());
1543 SubstArgs.reserve(InnerParams->size());
1544
1545 // Later template parameters could refer to earlier ones, so build up
1546 // a list of substituted template arguments as we go.
1547 for (NamedDecl *Param : *InnerParams) {
1548 MultiLevelTemplateArgumentList Args;
1549 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001550 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001551 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1552 if (!NewParam)
1553 return nullptr;
1554 AllParams.push_back(NewParam);
1555 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1556 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1557 }
1558 TemplateParams = TemplateParameterList::Create(
1559 SemaRef.Context, InnerParams->getTemplateLoc(),
1560 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1561 /*FIXME: RequiresClause*/ nullptr);
1562 }
1563
1564 // If we built a new template-parameter-list, track that we need to
1565 // substitute references to the old parameters into references to the
1566 // new ones.
1567 MultiLevelTemplateArgumentList Args;
1568 if (FTD) {
1569 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001570 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001571 }
1572
Richard Smithbc491202017-02-17 20:05:37 +00001573 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
Richard Smith32918772017-02-14 00:25:28 +00001574 .getAsAdjusted<FunctionProtoTypeLoc>();
1575 assert(FPTL && "no prototype for constructor declaration");
1576
1577 // Transform the type of the function, adjusting the return type and
1578 // replacing references to the old parameters with references to the
1579 // new ones.
1580 TypeLocBuilder TLB;
1581 SmallVector<ParmVarDecl*, 8> Params;
1582 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1583 if (NewType.isNull())
1584 return nullptr;
1585 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1586
Richard Smithbc491202017-02-17 20:05:37 +00001587 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1588 CD->getLocStart(), CD->getLocation(),
1589 CD->getLocEnd());
Richard Smith32918772017-02-14 00:25:28 +00001590 }
1591
1592 /// Build a deduction guide with the specified parameter types.
1593 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1594 SourceLocation Loc = Template->getLocation();
1595
1596 // Build the requested type.
1597 FunctionProtoType::ExtProtoInfo EPI;
1598 EPI.HasTrailingReturn = true;
1599 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1600 DeductionGuideName, EPI);
1601 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1602
1603 FunctionProtoTypeLoc FPTL =
1604 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1605
1606 // Build the parameters, needed during deduction / substitution.
1607 SmallVector<ParmVarDecl*, 4> Params;
1608 for (auto T : ParamTypes) {
1609 ParmVarDecl *NewParam = ParmVarDecl::Create(
1610 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1611 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1612 NewParam->setScopeInfo(0, Params.size());
1613 FPTL.setParam(Params.size(), NewParam);
1614 Params.push_back(NewParam);
1615 }
1616
1617 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1618 Loc, Loc, Loc);
1619 }
1620
1621private:
1622 /// Transform a constructor template parameter into a deduction guide template
1623 /// parameter, rebuilding any internal references to earlier parameters and
1624 /// renumbering as we go.
1625 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1626 MultiLevelTemplateArgumentList &Args) {
1627 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1628 // TemplateTypeParmDecl's index cannot be changed after creation, so
1629 // substitute it directly.
1630 auto *NewTTP = TemplateTypeParmDecl::Create(
1631 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1632 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1633 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1634 TTP->isParameterPack());
1635 if (TTP->hasDefaultArgument()) {
1636 TypeSourceInfo *InstantiatedDefaultArg =
1637 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1638 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1639 if (InstantiatedDefaultArg)
1640 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1641 }
Richard Smithb4f96252017-02-21 06:30:38 +00001642 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1643 NewTTP);
Richard Smith32918772017-02-14 00:25:28 +00001644 return NewTTP;
1645 }
1646
1647 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1648 return transformTemplateParameterImpl(TTP, Args);
1649
1650 return transformTemplateParameterImpl(
1651 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1652 }
1653 template<typename TemplateParmDecl>
1654 TemplateParmDecl *
1655 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1656 MultiLevelTemplateArgumentList &Args) {
1657 // Ask the template instantiator to do the heavy lifting for us, then adjust
1658 // the index of the parameter once it's done.
1659 auto *NewParam =
1660 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1661 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1662 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1663 return NewParam;
1664 }
1665
1666 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1667 FunctionProtoTypeLoc TL,
1668 SmallVectorImpl<ParmVarDecl*> &Params,
1669 MultiLevelTemplateArgumentList &Args) {
1670 SmallVector<QualType, 4> ParamTypes;
1671 const FunctionProtoType *T = TL.getTypePtr();
1672
1673 // -- The types of the function parameters are those of the constructor.
1674 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001675 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001676 if (!NewParam)
1677 return QualType();
1678 ParamTypes.push_back(NewParam->getType());
1679 Params.push_back(NewParam);
1680 }
1681
1682 // -- The return type is the class template specialization designated by
1683 // the template-name and template arguments corresponding to the
1684 // template parameters obtained from the class template.
1685 //
1686 // We use the injected-class-name type of the primary template instead.
1687 // This has the convenient property that it is different from any type that
1688 // the user can write in a deduction-guide (because they cannot enter the
1689 // context of the template), so implicit deduction guides can never collide
1690 // with explicit ones.
1691 QualType ReturnType = DeducedType;
1692 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1693
1694 // Resolving a wording defect, we also inherit the variadicness of the
1695 // constructor.
1696 FunctionProtoType::ExtProtoInfo EPI;
1697 EPI.Variadic = T->isVariadic();
1698 EPI.HasTrailingReturn = true;
1699
1700 QualType Result = SemaRef.BuildFunctionType(
1701 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1702 if (Result.isNull())
1703 return QualType();
1704
1705 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1706 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1707 NewTL.setLParenLoc(TL.getLParenLoc());
1708 NewTL.setRParenLoc(TL.getRParenLoc());
1709 NewTL.setExceptionSpecRange(SourceRange());
1710 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1711 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1712 NewTL.setParam(I, Params[I]);
1713
1714 return Result;
1715 }
1716
1717 ParmVarDecl *
1718 transformFunctionTypeParam(ParmVarDecl *OldParam,
1719 MultiLevelTemplateArgumentList &Args) {
1720 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smith479ba8e2017-04-20 01:15:31 +00001721 TypeSourceInfo *NewDI;
1722 if (!Args.getNumLevels())
1723 NewDI = OldDI;
1724 else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1725 // Expand out the one and only element in each inner pack.
1726 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1727 NewDI =
1728 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1729 OldParam->getLocation(), OldParam->getDeclName());
1730 if (!NewDI) return nullptr;
1731 NewDI =
1732 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1733 PackTL.getTypePtr()->getNumExpansions());
1734 } else
1735 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1736 OldParam->getDeclName());
Richard Smith32918772017-02-14 00:25:28 +00001737 if (!NewDI)
1738 return nullptr;
1739
Richard Smithc27b3d72017-02-14 01:49:59 +00001740 // Canonicalize the type. This (for instance) replaces references to
1741 // typedef members of the current instantiations with the definitions of
1742 // those typedefs, avoiding triggering instantiation of the deduced type
1743 // during deduction.
1744 // FIXME: It would be preferable to retain type sugar and source
1745 // information here (and handle this in substitution instead).
1746 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1747 SemaRef.Context.getCanonicalType(NewDI->getType()),
1748 OldParam->getLocation());
1749
Richard Smith32918772017-02-14 00:25:28 +00001750 // Resolving a wording defect, we also inherit default arguments from the
1751 // constructor.
1752 ExprResult NewDefArg;
1753 if (OldParam->hasDefaultArg()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001754 NewDefArg = Args.getNumLevels()
1755 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1756 : OldParam->getDefaultArg();
Richard Smith32918772017-02-14 00:25:28 +00001757 if (NewDefArg.isInvalid())
1758 return nullptr;
1759 }
1760
1761 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1762 OldParam->getInnerLocStart(),
1763 OldParam->getLocation(),
1764 OldParam->getIdentifier(),
1765 NewDI->getType(),
1766 NewDI,
1767 OldParam->getStorageClass(),
1768 NewDefArg.get());
1769 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1770 OldParam->getFunctionScopeIndex());
1771 return NewParam;
1772 }
1773
1774 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1775 bool Explicit, TypeSourceInfo *TInfo,
1776 SourceLocation LocStart, SourceLocation Loc,
1777 SourceLocation LocEnd) {
Richard Smithbc491202017-02-17 20:05:37 +00001778 DeclarationNameInfo Name(DeductionGuideName, Loc);
Richard Smithefa919a2017-02-16 21:29:21 +00001779 ArrayRef<ParmVarDecl *> Params =
1780 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1781
Richard Smith32918772017-02-14 00:25:28 +00001782 // Build the implicit deduction guide template.
Richard Smithbc491202017-02-17 20:05:37 +00001783 auto *Guide =
1784 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1785 Name, TInfo->getType(), TInfo, LocEnd);
Richard Smith32918772017-02-14 00:25:28 +00001786 Guide->setImplicit();
Richard Smithefa919a2017-02-16 21:29:21 +00001787 Guide->setParams(Params);
1788
1789 for (auto *Param : Params)
1790 Param->setDeclContext(Guide);
Richard Smith32918772017-02-14 00:25:28 +00001791
1792 auto *GuideTemplate = FunctionTemplateDecl::Create(
1793 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1794 GuideTemplate->setImplicit();
1795 Guide->setDescribedFunctionTemplate(GuideTemplate);
1796
1797 if (isa<CXXRecordDecl>(DC)) {
1798 Guide->setAccess(AS_public);
1799 GuideTemplate->setAccess(AS_public);
1800 }
1801
1802 DC->addDecl(GuideTemplate);
1803 return GuideTemplate;
1804 }
1805};
1806}
1807
1808void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1809 SourceLocation Loc) {
1810 DeclContext *DC = Template->getDeclContext();
1811 if (DC->isDependentContext())
1812 return;
1813
1814 ConvertConstructorToDeductionGuideTransform Transform(
1815 *this, cast<ClassTemplateDecl>(Template));
1816 if (!isCompleteType(Loc, Transform.DeducedType))
1817 return;
1818
1819 // Check whether we've already declared deduction guides for this template.
1820 // FIXME: Consider storing a flag on the template to indicate this.
1821 auto Existing = DC->lookup(Transform.DeductionGuideName);
1822 for (auto *D : Existing)
1823 if (D->isImplicit())
1824 return;
1825
1826 // In case we were expanding a pack when we attempted to declare deduction
1827 // guides, turn off pack expansion for everything we're about to do.
1828 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1829 // Create a template instantiation record to track the "instantiation" of
1830 // constructors into deduction guides.
1831 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1832 // this substitution process actually fail?
1833 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1834
1835 // Convert declared constructors into deduction guide templates.
1836 // FIXME: Skip constructors for which deduction must necessarily fail (those
1837 // for which some class template parameter without a default argument never
1838 // appears in a deduced context).
1839 bool AddedAny = false;
Richard Smith32918772017-02-14 00:25:28 +00001840 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1841 D = D->getUnderlyingDecl();
1842 if (D->isInvalidDecl() || D->isImplicit())
1843 continue;
1844 D = cast<NamedDecl>(D->getCanonicalDecl());
1845
1846 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00001847 auto *CD =
1848 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00001849 // Class-scope explicit specializations (MS extension) do not result in
1850 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00001851 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00001852 continue;
1853
Richard Smithbc491202017-02-17 20:05:37 +00001854 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00001855 AddedAny = true;
Richard Smith32918772017-02-14 00:25:28 +00001856 }
1857
Faisal Vali81b756e2017-10-22 14:45:08 +00001858 // C++17 [over.match.class.deduct]
1859 // -- If C is not defined or does not declare any constructors, an
1860 // additional function template derived as above from a hypothetical
1861 // constructor C().
Richard Smith32918772017-02-14 00:25:28 +00001862 if (!AddedAny)
1863 Transform.buildSimpleDeductionGuide(None);
1864
Faisal Vali81b756e2017-10-22 14:45:08 +00001865 // -- An additional function template derived as above from a hypothetical
1866 // constructor C(C), called the copy deduction candidate.
1867 cast<CXXDeductionGuideDecl>(
1868 cast<FunctionTemplateDecl>(
1869 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
1870 ->getTemplatedDecl())
1871 ->setIsCopyDeductionCandidate();
Richard Smith32918772017-02-14 00:25:28 +00001872}
1873
Douglas Gregored5731f2009-11-25 17:50:39 +00001874/// \brief Diagnose the presence of a default template argument on a
1875/// template parameter, which is ill-formed in certain contexts.
1876///
1877/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001878static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001879 Sema::TemplateParamListContext TPC,
1880 SourceLocation ParamLoc,
1881 SourceRange DefArgRange) {
1882 switch (TPC) {
1883 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001884 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001885 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001886 return false;
1887
1888 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001889 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001890 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001891 // A default template-argument shall not be specified in a
1892 // function template declaration or a function template
1893 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00001894 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001895 // template-argument, that declaration shall be a definition and shall be
1896 // the only declaration of the function template in the translation unit.
1897 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001898 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001899 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1900 : diag::ext_template_parameter_default_in_function_template)
1901 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001902 return false;
1903
1904 case Sema::TPC_ClassTemplateMember:
1905 // C++0x [temp.param]p9:
1906 // A default template-argument shall not be specified in the
1907 // template-parameter-lists of the definition of a member of a
1908 // class template that appears outside of the member's class.
1909 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1910 << DefArgRange;
1911 return true;
1912
David Majnemerba8f17a2013-06-25 22:08:55 +00001913 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001914 case Sema::TPC_FriendFunctionTemplate:
1915 // C++ [temp.param]p9:
1916 // A default template-argument shall not be specified in a
1917 // friend template declaration.
1918 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1919 << DefArgRange;
1920 return true;
1921
1922 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1923 // for friend function templates if there is only a single
1924 // declaration (and it is a definition). Strange!
1925 }
1926
David Blaikie8a40f702012-01-17 06:56:22 +00001927 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001928}
1929
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001930/// \brief Check for unexpanded parameter packs within the template parameters
1931/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001932static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1933 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001934 // A template template parameter which is a parameter pack is also a pack
1935 // expansion.
1936 if (TTP->isParameterPack())
1937 return false;
1938
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001939 TemplateParameterList *Params = TTP->getTemplateParameters();
1940 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1941 NamedDecl *P = Params->getParam(I);
1942 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001943 if (!NTTP->isParameterPack() &&
1944 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001945 NTTP->getTypeSourceInfo(),
1946 Sema::UPPC_NonTypeTemplateParameterType))
1947 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001948
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001949 continue;
1950 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001951
1952 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001953 = dyn_cast<TemplateTemplateParmDecl>(P))
1954 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1955 return true;
1956 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001958 return false;
1959}
1960
Douglas Gregordba32632009-02-10 19:49:53 +00001961/// \brief Checks the validity of a template parameter list, possibly
1962/// considering the template parameter list from a previous
1963/// declaration.
1964///
1965/// If an "old" template parameter list is provided, it must be
1966/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1967/// template parameter list.
1968///
1969/// \param NewParams Template parameter list for a new template
1970/// declaration. This template parameter list will be updated with any
1971/// default arguments that are carried through from the previous
1972/// template parameter list.
1973///
1974/// \param OldParams If provided, template parameter list from a
1975/// previous declaration of the same template. Default template
1976/// arguments will be merged from the old template parameter list to
1977/// the new template parameter list.
1978///
Douglas Gregored5731f2009-11-25 17:50:39 +00001979/// \param TPC Describes the context in which we are checking the given
1980/// template parameter list.
1981///
Douglas Gregordba32632009-02-10 19:49:53 +00001982/// \returns true if an error occurred, false otherwise.
1983bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001984 TemplateParameterList *OldParams,
1985 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001986 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001987
Douglas Gregordba32632009-02-10 19:49:53 +00001988 // C++ [temp.param]p10:
1989 // The set of default template-arguments available for use with a
1990 // template declaration or definition is obtained by merging the
1991 // default arguments from the definition (if in scope) and all
1992 // declarations in scope in the same way default function
1993 // arguments are (8.3.6).
1994 bool SawDefaultArgument = false;
1995 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001996
Mike Stumpc89c8e32009-02-11 23:03:27 +00001997 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001998 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001999 if (OldParams)
2000 OldParam = OldParams->begin();
2001
Douglas Gregor0693def2011-01-27 01:40:17 +00002002 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00002003 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2004 NewParamEnd = NewParams->end();
2005 NewParam != NewParamEnd; ++NewParam) {
2006 // Variables used to diagnose redundant default arguments
2007 bool RedundantDefaultArg = false;
2008 SourceLocation OldDefaultLoc;
2009 SourceLocation NewDefaultLoc;
2010
David Blaikie651c73c2011-10-19 05:19:50 +00002011 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00002012 bool MissingDefaultArg = false;
2013
David Blaikie651c73c2011-10-19 05:19:50 +00002014 // Variable used to diagnose non-final parameter packs
2015 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00002016
Douglas Gregordba32632009-02-10 19:49:53 +00002017 if (TemplateTypeParmDecl *NewTypeParm
2018 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00002019 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002020 if (NewTypeParm->hasDefaultArgument() &&
2021 DiagnoseDefaultTemplateArgument(*this, TPC,
2022 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002023 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002024 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00002025 NewTypeParm->removeDefaultArgument();
2026
2027 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002028 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002029 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00002030 if (NewTypeParm->isParameterPack()) {
2031 assert(!NewTypeParm->hasDefaultArgument() &&
2032 "Parameter packs can't have a default argument!");
2033 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002034 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00002035 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00002036 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2037 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2038 SawDefaultArgument = true;
2039 RedundantDefaultArg = true;
2040 PreviousDefaultArgLoc = NewDefaultLoc;
2041 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2042 // Merge the default argument from the old declaration to the
2043 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002044 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002045 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2046 } else if (NewTypeParm->hasDefaultArgument()) {
2047 SawDefaultArgument = true;
2048 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2049 } else if (SawDefaultArgument)
2050 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002051 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00002052 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002053 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002054 if (!NewNonTypeParm->isParameterPack() &&
2055 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002056 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002057 UPPC_NonTypeTemplateParameterType)) {
2058 Invalid = true;
2059 continue;
2060 }
2061
Douglas Gregored5731f2009-11-25 17:50:39 +00002062 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002063 if (NewNonTypeParm->hasDefaultArgument() &&
2064 DiagnoseDefaultTemplateArgument(*this, TPC,
2065 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002066 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00002067 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002068 }
2069
Mike Stump12b8ce12009-08-04 21:02:39 +00002070 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002071 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002072 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002073 if (NewNonTypeParm->isParameterPack()) {
2074 assert(!NewNonTypeParm->hasDefaultArgument() &&
2075 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002076 if (!NewNonTypeParm->isPackExpansion())
2077 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002078 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00002079 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00002080 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2081 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2082 SawDefaultArgument = true;
2083 RedundantDefaultArg = true;
2084 PreviousDefaultArgLoc = NewDefaultLoc;
2085 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2086 // Merge the default argument from the old declaration to the
2087 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002088 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002089 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2090 } else if (NewNonTypeParm->hasDefaultArgument()) {
2091 SawDefaultArgument = true;
2092 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2093 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002094 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002095 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00002096 TemplateTemplateParmDecl *NewTemplateParm
2097 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002098
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002099 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002100 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002101 Invalid = true;
2102 continue;
2103 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002104
David Blaikie651c73c2011-10-19 05:19:50 +00002105 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002106 if (NewTemplateParm->hasDefaultArgument() &&
2107 DiagnoseDefaultTemplateArgument(*this, TPC,
2108 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002109 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002110 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002111
2112 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002113 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002114 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002115 if (NewTemplateParm->isParameterPack()) {
2116 assert(!NewTemplateParm->hasDefaultArgument() &&
2117 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002118 if (!NewTemplateParm->isPackExpansion())
2119 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002120 } else if (OldTemplateParm &&
2121 hasVisibleDefaultArgument(OldTemplateParm) &&
2122 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002123 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2124 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002125 SawDefaultArgument = true;
2126 RedundantDefaultArg = true;
2127 PreviousDefaultArgLoc = NewDefaultLoc;
2128 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2129 // Merge the default argument from the old declaration to the
2130 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002131 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002132 PreviousDefaultArgLoc
2133 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002134 } else if (NewTemplateParm->hasDefaultArgument()) {
2135 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002136 PreviousDefaultArgLoc
2137 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002138 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002139 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002140 }
2141
Richard Smith1fde8ec2012-09-07 02:06:42 +00002142 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002143 // If a template parameter of a primary class template or alias template
2144 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002145 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002146 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2147 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002148 Diag((*NewParam)->getLocation(),
2149 diag::err_template_param_pack_must_be_last_template_parameter);
2150 Invalid = true;
2151 }
2152
Douglas Gregordba32632009-02-10 19:49:53 +00002153 if (RedundantDefaultArg) {
2154 // C++ [temp.param]p12:
2155 // A template-parameter shall not be given default arguments
2156 // by two different declarations in the same scope.
2157 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2158 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2159 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002160 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002161 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002162 // If a template-parameter of a class template has a default
2163 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002164 // have a default template-argument supplied or be a template parameter
2165 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002166 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002167 diag::err_template_param_default_arg_missing);
2168 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2169 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002170 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002171 }
2172
2173 // If we have an old template parameter list that we're merging
2174 // in, move on to the next parameter.
2175 if (OldParams)
2176 ++OldParam;
2177 }
2178
Douglas Gregor0693def2011-01-27 01:40:17 +00002179 // We were missing some default arguments at the end of the list, so remove
2180 // all of the default arguments.
2181 if (RemoveDefaultArguments) {
2182 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2183 NewParamEnd = NewParams->end();
2184 NewParam != NewParamEnd; ++NewParam) {
2185 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2186 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002187 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002188 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2189 NTTP->removeDefaultArgument();
2190 else
2191 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2192 }
2193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002194
Douglas Gregordba32632009-02-10 19:49:53 +00002195 return Invalid;
2196}
Douglas Gregord32e0282009-02-09 23:23:08 +00002197
John McCalla020a012010-10-20 05:44:58 +00002198namespace {
2199
2200/// A class which looks for a use of a certain level of template
2201/// parameter.
2202struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2203 typedef RecursiveASTVisitor<DependencyChecker> super;
2204
2205 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00002206
2207 // Whether we're looking for a use of a template parameter that makes the
2208 // overall construct type-dependent / a dependent type. This is strictly
2209 // best-effort for now; we may fail to match at all for a dependent type
2210 // in some cases if this is set.
2211 bool IgnoreNonTypeDependent;
2212
John McCalla020a012010-10-20 05:44:58 +00002213 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002214 SourceLocation MatchLoc;
2215
Richard Smith13894182017-04-13 21:37:24 +00002216 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2217 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2218 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002219
Richard Smith57aae072016-12-28 02:37:25 +00002220 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith13894182017-04-13 21:37:24 +00002221 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2222 NamedDecl *ND = Params->getParam(0);
2223 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2224 Depth = PD->getDepth();
2225 } else if (NonTypeTemplateParmDecl *PD =
2226 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2227 Depth = PD->getDepth();
2228 } else {
2229 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2230 }
2231 }
John McCalla020a012010-10-20 05:44:58 +00002232
Richard Smith6056d5e2014-02-09 00:54:43 +00002233 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith13894182017-04-13 21:37:24 +00002234 if (ParmDepth >= Depth) {
John McCalla020a012010-10-20 05:44:58 +00002235 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002236 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002237 return true;
2238 }
2239 return false;
2240 }
2241
Richard Smith57aae072016-12-28 02:37:25 +00002242 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2243 // Prune out non-type-dependent expressions if requested. This can
2244 // sometimes result in us failing to find a template parameter reference
2245 // (if a value-dependent expression creates a dependent type), but this
2246 // mode is best-effort only.
2247 if (auto *E = dyn_cast_or_null<Expr>(S))
2248 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2249 return true;
2250 return super::TraverseStmt(S, Q);
2251 }
2252
2253 bool TraverseTypeLoc(TypeLoc TL) {
2254 if (IgnoreNonTypeDependent && !TL.isNull() &&
2255 !TL.getType()->isDependentType())
2256 return true;
2257 return super::TraverseTypeLoc(TL);
2258 }
2259
Richard Smith6056d5e2014-02-09 00:54:43 +00002260 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2261 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2262 }
2263
John McCalla020a012010-10-20 05:44:58 +00002264 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002265 // For a best-effort search, keep looking until we find a location.
2266 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002267 }
2268
2269 bool TraverseTemplateName(TemplateName N) {
2270 if (TemplateTemplateParmDecl *PD =
2271 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002272 if (Matches(PD->getDepth()))
2273 return false;
John McCalla020a012010-10-20 05:44:58 +00002274 return super::TraverseTemplateName(N);
2275 }
2276
2277 bool VisitDeclRefExpr(DeclRefExpr *E) {
2278 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002279 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2280 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002281 return false;
John McCalla020a012010-10-20 05:44:58 +00002282 return super::VisitDeclRefExpr(E);
2283 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002284
2285 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2286 return TraverseType(T->getReplacementType());
2287 }
2288
2289 bool
2290 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2291 return TraverseTemplateArgument(T->getArgumentPack());
2292 }
2293
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002294 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2295 return TraverseType(T->getInjectedSpecializationType());
2296 }
John McCalla020a012010-10-20 05:44:58 +00002297};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002298} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002299
Douglas Gregor972fe532011-05-10 18:27:06 +00002300/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002301/// list.
2302static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002303DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002304 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002305 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002306 return Checker.Match;
2307}
2308
Douglas Gregor972fe532011-05-10 18:27:06 +00002309// Find the source range corresponding to the named type in the given
2310// nested-name-specifier, if any.
2311static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2312 QualType T,
2313 const CXXScopeSpec &SS) {
2314 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2315 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2316 if (const Type *CurType = NNS->getAsType()) {
2317 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2318 return NNSLoc.getTypeLoc().getSourceRange();
2319 } else
2320 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002321
Douglas Gregor972fe532011-05-10 18:27:06 +00002322 NNSLoc = NNSLoc.getPrefix();
2323 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002324
Douglas Gregor972fe532011-05-10 18:27:06 +00002325 return SourceRange();
2326}
2327
Mike Stump11289f42009-09-09 15:08:12 +00002328/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002329/// specifier, returning the template parameter list that applies to the
2330/// name.
2331///
2332/// \param DeclStartLoc the start of the declaration that has a scope
2333/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002334///
Douglas Gregor972fe532011-05-10 18:27:06 +00002335/// \param DeclLoc The location of the declaration itself.
2336///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002337/// \param SS the scope specifier that will be matched to the given template
2338/// parameter lists. This scope specifier precedes a qualified name that is
2339/// being declared.
2340///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002341/// \param TemplateId The template-id following the scope specifier, if there
2342/// is one. Used to check for a missing 'template<>'.
2343///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002344/// \param ParamLists the template parameter lists, from the outermost to the
2345/// innermost template parameter lists.
2346///
John McCalle820e5e2010-04-13 20:37:33 +00002347/// \param IsFriend Whether to apply the slightly different rules for
2348/// matching template parameters to scope specifiers in friend
2349/// declarations.
2350///
Richard Smithf445f192017-02-09 21:04:43 +00002351/// \param IsMemberSpecialization will be set true if the scope specifier
2352/// denotes a fully-specialized type, and therefore this is a declaration of
2353/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002354///
Mike Stump11289f42009-09-09 15:08:12 +00002355/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002356/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002357/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002358/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002359/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002360/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002361TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2362 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002363 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002364 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002365 bool &IsMemberSpecialization, bool &Invalid) {
2366 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002367 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002368
Douglas Gregor972fe532011-05-10 18:27:06 +00002369 // The sequence of nested types to which we will match up the template
2370 // parameter lists. We first build this list by starting with the type named
2371 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002372 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002373 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002374 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002375 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002376 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2377 T = Context.getTypeDeclType(Record);
2378 else
2379 T = QualType(SS.getScopeRep()->getAsType(), 0);
2380 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002381
Douglas Gregor972fe532011-05-10 18:27:06 +00002382 // If we found an explicit specialization that prevents us from needing
2383 // 'template<>' headers, this will be set to the location of that
2384 // explicit specialization.
2385 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002386
Douglas Gregor972fe532011-05-10 18:27:06 +00002387 while (!T.isNull()) {
2388 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002389
Douglas Gregor972fe532011-05-10 18:27:06 +00002390 // Retrieve the parent of a record type.
2391 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2392 // If this type is an explicit specialization, we're done.
2393 if (ClassTemplateSpecializationDecl *Spec
2394 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002395 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002396 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2397 ExplicitSpecLoc = Spec->getLocation();
2398 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002399 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002400 } else if (Record->getTemplateSpecializationKind()
2401 == TSK_ExplicitSpecialization) {
2402 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002403 break;
2404 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002405
Douglas Gregor972fe532011-05-10 18:27:06 +00002406 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2407 T = Context.getTypeDeclType(Parent);
2408 else
2409 T = QualType();
2410 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002411 }
2412
Douglas Gregor972fe532011-05-10 18:27:06 +00002413 if (const TemplateSpecializationType *TST
2414 = T->getAs<TemplateSpecializationType>()) {
2415 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2416 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2417 T = Context.getTypeDeclType(Parent);
2418 else
2419 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002420 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002421 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002422 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002423
Douglas Gregor972fe532011-05-10 18:27:06 +00002424 // Look one step prior in a dependent template specialization type.
2425 if (const DependentTemplateSpecializationType *DependentTST
2426 = T->getAs<DependentTemplateSpecializationType>()) {
2427 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2428 T = QualType(NNS->getAsType(), 0);
2429 else
2430 T = QualType();
2431 continue;
2432 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002433
Douglas Gregor972fe532011-05-10 18:27:06 +00002434 // Look one step prior in a dependent name type.
2435 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2436 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2437 T = QualType(NNS->getAsType(), 0);
2438 else
2439 T = QualType();
2440 continue;
2441 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002442
Douglas Gregor972fe532011-05-10 18:27:06 +00002443 // Retrieve the parent of an enumeration type.
2444 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2445 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2446 // check here.
2447 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002448
Douglas Gregor972fe532011-05-10 18:27:06 +00002449 // Get to the parent type.
2450 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2451 T = Context.getTypeDeclType(Parent);
2452 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002453 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002454 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002455 }
Mike Stump11289f42009-09-09 15:08:12 +00002456
Douglas Gregor972fe532011-05-10 18:27:06 +00002457 T = QualType();
2458 }
2459 // Reverse the nested types list, since we want to traverse from the outermost
2460 // to the innermost while checking template-parameter-lists.
2461 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002462
Douglas Gregor972fe532011-05-10 18:27:06 +00002463 // C++0x [temp.expl.spec]p17:
2464 // A member or a member template may be nested within many
2465 // enclosing class templates. In an explicit specialization for
2466 // such a member, the member declaration shall be preceded by a
2467 // template<> for each enclosing class template that is
2468 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002469 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002470
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002471 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002472 if (SawNonEmptyTemplateParameterList) {
2473 Diag(DeclLoc, diag::err_specialize_member_of_template)
2474 << !Recovery << Range;
2475 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002476 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002477 return true;
2478 }
2479
2480 return false;
2481 };
2482
2483 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2484 // Check that we can have an explicit specialization here.
2485 if (CheckExplicitSpecialization(Range, true))
2486 return true;
2487
2488 // We don't have a template header, but we should.
2489 SourceLocation ExpectedTemplateLoc;
2490 if (!ParamLists.empty())
2491 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2492 else
2493 ExpectedTemplateLoc = DeclStartLoc;
2494
2495 Diag(DeclLoc, diag::err_template_spec_needs_header)
2496 << Range
2497 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2498 return false;
2499 };
2500
Douglas Gregor972fe532011-05-10 18:27:06 +00002501 unsigned ParamIdx = 0;
2502 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2503 ++TypeIdx) {
2504 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002505
Douglas Gregor972fe532011-05-10 18:27:06 +00002506 // Whether we expect a 'template<>' header.
2507 bool NeedEmptyTemplateHeader = false;
2508
2509 // Whether we expect a template header with parameters.
2510 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002511
Douglas Gregor972fe532011-05-10 18:27:06 +00002512 // For a dependent type, the set of template parameters that we
2513 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002514 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002515
Douglas Gregor373af9b2011-05-11 23:26:17 +00002516 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002517 // A member or a member template may be nested within many enclosing
2518 // class templates. In an explicit specialization for such a member, the
2519 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002520 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002521 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2522 if (ClassTemplatePartialSpecializationDecl *Partial
2523 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2524 ExpectedTemplateParams = Partial->getTemplateParameters();
2525 NeedNonemptyTemplateHeader = true;
2526 } else if (Record->isDependentType()) {
2527 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002528 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002529 ->getTemplateParameters();
2530 NeedNonemptyTemplateHeader = true;
2531 }
2532 } else if (ClassTemplateSpecializationDecl *Spec
2533 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2534 // C++0x [temp.expl.spec]p4:
2535 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002536 // in the same manner as members of normal classes, and not using
2537 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002538 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2539 NeedEmptyTemplateHeader = true;
2540 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002541 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002542 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002543 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002544 != TSK_ExplicitSpecialization &&
2545 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002546 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002547
Douglas Gregor373af9b2011-05-11 23:26:17 +00002548 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002549 }
2550 } else if (const TemplateSpecializationType *TST
2551 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002552 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002553 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002554 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002555 }
2556 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2557 // FIXME: We actually could/should check the template arguments here
2558 // against the corresponding template parameter list.
2559 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002560 }
2561
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002562 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002563 // In an explicit specialization declaration for a member of a class
2564 // template or a member template that ap- pears in namespace scope, the
2565 // member template and some of its enclosing class templates may remain
2566 // unspecialized, except that the declaration shall not explicitly
2567 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002568 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002569 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002570 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002571 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2572 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002573 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002574 } else
2575 SawNonEmptyTemplateParameterList = true;
2576 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002577
Douglas Gregor972fe532011-05-10 18:27:06 +00002578 if (NeedEmptyTemplateHeader) {
2579 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002580 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002581 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002582 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002583
2584 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002585 if (ParamLists[ParamIdx]->size() > 0) {
2586 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002587 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002588 diag::err_template_param_list_matches_nontemplate)
2589 << T
2590 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2591 ParamLists[ParamIdx]->getRAngleLoc())
2592 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2593 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002594 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002595 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002596
Douglas Gregor972fe532011-05-10 18:27:06 +00002597 // Consume this template header.
2598 ++ParamIdx;
2599 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002600 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002601
2602 if (!IsFriend)
2603 if (DiagnoseMissingExplicitSpecialization(
2604 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002605 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002606
Douglas Gregor972fe532011-05-10 18:27:06 +00002607 continue;
2608 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002609
Douglas Gregor972fe532011-05-10 18:27:06 +00002610 if (NeedNonemptyTemplateHeader) {
2611 // In friend declarations we can have template-ids which don't
2612 // depend on the corresponding template parameter lists. But
2613 // assume that empty parameter lists are supposed to match this
2614 // template-id.
2615 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002616 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002617 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002618 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002619 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002620 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002621 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002622
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002623 if (ParamIdx < ParamLists.size()) {
2624 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002625 if (ExpectedTemplateParams &&
2626 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2627 ExpectedTemplateParams,
2628 true, TPL_TemplateMatch))
2629 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002630
Douglas Gregor972fe532011-05-10 18:27:06 +00002631 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002632 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002633 TPC_ClassTemplateMember))
2634 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002635
Douglas Gregor972fe532011-05-10 18:27:06 +00002636 ++ParamIdx;
2637 continue;
2638 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002639
Douglas Gregor972fe532011-05-10 18:27:06 +00002640 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2641 << T
2642 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2643 Invalid = true;
2644 continue;
2645 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002646 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002647
Douglas Gregord8d297c2009-07-21 23:53:31 +00002648 // If there were at least as many template-ids as there were template
2649 // parameter lists, then there are no template parameter lists remaining for
2650 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002651 if (ParamIdx >= ParamLists.size()) {
2652 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002653 // We don't have a template header for the declaration itself, but we
2654 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002655 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2656 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002657
2658 // Fabricate an empty template parameter list for the invented header.
2659 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002660 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002661 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002662 }
2663
Craig Topperc3ec1492014-05-26 06:22:03 +00002664 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002665 }
Mike Stump11289f42009-09-09 15:08:12 +00002666
Douglas Gregord8d297c2009-07-21 23:53:31 +00002667 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002668 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002669 bool HasAnyExplicitSpecHeader = false;
2670 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002671 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002672 if (ParamLists[I]->size() == 0)
2673 HasAnyExplicitSpecHeader = true;
2674 else
2675 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002676 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002677
Douglas Gregor972fe532011-05-10 18:27:06 +00002678 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002679 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2680 : diag::err_template_spec_extra_headers)
2681 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2682 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002683
2684 // If there was a specialization somewhere, such that 'template<>' is
2685 // not required, and there were any 'template<>' headers, note where the
2686 // specialization occurred.
2687 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002688 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002689 diag::note_explicit_template_spec_does_not_need_header)
2690 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002691
Douglas Gregor972fe532011-05-10 18:27:06 +00002692 // We have a template parameter list with no corresponding scope, which
2693 // means that the resulting template declaration can't be instantiated
2694 // properly (we'll end up with dependent nodes when we shouldn't).
2695 if (!AllExplicitSpecHeaders)
2696 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002697 }
Mike Stump11289f42009-09-09 15:08:12 +00002698
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002699 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002700 // In an explicit specialization declaration for a member of a class
2701 // template or a member template that ap- pears in namespace scope, the
2702 // member template and some of its enclosing class templates may remain
2703 // unspecialized, except that the declaration shall not explicitly
2704 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002705 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002706 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002707 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2708 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002709 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002710
Douglas Gregord8d297c2009-07-21 23:53:31 +00002711 // Return the last template parameter list, which corresponds to the
2712 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002713 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002714}
2715
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002716void Sema::NoteAllFoundTemplates(TemplateName Name) {
2717 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2718 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002719 << (isa<FunctionTemplateDecl>(Template)
2720 ? 0
2721 : isa<ClassTemplateDecl>(Template)
2722 ? 1
2723 : isa<VarTemplateDecl>(Template)
2724 ? 2
2725 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2726 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002727 return;
2728 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002729
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002730 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002731 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002732 IEnd = OST->end();
2733 I != IEnd; ++I)
2734 Diag((*I)->getLocation(), diag::note_template_declared_here)
2735 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002736
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002737 return;
2738 }
2739}
2740
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002741static QualType
2742checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2743 const SmallVectorImpl<TemplateArgument> &Converted,
2744 SourceLocation TemplateLoc,
2745 TemplateArgumentListInfo &TemplateArgs) {
2746 ASTContext &Context = SemaRef.getASTContext();
2747 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002748 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002749 // Specializations of __make_integer_seq<S, T, N> are treated like
2750 // S<T, 0, ..., N-1>.
2751
2752 // C++14 [inteseq.intseq]p1:
2753 // T shall be an integer type.
2754 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2755 SemaRef.Diag(TemplateArgs[1].getLocation(),
2756 diag::err_integer_sequence_integral_element_type);
2757 return QualType();
2758 }
2759
2760 // C++14 [inteseq.make]p1:
2761 // If N is negative the program is ill-formed.
2762 TemplateArgument NumArgsArg = Converted[2];
2763 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2764 if (NumArgs < 0) {
2765 SemaRef.Diag(TemplateArgs[2].getLocation(),
2766 diag::err_integer_sequence_negative_length);
2767 return QualType();
2768 }
2769
2770 QualType ArgTy = NumArgsArg.getIntegralType();
2771 TemplateArgumentListInfo SyntheticTemplateArgs;
2772 // The type argument gets reused as the first template argument in the
2773 // synthetic template argument list.
2774 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2775 // Expand N into 0 ... N-1.
2776 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2777 I < NumArgs; ++I) {
2778 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002779 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2780 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002781 }
2782 // The first template argument will be reused as the template decl that
2783 // our synthetic template arguments will be applied to.
2784 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2785 TemplateLoc, SyntheticTemplateArgs);
2786 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002787
2788 case BTK__type_pack_element:
2789 // Specializations of
2790 // __type_pack_element<Index, T_1, ..., T_N>
2791 // are treated like T_Index.
2792 assert(Converted.size() == 2 &&
2793 "__type_pack_element should be given an index and a parameter pack");
2794
2795 // If the Index is out of bounds, the program is ill-formed.
2796 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2797 llvm::APSInt Index = IndexArg.getAsIntegral();
2798 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2799 "type std::size_t, and hence be non-negative");
2800 if (Index >= Ts.pack_size()) {
2801 SemaRef.Diag(TemplateArgs[0].getLocation(),
2802 diag::err_type_pack_element_out_of_bounds);
2803 return QualType();
2804 }
2805
2806 // We simply return the type at index `Index`.
2807 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2808 return Nth->getAsType();
2809 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002810 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2811}
2812
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002813/// Determine whether this alias template is "enable_if_t".
2814static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
2815 return AliasTemplate->getName().equals("enable_if_t");
2816}
2817
2818/// Collect all of the separable terms in the given condition, which
2819/// might be a conjunction.
2820///
2821/// FIXME: The right answer is to convert the logical expression into
2822/// disjunctive normal form, so we can find the first failed term
2823/// within each possible clause.
2824static void collectConjunctionTerms(Expr *Clause,
2825 SmallVectorImpl<Expr *> &Terms) {
2826 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
2827 if (BinOp->getOpcode() == BO_LAnd) {
2828 collectConjunctionTerms(BinOp->getLHS(), Terms);
2829 collectConjunctionTerms(BinOp->getRHS(), Terms);
2830 }
2831
2832 return;
2833 }
2834
2835 Terms.push_back(Clause);
2836}
2837
Douglas Gregorbb33f572017-07-05 20:20:15 +00002838// The ranges-v3 library uses an odd pattern of a top-level "||" with
2839// a left-hand side that is value-dependent but never true. Identify
2840// the idiom and ignore that term.
2841static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
2842 // Top-level '||'.
2843 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
2844 if (!BinOp) return Cond;
2845
2846 if (BinOp->getOpcode() != BO_LOr) return Cond;
2847
2848 // With an inner '==' that has a literal on the right-hand side.
2849 Expr *LHS = BinOp->getLHS();
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00002850 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
Douglas Gregorbb33f572017-07-05 20:20:15 +00002851 if (!InnerBinOp) return Cond;
2852
2853 if (InnerBinOp->getOpcode() != BO_EQ ||
2854 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
2855 return Cond;
2856
2857 // If the inner binary operation came from a macro expansion named
2858 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
2859 // of the '||', which is the real, user-provided condition.
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00002860 SourceLocation Loc = InnerBinOp->getExprLoc();
Douglas Gregorbb33f572017-07-05 20:20:15 +00002861 if (!Loc.isMacroID()) return Cond;
2862
2863 StringRef MacroName = PP.getImmediateMacroName(Loc);
2864 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
2865 return BinOp->getRHS();
2866
2867 return Cond;
2868}
2869
Douglas Gregor672281a2017-09-14 23:38:42 +00002870std::pair<Expr *, std::string>
2871Sema::findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond) {
2872 Cond = lookThroughRangesV3Condition(PP, Cond);
Douglas Gregorbb33f572017-07-05 20:20:15 +00002873
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002874 // Separate out all of the terms in a conjunction.
2875 SmallVector<Expr *, 4> Terms;
2876 collectConjunctionTerms(Cond, Terms);
2877
2878 // Determine which term failed.
2879 Expr *FailedCond = nullptr;
2880 for (Expr *Term : Terms) {
Douglas Gregor672281a2017-09-14 23:38:42 +00002881 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
2882
2883 // Literals are uninteresting.
2884 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
2885 isa<IntegerLiteral>(TermAsWritten))
2886 continue;
2887
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002888 // The initialization of the parameter from the argument is
2889 // a constant-evaluated context.
2890 EnterExpressionEvaluationContext ConstantEvaluated(
Douglas Gregor672281a2017-09-14 23:38:42 +00002891 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002892
2893 bool Succeeded;
Douglas Gregor672281a2017-09-14 23:38:42 +00002894 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002895 !Succeeded) {
Douglas Gregor672281a2017-09-14 23:38:42 +00002896 FailedCond = TermAsWritten;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002897 break;
2898 }
2899 }
2900
Douglas Gregor672281a2017-09-14 23:38:42 +00002901 if (!FailedCond) {
2902 if (!AllowTopLevelCond)
2903 return { nullptr, "" };
2904
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002905 FailedCond = Cond->IgnoreParenImpCasts();
Douglas Gregor672281a2017-09-14 23:38:42 +00002906 }
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002907
2908 std::string Description;
2909 {
2910 llvm::raw_string_ostream Out(Description);
Douglas Gregor672281a2017-09-14 23:38:42 +00002911 FailedCond->printPretty(Out, nullptr, getPrintingPolicy());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002912 }
2913 return { FailedCond, Description };
2914}
2915
Douglas Gregordc572a32009-03-30 22:58:21 +00002916QualType Sema::CheckTemplateIdType(TemplateName Name,
2917 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002918 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002919 DependentTemplateName *DTN
2920 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002921 if (DTN && DTN->isIdentifier())
2922 // When building a template-id where the template-name is dependent,
2923 // assume the template is a type template. Either our assumption is
2924 // correct, or the code is ill-formed and will be diagnosed when the
2925 // dependent name is substituted.
2926 return Context.getDependentTemplateSpecializationType(ETK_None,
2927 DTN->getQualifier(),
2928 DTN->getIdentifier(),
2929 TemplateArgs);
2930
Douglas Gregordc572a32009-03-30 22:58:21 +00002931 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002932 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2933 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002934 // We might have a substituted template template parameter pack. If so,
2935 // build a template specialization type for it.
2936 if (Name.getAsSubstTemplateTemplateParmPack())
2937 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002938
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002939 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2940 << Name;
2941 NoteAllFoundTemplates(Name);
2942 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002943 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002944
Douglas Gregorc40290e2009-03-09 23:48:35 +00002945 // Check that the template argument list is well-formed for this
2946 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002947 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002948 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002949 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002950 return QualType();
2951
Douglas Gregorc40290e2009-03-09 23:48:35 +00002952 QualType CanonType;
2953
Douglas Gregor678d76c2011-07-01 01:22:09 +00002954 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002955 if (TypeAliasTemplateDecl *AliasTemplate =
2956 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002957 // Find the canonical type for this type alias template specialization.
2958 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2959 if (Pattern->isInvalidDecl())
2960 return QualType();
2961
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002962 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
2963 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002964
2965 // Only substitute for the innermost template argument list.
2966 MultiLevelTemplateArgumentList TemplateArgLists;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002967 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002968 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2969 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002970 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002971
Richard Smith802c4b72012-08-23 06:16:52 +00002972 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002973 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002974 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002975 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002976
Richard Smith3f1b5d02011-05-05 21:57:07 +00002977 CanonType = SubstType(Pattern->getUnderlyingType(),
2978 TemplateArgLists, AliasTemplate->getLocation(),
2979 AliasTemplate->getDeclName());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002980 if (CanonType.isNull()) {
2981 // If this was enable_if and we failed to find the nested type
2982 // within enable_if in a SFINAE context, dig out the specific
2983 // enable_if condition that failed and present that instead.
2984 if (isEnableIfAliasTemplate(AliasTemplate)) {
2985 if (auto DeductionInfo = isSFINAEContext()) {
2986 if (*DeductionInfo &&
2987 (*DeductionInfo)->hasSFINAEDiagnostic() &&
2988 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
2989 diag::err_typename_nested_not_found_enable_if &&
2990 TemplateArgs[0].getArgument().getKind()
2991 == TemplateArgument::Expression) {
2992 Expr *FailedCond;
2993 std::string FailedDescription;
2994 std::tie(FailedCond, FailedDescription) =
Douglas Gregor672281a2017-09-14 23:38:42 +00002995 findFailedBooleanCondition(
2996 TemplateArgs[0].getSourceExpression(),
2997 /*AllowTopLevelCond=*/true);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002998
2999 // Remove the old SFINAE diagnostic.
3000 PartialDiagnosticAt OldDiag =
3001 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3002 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3003
3004 // Add a new SFINAE diagnostic specifying which condition
3005 // failed.
3006 (*DeductionInfo)->addSFINAEDiagnostic(
3007 OldDiag.first,
3008 PDiag(diag::err_typename_nested_not_found_requirement)
3009 << FailedDescription
3010 << FailedCond->getSourceRange());
3011 }
3012 }
3013 }
3014
Richard Smith3f1b5d02011-05-05 21:57:07 +00003015 return QualType();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003016 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003017 } else if (Name.isDependent() ||
3018 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00003019 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003020 // This class template specialization is a dependent
3021 // type. Therefore, its canonical type is another class template
3022 // specialization type that contains all of the converted
3023 // arguments in canonical form. This ensures that, e.g., A<T> and
3024 // A<T, T> have identical types when A is declared as:
3025 //
3026 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003027 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00003028
3029 // This might work out to be a current instantiation, in which
3030 // case the canonical type needs to be the InjectedClassNameType.
3031 //
3032 // TODO: in theory this could be a simple hashtable lookup; most
3033 // changes to CurContext don't change the set of current
3034 // instantiations.
3035 if (isa<ClassTemplateDecl>(Template)) {
3036 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3037 // If we get out to a namespace, we're done.
3038 if (Ctx->isFileContext()) break;
3039
3040 // If this isn't a record, keep looking.
3041 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3042 if (!Record) continue;
3043
3044 // Look for one of the two cases with InjectedClassNameTypes
3045 // and check whether it's the same template.
3046 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3047 !Record->getDescribedClassTemplate())
3048 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003049
John McCall2408e322010-04-27 00:57:59 +00003050 // Fetch the injected class name type and check whether its
3051 // injected type is equal to the type we just built.
3052 QualType ICNT = Context.getTypeDeclType(Record);
3053 QualType Injected = cast<InjectedClassNameType>(ICNT)
3054 ->getInjectedSpecializationType();
3055
3056 if (CanonType != Injected->getCanonicalTypeInternal())
3057 continue;
3058
3059 // If so, the canonical type of this TST is the injected
3060 // class name type of the record we just found.
3061 assert(ICNT.isCanonical());
3062 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00003063 break;
3064 }
3065 }
Mike Stump11289f42009-09-09 15:08:12 +00003066 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00003067 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003068 // Find the class template specialization declaration that
3069 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003070 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003071 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00003072 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003073 if (!Decl) {
3074 // This is the first time we have referenced this class template
3075 // specialization. Create the canonical declaration and add it to
3076 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003077 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00003078 ClassTemplate->getTemplatedDecl()->getTagKind(),
3079 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00003080 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003081 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003082 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00003083 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003084 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00003085 if (ClassTemplate->isOutOfLine())
3086 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00003087 }
3088
Erich Keanea32910d2017-03-23 18:51:54 +00003089 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3090 MultiLevelTemplateArgumentList TemplateArgLists;
3091 TemplateArgLists.addOuterTemplateArguments(Converted);
3092 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3093 Decl);
3094 }
3095
Chandler Carruth2acfb222013-09-27 22:14:40 +00003096 // Diagnose uses of this specialization.
3097 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3098
Douglas Gregorc40290e2009-03-09 23:48:35 +00003099 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00003100 assert(isa<RecordType>(CanonType) &&
3101 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003102 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3103 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3104 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003105 }
Mike Stump11289f42009-09-09 15:08:12 +00003106
Douglas Gregorc40290e2009-03-09 23:48:35 +00003107 // Build the fully-sugared type for this class template
3108 // specialization, which refers back to the class template
3109 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00003110 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003111}
3112
John McCallfaf5fb42010-08-26 23:41:50 +00003113TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003114Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00003115 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3116 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00003117 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00003118 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00003119 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00003120 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003121 if (SS.isInvalid())
3122 return true;
3123
Richard Smith62559bd2017-02-01 21:36:38 +00003124 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3125 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3126
3127 // C++ [temp.res]p3:
3128 // A qualified-id that refers to a type and in which the
3129 // nested-name-specifier depends on a template-parameter (14.6.2)
3130 // shall be prefixed by the keyword typename to indicate that the
3131 // qualified-id denotes a type, forming an
3132 // elaborated-type-specifier (7.1.5.3).
3133 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00003134 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00003135 << SS.getScopeRep() << TemplateII->getName();
3136 // Recover as if 'typename' were specified.
3137 // FIXME: This is not quite correct recovery as we don't transform SS
3138 // into the corresponding dependent form (and we don't diagnose missing
3139 // 'template' keywords within SS as a result).
3140 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3141 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3142 TemplateArgsIn, RAngleLoc);
3143 }
3144
3145 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3146 // it's not actually allowed to be used as a type in most cases. Because
3147 // we annotate it before we know whether it's valid, we have to check for
3148 // this case here.
3149 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00003150 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3151 Diag(TemplateIILoc,
3152 TemplateKWLoc.isInvalid()
3153 ? diag::err_out_of_line_qualified_id_type_names_constructor
3154 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3155 << TemplateII << 0 /*injected-class-name used as template name*/
3156 << 1 /*if any keyword was present, it was 'template'*/;
3157 }
3158 }
3159
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003160 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00003161
Douglas Gregorc40290e2009-03-09 23:48:35 +00003162 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003163 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003164 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00003165
Douglas Gregor5a064722011-02-28 17:23:35 +00003166 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00003167 QualType T
3168 = Context.getDependentTemplateSpecializationType(ETK_None,
3169 DTN->getQualifier(),
3170 DTN->getIdentifier(),
3171 TemplateArgs);
3172 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00003173 TypeLocBuilder TLB;
3174 DependentTemplateSpecializationTypeLoc SpecTL
3175 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003176 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3177 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003178 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003179 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003180 SpecTL.setLAngleLoc(LAngleLoc);
3181 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003182 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3183 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3184 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3185 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003186
Richard Smith74f02342017-01-19 21:00:13 +00003187 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003188 if (Result.isNull())
3189 return true;
3190
Douglas Gregore7c20652011-03-02 00:47:37 +00003191 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003192 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00003193 TemplateSpecializationTypeLoc SpecTL
3194 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003195 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003196 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003197 SpecTL.setLAngleLoc(LAngleLoc);
3198 SpecTL.setRAngleLoc(RAngleLoc);
3199 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3200 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00003201
Abramo Bagnara4244b432012-01-27 08:46:19 +00003202 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3203 // constructor or destructor name (in such a case, the scope specifier
3204 // will be attached to the enclosing Decl or Expr node).
3205 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003206 // Create an elaborated-type-specifier containing the nested-name-specifier.
3207 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3208 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003209 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00003210 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3211 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003212
Douglas Gregore7c20652011-03-02 00:47:37 +00003213 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00003214}
John McCall06f6fe8d2009-09-04 01:14:41 +00003215
Douglas Gregore7c20652011-03-02 00:47:37 +00003216TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00003217 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00003218 SourceLocation TagLoc,
3219 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003220 SourceLocation TemplateKWLoc,
3221 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00003222 SourceLocation TemplateLoc,
3223 SourceLocation LAngleLoc,
3224 ASTTemplateArgsPtr TemplateArgsIn,
3225 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003226 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003227
Douglas Gregore7c20652011-03-02 00:47:37 +00003228 // Translate the parser's template argument list in our AST format.
3229 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3230 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003231
Douglas Gregore7c20652011-03-02 00:47:37 +00003232 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00003233 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00003234 ElaboratedTypeKeyword Keyword
3235 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00003236
Douglas Gregore7c20652011-03-02 00:47:37 +00003237 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3238 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00003239 DTN->getQualifier(),
3240 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00003241 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003242
3243 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00003244 TypeLocBuilder TLB;
3245 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003246 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3247 SpecTL.setElaboratedKeywordLoc(TagLoc);
3248 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003249 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003250 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003251 SpecTL.setLAngleLoc(LAngleLoc);
3252 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003253 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3254 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3255 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3256 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003257
3258 if (TypeAliasTemplateDecl *TAT =
3259 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3260 // C++0x [dcl.type.elab]p2:
3261 // If the identifier resolves to a typedef-name or the simple-template-id
3262 // resolves to an alias template specialization, the
3263 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003264 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3265 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003266 Diag(TAT->getLocation(), diag::note_declared_at);
3267 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003268
Douglas Gregore7c20652011-03-02 00:47:37 +00003269 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3270 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003271 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003272
Douglas Gregore7c20652011-03-02 00:47:37 +00003273 // Check the tag kind
3274 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003275 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003276
John McCalld8fe9af2009-09-08 17:47:29 +00003277 IdentifierInfo *Id = D->getIdentifier();
3278 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003279
Richard Trieucaa33d32011-06-10 03:11:26 +00003280 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003281 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003282 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003283 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003284 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003285 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003286 }
3287 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003288
Douglas Gregore7c20652011-03-02 00:47:37 +00003289 // Provide source-location information for the template specialization.
3290 TypeLocBuilder TLB;
3291 TemplateSpecializationTypeLoc SpecTL
3292 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003293 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003294 SpecTL.setTemplateNameLoc(TemplateLoc);
3295 SpecTL.setLAngleLoc(LAngleLoc);
3296 SpecTL.setRAngleLoc(RAngleLoc);
3297 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3298 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003299
Douglas Gregore7c20652011-03-02 00:47:37 +00003300 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003301 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003302 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3303 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003304 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003305 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3306 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003307}
3308
Larisse Voufo39a1e502013-08-06 01:03:05 +00003309static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3310 NamedDecl *PrevDecl,
3311 SourceLocation Loc,
3312 bool IsPartialSpecialization);
3313
3314static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003315
Richard Smith300e0c32013-09-24 04:49:23 +00003316static bool isTemplateArgumentTemplateParameter(
3317 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3318 switch (Arg.getKind()) {
3319 case TemplateArgument::Null:
3320 case TemplateArgument::NullPtr:
3321 case TemplateArgument::Integral:
3322 case TemplateArgument::Declaration:
3323 case TemplateArgument::Pack:
3324 case TemplateArgument::TemplateExpansion:
3325 return false;
3326
3327 case TemplateArgument::Type: {
3328 QualType Type = Arg.getAsType();
3329 const TemplateTypeParmType *TPT =
3330 Arg.getAsType()->getAs<TemplateTypeParmType>();
3331 return TPT && !Type.hasQualifiers() &&
3332 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3333 }
3334
3335 case TemplateArgument::Expression: {
3336 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3337 if (!DRE || !DRE->getDecl())
3338 return false;
3339 const NonTypeTemplateParmDecl *NTTP =
3340 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3341 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3342 }
3343
3344 case TemplateArgument::Template:
3345 const TemplateTemplateParmDecl *TTP =
3346 dyn_cast_or_null<TemplateTemplateParmDecl>(
3347 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3348 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3349 }
3350 llvm_unreachable("unexpected kind of template argument");
3351}
3352
3353static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3354 ArrayRef<TemplateArgument> Args) {
3355 if (Params->size() != Args.size())
3356 return false;
3357
3358 unsigned Depth = Params->getDepth();
3359
3360 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3361 TemplateArgument Arg = Args[I];
3362
3363 // If the parameter is a pack expansion, the argument must be a pack
3364 // whose only element is a pack expansion.
3365 if (Params->getParam(I)->isParameterPack()) {
3366 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3367 !Arg.pack_begin()->isPackExpansion())
3368 return false;
3369 Arg = Arg.pack_begin()->getPackExpansionPattern();
3370 }
3371
3372 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3373 return false;
3374 }
3375
3376 return true;
3377}
3378
Richard Smith4b55a9c2014-04-17 03:29:33 +00003379/// Convert the parser's template argument list representation into our form.
3380static TemplateArgumentListInfo
3381makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3382 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3383 TemplateId.RAngleLoc);
3384 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3385 TemplateId.NumArgs);
3386 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3387 return TemplateArgs;
3388}
3389
Richard Smith0e617ec2016-12-27 07:56:27 +00003390template<typename PartialSpecDecl>
3391static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3392 if (Partial->getDeclContext()->isDependentContext())
3393 return;
3394
3395 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3396 // for non-substitution-failure issues?
3397 TemplateDeductionInfo Info(Partial->getLocation());
3398 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3399 return;
3400
3401 auto *Template = Partial->getSpecializedTemplate();
3402 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003403 diag::ext_partial_spec_not_more_specialized_than_primary)
3404 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003405
3406 if (Info.hasSFINAEDiagnostic()) {
3407 PartialDiagnosticAt Diag = {SourceLocation(),
3408 PartialDiagnostic::NullDiagnostic()};
3409 Info.takeSFINAEDiagnostic(Diag);
3410 SmallString<128> SFINAEArgString;
3411 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3412 S.Diag(Diag.first,
3413 diag::note_partial_spec_not_more_specialized_than_primary)
3414 << SFINAEArgString;
3415 }
3416
3417 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3418}
3419
Richard Smith4e05eaa2017-02-16 00:36:47 +00003420static void
3421noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3422 const llvm::SmallBitVector &DeducibleParams) {
3423 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3424 if (!DeducibleParams[I]) {
3425 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3426 if (Param->getDeclName())
3427 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3428 << Param->getDeclName();
3429 else
3430 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3431 << "(anonymous)";
3432 }
3433 }
3434}
3435
3436
Richard Smith57aae072016-12-28 02:37:25 +00003437template<typename PartialSpecDecl>
3438static void checkTemplatePartialSpecialization(Sema &S,
3439 PartialSpecDecl *Partial) {
3440 // C++1z [temp.class.spec]p8: (DR1495)
3441 // - The specialization shall be more specialized than the primary
3442 // template (14.5.5.2).
3443 checkMoreSpecializedThanPrimary(S, Partial);
3444
3445 // C++ [temp.class.spec]p8: (DR1315)
3446 // - Each template-parameter shall appear at least once in the
3447 // template-id outside a non-deduced context.
3448 // C++1z [temp.class.spec.match]p3 (P0127R2)
3449 // If the template arguments of a partial specialization cannot be
3450 // deduced because of the structure of its template-parameter-list
3451 // and the template-id, the program is ill-formed.
3452 auto *TemplateParams = Partial->getTemplateParameters();
3453 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3454 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3455 TemplateParams->getDepth(), DeducibleParams);
3456
3457 if (!DeducibleParams.all()) {
3458 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3459 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3460 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3461 << (NumNonDeducible > 1)
3462 << SourceRange(Partial->getLocation(),
3463 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003464 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003465 }
3466}
3467
3468void Sema::CheckTemplatePartialSpecialization(
3469 ClassTemplatePartialSpecializationDecl *Partial) {
3470 checkTemplatePartialSpecialization(*this, Partial);
3471}
3472
3473void Sema::CheckTemplatePartialSpecialization(
3474 VarTemplatePartialSpecializationDecl *Partial) {
3475 checkTemplatePartialSpecialization(*this, Partial);
3476}
3477
Richard Smith4e05eaa2017-02-16 00:36:47 +00003478void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3479 // C++1z [temp.param]p11:
3480 // A template parameter of a deduction guide template that does not have a
3481 // default-argument shall be deducible from the parameter-type-list of the
3482 // deduction guide template.
3483 auto *TemplateParams = TD->getTemplateParameters();
3484 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3485 MarkDeducedTemplateParameters(TD, DeducibleParams);
3486 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3487 // A parameter pack is deducible (to an empty pack).
3488 auto *Param = TemplateParams->getParam(I);
3489 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3490 DeducibleParams[I] = true;
3491 }
3492
3493 if (!DeducibleParams.all()) {
3494 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3495 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3496 << (NumNonDeducible > 1);
3497 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3498 }
3499}
3500
Larisse Voufo39a1e502013-08-06 01:03:05 +00003501DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003502 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003503 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003504 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003505 // D must be variable template id.
3506 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
3507 "Variable template specialization is declared with a template it.");
3508
3509 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003510 TemplateArgumentListInfo TemplateArgs =
3511 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003512 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3513 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3514 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003515
Richard Smithbeef3452014-01-16 23:39:20 +00003516 TemplateName Name = TemplateId->Template.get();
3517
3518 // The template-id must name a variable template.
3519 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003520 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3521 if (!VarTemplate) {
3522 NamedDecl *FnTemplate;
3523 if (auto *OTS = Name.getAsOverloadedTemplate())
3524 FnTemplate = *OTS->begin();
3525 else
3526 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3527 if (FnTemplate)
3528 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3529 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003530 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3531 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003532 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003533
3534 // Check for unexpanded parameter packs in any of the template arguments.
3535 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3536 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3537 UPPC_PartialSpecialization))
3538 return true;
3539
3540 // Check that the template argument list is well-formed for this
3541 // template.
3542 SmallVector<TemplateArgument, 4> Converted;
3543 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3544 false, Converted))
3545 return true;
3546
Larisse Voufo39a1e502013-08-06 01:03:05 +00003547 // Find the variable template (partial) specialization declaration that
3548 // corresponds to these arguments.
3549 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003550 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3551 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003552 return true;
3553
Richard Smith57aae072016-12-28 02:37:25 +00003554 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3555 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003556 bool InstantiationDependent;
3557 if (!Name.isDependent() &&
3558 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003559 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003560 InstantiationDependent)) {
3561 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3562 << VarTemplate->getDeclName();
3563 IsPartialSpecialization = false;
3564 }
Richard Smith300e0c32013-09-24 04:49:23 +00003565
3566 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3567 Converted)) {
3568 // C++ [temp.class.spec]p9b3:
3569 //
3570 // -- The argument list of the specialization shall not be identical
3571 // to the implicit argument list of the primary template.
3572 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3573 << /*variable template*/ 1
3574 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3575 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3576 // FIXME: Recover from this by treating the declaration as a redeclaration
3577 // of the primary template.
3578 return true;
3579 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003580 }
3581
Craig Topperc3ec1492014-05-26 06:22:03 +00003582 void *InsertPos = nullptr;
3583 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003584
3585 if (IsPartialSpecialization)
3586 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003587 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003588 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003589 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003590
Craig Topperc3ec1492014-05-26 06:22:03 +00003591 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003592
3593 // Check whether we can declare a variable template specialization in
3594 // the current scope.
3595 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3596 TemplateNameLoc,
3597 IsPartialSpecialization))
3598 return true;
3599
3600 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3601 // Since the only prior variable template specialization with these
3602 // arguments was referenced but not declared, reuse that
3603 // declaration node as our own, updating its source location and
3604 // the list of outer template parameters to reflect our new declaration.
3605 Specialization = PrevDecl;
3606 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003607 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003608 } else if (IsPartialSpecialization) {
3609 // Create a new class template partial specialization declaration node.
3610 VarTemplatePartialSpecializationDecl *PrevPartial =
3611 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003612 VarTemplatePartialSpecializationDecl *Partial =
3613 VarTemplatePartialSpecializationDecl::Create(
3614 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3615 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003616 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003617
3618 if (!PrevPartial)
3619 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3620 Specialization = Partial;
3621
3622 // If we are providing an explicit specialization of a member variable
3623 // template specialization, make a note of that.
3624 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003625 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003626
Richard Smith57aae072016-12-28 02:37:25 +00003627 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003628 } else {
3629 // Create a new class template specialization declaration node for
3630 // this explicit specialization or friend declaration.
3631 Specialization = VarTemplateSpecializationDecl::Create(
3632 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003633 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003634 Specialization->setTemplateArgsInfo(TemplateArgs);
3635
3636 if (!PrevDecl)
3637 VarTemplate->AddSpecialization(Specialization, InsertPos);
3638 }
3639
3640 // C++ [temp.expl.spec]p6:
3641 // If a template, a member template or the member of a class template is
3642 // explicitly specialized then that specialization shall be declared
3643 // before the first use of that specialization that would cause an implicit
3644 // instantiation to take place, in every translation unit in which such a
3645 // use occurs; no diagnostic is required.
3646 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3647 bool Okay = false;
3648 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3649 // Is there any previous explicit specialization declaration?
3650 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3651 Okay = true;
3652 break;
3653 }
3654 }
3655
3656 if (!Okay) {
3657 SourceRange Range(TemplateNameLoc, RAngleLoc);
3658 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3659 << Name << Range;
3660
3661 Diag(PrevDecl->getPointOfInstantiation(),
3662 diag::note_instantiation_required_here)
3663 << (PrevDecl->getTemplateSpecializationKind() !=
3664 TSK_ImplicitInstantiation);
3665 return true;
3666 }
3667 }
3668
3669 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3670 Specialization->setLexicalDeclContext(CurContext);
3671
3672 // Add the specialization into its lexical context, so that it can
3673 // be seen when iterating through the list of declarations in that
3674 // context. However, specializations are not found by name lookup.
3675 CurContext->addDecl(Specialization);
3676
3677 // Note that this is an explicit specialization.
3678 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3679
3680 if (PrevDecl) {
3681 // Check that this isn't a redefinition of this specialization,
3682 // merging with previous declarations.
3683 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00003684 forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003685 PrevSpec.addDecl(PrevDecl);
3686 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003687 } else if (Specialization->isStaticDataMember() &&
3688 Specialization->isOutOfLine()) {
3689 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003690 }
3691
3692 // Link instantiations of static data members back to the template from
3693 // which they were instantiated.
3694 if (Specialization->isStaticDataMember())
3695 Specialization->setInstantiationOfStaticDataMember(
3696 VarTemplate->getTemplatedDecl(),
3697 Specialization->getSpecializationKind());
3698
3699 return Specialization;
3700}
3701
3702namespace {
3703/// \brief A partial specialization whose template arguments have matched
3704/// a given template-id.
3705struct PartialSpecMatchResult {
3706 VarTemplatePartialSpecializationDecl *Partial;
3707 TemplateArgumentList *Args;
3708};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003709} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003710
3711DeclResult
3712Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3713 SourceLocation TemplateNameLoc,
3714 const TemplateArgumentListInfo &TemplateArgs) {
3715 assert(Template && "A variable template id without template?");
3716
3717 // Check that the template argument list is well-formed for this template.
3718 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003719 if (CheckTemplateArgumentList(
3720 Template, TemplateNameLoc,
3721 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003722 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003723 return true;
3724
3725 // Find the variable template specialization declaration that
3726 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003727 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003728 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003729 Converted, InsertPos)) {
3730 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003731 // If we already have a variable template specialization, return it.
3732 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003733 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003734
3735 // This is the first time we have referenced this variable template
3736 // specialization. Create the canonical declaration and add it to
3737 // the set of specializations, based on the closest partial specialization
3738 // that it represents. That is,
3739 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3740 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003741 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003742 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3743 bool AmbiguousPartialSpec = false;
3744 typedef PartialSpecMatchResult MatchResult;
3745 SmallVector<MatchResult, 4> Matched;
3746 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003747 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3748 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003749
3750 // 1. Attempt to find the closest partial specialization that this
3751 // specializes, if any.
3752 // If any of the template arguments is dependent, then this is probably
3753 // a placeholder for an incomplete declarative context; which must be
3754 // complete by instantiation time. Thus, do not search through the partial
3755 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003756 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3757 // Perhaps better after unification of DeduceTemplateArguments() and
3758 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003759 bool InstantiationDependent = false;
3760 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3761 TemplateArgs, InstantiationDependent)) {
3762
3763 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3764 Template->getPartialSpecializations(PartialSpecs);
3765
3766 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3767 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3768 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3769
3770 if (TemplateDeductionResult Result =
3771 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3772 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003773 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003774 FailedCandidates.addCandidate().set(
3775 DeclAccessPair::make(Template, AS_public), Partial,
3776 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003777 (void)Result;
3778 } else {
3779 Matched.push_back(PartialSpecMatchResult());
3780 Matched.back().Partial = Partial;
3781 Matched.back().Args = Info.take();
3782 }
3783 }
3784
Larisse Voufo39a1e502013-08-06 01:03:05 +00003785 if (Matched.size() >= 1) {
3786 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3787 if (Matched.size() == 1) {
3788 // -- If exactly one matching specialization is found, the
3789 // instantiation is generated from that specialization.
3790 // We don't need to do anything for this.
3791 } else {
3792 // -- If more than one matching specialization is found, the
3793 // partial order rules (14.5.4.2) are used to determine
3794 // whether one of the specializations is more specialized
3795 // than the others. If none of the specializations is more
3796 // specialized than all of the other matching
3797 // specializations, then the use of the variable template is
3798 // ambiguous and the program is ill-formed.
3799 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3800 PEnd = Matched.end();
3801 P != PEnd; ++P) {
3802 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3803 PointOfInstantiation) ==
3804 P->Partial)
3805 Best = P;
3806 }
3807
3808 // Determine if the best partial specialization is more specialized than
3809 // the others.
3810 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3811 PEnd = Matched.end();
3812 P != PEnd; ++P) {
3813 if (P != Best && getMoreSpecializedPartialSpecialization(
3814 P->Partial, Best->Partial,
3815 PointOfInstantiation) != Best->Partial) {
3816 AmbiguousPartialSpec = true;
3817 break;
3818 }
3819 }
3820 }
3821
3822 // Instantiate using the best variable template partial specialization.
3823 InstantiationPattern = Best->Partial;
3824 InstantiationArgs = Best->Args;
3825 } else {
3826 // -- If no match is found, the instantiation is generated
3827 // from the primary template.
3828 // InstantiationPattern = Template->getTemplatedDecl();
3829 }
3830 }
3831
Larisse Voufo39a1e502013-08-06 01:03:05 +00003832 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00003833 // Note that we do not instantiate a definition until we see an odr-use
3834 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003835 // FIXME: LateAttrs et al.?
3836 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3837 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3838 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3839 if (!Decl)
3840 return true;
3841
3842 if (AmbiguousPartialSpec) {
3843 // Partial ordering did not produce a clear winner. Complain.
3844 Decl->setInvalidDecl();
3845 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3846 << Decl;
3847
3848 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00003849 for (MatchResult P : Matched)
3850 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3851 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3852 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003853 return true;
3854 }
3855
3856 if (VarTemplatePartialSpecializationDecl *D =
3857 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3858 Decl->setInstantiationOf(D, InstantiationArgs);
3859
Richard Smith6739a102016-05-05 00:56:12 +00003860 checkSpecializationVisibility(TemplateNameLoc, Decl);
3861
Larisse Voufo39a1e502013-08-06 01:03:05 +00003862 assert(Decl && "No variable template specialization?");
3863 return Decl;
3864}
3865
3866ExprResult
3867Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3868 const DeclarationNameInfo &NameInfo,
3869 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3870 const TemplateArgumentListInfo *TemplateArgs) {
3871
3872 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3873 *TemplateArgs);
3874 if (Decl.isInvalid())
3875 return ExprError();
3876
3877 VarDecl *Var = cast<VarDecl>(Decl.get());
3878 if (!Var->getTemplateSpecializationKind())
3879 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3880 NameInfo.getLoc());
3881
3882 // Build an ordinary singleton decl ref.
3883 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003884 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003885}
3886
John McCalldadc5752010-08-24 06:29:42 +00003887ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003888 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003889 LookupResult &R,
3890 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003891 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003892 // FIXME: Can we do any checking at this point? I guess we could check the
3893 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003894 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003895 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003896 // foo<int> could identify a single function unambiguously
3897 // This approach does NOT work, since f<int>(1);
3898 // gets resolved prior to resorting to overload resolution
3899 // i.e., template<class T> void f(double);
3900 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003901
3902 // These should be filtered out by our callers.
3903 assert(!R.empty() && "empty lookup results when building templateid");
3904 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3905
Larisse Voufo39a1e502013-08-06 01:03:05 +00003906 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003907 bool InstantiationDependent;
3908 if (R.getAsSingle<VarTemplateDecl>() &&
3909 !TemplateSpecializationType::anyDependentTemplateArguments(
3910 *TemplateArgs, InstantiationDependent)) {
3911 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3912 R.getAsSingle<VarTemplateDecl>(),
3913 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003914 }
3915
John McCall58cc69d2010-01-27 01:50:18 +00003916 // We don't want lookup warnings at this point.
3917 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003918
John McCalle66edc12009-11-24 19:00:30 +00003919 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003920 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003921 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003922 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003923 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003924 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003925 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003926
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003927 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003928}
3929
John McCalle66edc12009-11-24 19:00:30 +00003930// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003931ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003932Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003933 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003934 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003935 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003936
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003937 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003938 DeclContext *DC;
3939 if (!(DC = computeDeclContext(SS, false)) ||
3940 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003941 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003942 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003943
Douglas Gregor786123d2010-05-21 23:18:07 +00003944 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003945 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003946 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003947 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003948
John McCalle66edc12009-11-24 19:00:30 +00003949 if (R.isAmbiguous())
3950 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951
John McCalle66edc12009-11-24 19:00:30 +00003952 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003953 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3954 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003955 return ExprError();
3956 }
3957
3958 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003959 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003960 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003961 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003962 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3963 return ExprError();
3964 }
3965
Abramo Bagnara7945c982012-01-27 09:46:47 +00003966 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003967}
3968
Douglas Gregorb67535d2009-03-31 00:43:58 +00003969/// \brief Form a dependent template name.
3970///
3971/// This action forms a dependent template name given the template
3972/// name and its (presumably dependent) scope specifier. For
3973/// example, given "MetaFun::template apply", the scope specifier \p
3974/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3975/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003976TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003977 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003978 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003979 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003980 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003981 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00003982 TemplateTy &Result,
3983 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003984 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3985 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003986 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003987 diag::warn_cxx98_compat_template_outside_of_template :
3988 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003989 << FixItHint::CreateRemoval(TemplateKWLoc);
3990
Craig Topperc3ec1492014-05-26 06:22:03 +00003991 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003992 if (SS.isSet())
3993 LookupCtx = computeDeclContext(SS, EnteringContext);
3994 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003995 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003996 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003997 // C++0x [temp.names]p5:
3998 // If a name prefixed by the keyword template is not the name of
3999 // a template, the program is ill-formed. [Note: the keyword
4000 // template may not be applied to non-template members of class
4001 // templates. -end note ] [ Note: as is the case with the
4002 // typename prefix, the template prefix is allowed in cases
4003 // where it is not strictly necessary; i.e., when the
4004 // nested-name-specifier or the expression on the left of the ->
4005 // or . is not dependent on a template-parameter, or the use
4006 // does not appear in the scope of a template. -end note]
4007 //
4008 // Note: C++03 was more strict here, because it banned the use of
4009 // the "template" keyword prior to a template-name that was not a
4010 // dependent name. C++ DR468 relaxed this requirement (the
4011 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00004012 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00004013 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00004014 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00004015 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00004016 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00004017 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
4018 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00004019 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
4020 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00004021 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00004022 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004023 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00004024 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004025 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00004026 << Name.getSourceRange()
4027 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004028 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00004029 } else {
4030 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00004031 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4032 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4033 Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
4034 LookupRD->getIdentifier() == Name.Identifier) {
4035 // C++14 [class.qual]p2:
4036 // In a lookup in which function names are not ignored and the
4037 // nested-name-specifier nominates a class C, if the name specified
4038 // [...] is the injected-class-name of C, [...] the name is instead
4039 // considered to name the constructor
4040 //
4041 // We don't get here if naming the constructor would be valid, so we
4042 // just reject immediately and recover by treating the
4043 // injected-class-name as naming the template.
4044 Diag(Name.getLocStart(),
4045 diag::ext_out_of_line_qualified_id_type_names_constructor)
4046 << Name.Identifier << 0 /*injected-class-name used as template name*/
4047 << 1 /*'template' keyword was used*/;
4048 }
Douglas Gregorbb119652010-06-16 23:00:59 +00004049 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004050 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00004051 }
4052
Aaron Ballman4a979672014-01-03 13:56:08 +00004053 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004054
Douglas Gregor3cf81312009-11-03 23:16:33 +00004055 switch (Name.getKind()) {
4056 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00004058 Name.Identifier));
4059 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004060
Douglas Gregor71395fa2009-11-04 00:56:37 +00004061 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00004062 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00004063 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00004064 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00004065
4066 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00004067 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00004068
Douglas Gregor3cf81312009-11-03 23:16:33 +00004069 default:
4070 break;
4071 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004072
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004073 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00004074 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004075 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00004076 << Name.getSourceRange()
4077 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004078 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004079}
4080
Mike Stump11289f42009-09-09 15:08:12 +00004081bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004082 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004083 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00004084 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00004085 QualType ArgType;
4086 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00004087
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004088 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004089 switch(Arg.getKind()) {
4090 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004091 // C++ [temp.arg.type]p1:
4092 // A template-argument for a template-parameter which is a
4093 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00004094 ArgType = Arg.getAsType();
4095 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004096 break;
4097 case TemplateArgument::Template: {
4098 // We have a template type parameter but the template argument
4099 // is a template without any arguments.
4100 SourceRange SR = AL.getSourceRange();
4101 TemplateName Name = Arg.getAsTemplate();
4102 Diag(SR.getBegin(), diag::err_template_missing_args)
Richard Smith0c062b42017-01-14 02:19:59 +00004103 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004104 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
4105 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004106
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004107 return true;
4108 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004109 case TemplateArgument::Expression: {
4110 // We have a template type parameter but the template argument is an
4111 // expression; see if maybe it is missing the "typename" keyword.
4112 CXXScopeSpec SS;
4113 DeclarationNameInfo NameInfo;
4114
4115 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4116 SS.Adopt(ArgExpr->getQualifierLoc());
4117 NameInfo = ArgExpr->getNameInfo();
4118 } else if (DependentScopeDeclRefExpr *ArgExpr =
4119 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4120 SS.Adopt(ArgExpr->getQualifierLoc());
4121 NameInfo = ArgExpr->getNameInfo();
4122 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4123 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004124 if (ArgExpr->isImplicitAccess()) {
4125 SS.Adopt(ArgExpr->getQualifierLoc());
4126 NameInfo = ArgExpr->getMemberNameInfo();
4127 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004128 }
4129
Reid Kleckner377c1592014-06-10 23:29:48 +00004130 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004131 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4132 LookupParsedName(Result, CurScope, &SS);
4133
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004134 if (Result.getAsSingle<TypeDecl>() ||
4135 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00004136 LookupResult::NotFoundInCurrentInstantiation) {
4137 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004138 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00004139 Diag(Loc, getLangOpts().MSVCCompat
4140 ? diag::ext_ms_template_type_arg_missing_typename
4141 : diag::err_template_arg_must_be_type_suggest)
4142 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004143 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00004144
4145 // Recover by synthesizing a type using the location information that we
4146 // already have.
4147 ArgType =
4148 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4149 TypeLocBuilder TLB;
4150 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4151 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4152 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4153 TL.setNameLoc(NameInfo.getLoc());
4154 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4155
4156 // Overwrite our input TemplateArgumentLoc so that we can recover
4157 // properly.
4158 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4159 TemplateArgumentLocInfo(TSI));
4160
4161 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004162 }
4163 }
4164 // fallthrough
Galina Kistanova3779cb32017-06-07 06:25:05 +00004165 LLVM_FALLTHROUGH;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004166 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004167 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004168 // We have a template type parameter but the template argument
4169 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00004170 SourceRange SR = AL.getSourceRange();
4171 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004172 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00004173
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004174 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004175 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004176 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004177
Reid Kleckner377c1592014-06-10 23:29:48 +00004178 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004179 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004180
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004181 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00004182 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004183
Douglas Gregore46db902011-06-17 22:11:49 +00004184 // Objective-C ARC:
4185 // If an explicitly-specified template argument type is a lifetime type
4186 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004187 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00004188 ArgType->isObjCLifetimeType() &&
4189 !ArgType.getObjCLifetime()) {
4190 Qualifiers Qs;
4191 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4192 ArgType = Context.getQualifiedType(ArgType, Qs);
4193 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004194
Douglas Gregore46db902011-06-17 22:11:49 +00004195 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004196 return false;
4197}
4198
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004199/// \brief Substitute template arguments into the default template argument for
4200/// the given template type parameter.
4201///
4202/// \param SemaRef the semantic analysis object for which we are performing
4203/// the substitution.
4204///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004206/// for.
4207///
4208/// \param TemplateLoc the location of the template name that started the
4209/// template-id we are checking.
4210///
4211/// \param RAngleLoc the location of the right angle bracket ('>') that
4212/// terminates the template-id.
4213///
4214/// \param Param the template template parameter whose default we are
4215/// substituting into.
4216///
4217/// \param Converted the list of template arguments provided for template
4218/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004219/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00004220static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004221SubstDefaultTemplateArgument(Sema &SemaRef,
4222 TemplateDecl *Template,
4223 SourceLocation TemplateLoc,
4224 SourceLocation RAngleLoc,
4225 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00004226 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00004227 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004228
4229 // If the argument type is dependent, instantiate it now based
4230 // on the previously-computed template arguments.
4231 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004232 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004233 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004234 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004235 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004236 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004237
David Majnemer8b622692016-07-03 21:17:51 +00004238 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004239
4240 // Only substitute for the innermost template argument list.
4241 MultiLevelTemplateArgumentList TemplateArgLists;
4242 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4243 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4244 TemplateArgLists.addOuterTemplateArguments(None);
4245
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004246 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004247 ArgType =
4248 SemaRef.SubstType(ArgType, TemplateArgLists,
4249 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004250 }
4251
4252 return ArgType;
4253}
4254
4255/// \brief Substitute template arguments into the default template argument for
4256/// the given non-type template parameter.
4257///
4258/// \param SemaRef the semantic analysis object for which we are performing
4259/// the substitution.
4260///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004261/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004262/// for.
4263///
4264/// \param TemplateLoc the location of the template name that started the
4265/// template-id we are checking.
4266///
4267/// \param RAngleLoc the location of the right angle bracket ('>') that
4268/// terminates the template-id.
4269///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004270/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004271/// substituting into.
4272///
4273/// \param Converted the list of template arguments provided for template
4274/// parameters that precede \p Param in the template parameter list.
4275///
4276/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004277static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004278SubstDefaultTemplateArgument(Sema &SemaRef,
4279 TemplateDecl *Template,
4280 SourceLocation TemplateLoc,
4281 SourceLocation RAngleLoc,
4282 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004283 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004284 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004285 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004286 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004287 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004288 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004289
David Majnemer8b622692016-07-03 21:17:51 +00004290 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004291
4292 // Only substitute for the innermost template argument list.
4293 MultiLevelTemplateArgumentList TemplateArgLists;
4294 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4295 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4296 TemplateArgLists.addOuterTemplateArguments(None);
4297
Faisal Valid143a0c2017-04-01 21:30:49 +00004298 EnterExpressionEvaluationContext ConstantEvaluated(
4299 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004300 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004301}
4302
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004303/// \brief Substitute template arguments into the default template argument for
4304/// the given template template parameter.
4305///
4306/// \param SemaRef the semantic analysis object for which we are performing
4307/// the substitution.
4308///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004309/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004310/// for.
4311///
4312/// \param TemplateLoc the location of the template name that started the
4313/// template-id we are checking.
4314///
4315/// \param RAngleLoc the location of the right angle bracket ('>') that
4316/// terminates the template-id.
4317///
4318/// \param Param the template template parameter whose default we are
4319/// substituting into.
4320///
4321/// \param Converted the list of template arguments provided for template
4322/// parameters that precede \p Param in the template parameter list.
4323///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004324/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004325/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004326///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004327/// \returns the substituted template argument, or NULL if an error occurred.
4328static TemplateName
4329SubstDefaultTemplateArgument(Sema &SemaRef,
4330 TemplateDecl *Template,
4331 SourceLocation TemplateLoc,
4332 SourceLocation RAngleLoc,
4333 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004334 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004335 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004336 Sema::InstantiatingTemplate Inst(
4337 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4338 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004339 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004340 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004341
David Majnemer8b622692016-07-03 21:17:51 +00004342 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004343
4344 // Only substitute for the innermost template argument list.
4345 MultiLevelTemplateArgumentList TemplateArgLists;
4346 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4347 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4348 TemplateArgLists.addOuterTemplateArguments(None);
4349
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004350 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004351 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004352 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004353 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004354 QualifierLoc =
4355 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004356 if (!QualifierLoc)
4357 return TemplateName();
4358 }
David Majnemer89189202013-08-28 23:48:32 +00004359
4360 return SemaRef.SubstTemplateName(
4361 QualifierLoc,
4362 Param->getDefaultArgument().getArgument().getAsTemplate(),
4363 Param->getDefaultArgument().getTemplateNameLoc(),
4364 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004365}
4366
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004367/// \brief If the given template parameter has a default template
4368/// argument, substitute into that default template argument and
4369/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004371Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4372 SourceLocation TemplateLoc,
4373 SourceLocation RAngleLoc,
4374 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004375 SmallVectorImpl<TemplateArgument>
4376 &Converted,
4377 bool &HasDefaultArg) {
4378 HasDefaultArg = false;
4379
4380 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004381 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004382 return TemplateArgumentLoc();
4383
Richard Smithc87b9382013-07-04 01:01:24 +00004384 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004385 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004386 TemplateLoc,
4387 RAngleLoc,
4388 TypeParm,
4389 Converted);
4390 if (DI)
4391 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4392
4393 return TemplateArgumentLoc();
4394 }
4395
4396 if (NonTypeTemplateParmDecl *NonTypeParm
4397 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004398 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004399 return TemplateArgumentLoc();
4400
Richard Smithc87b9382013-07-04 01:01:24 +00004401 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004402 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004403 TemplateLoc,
4404 RAngleLoc,
4405 NonTypeParm,
4406 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004407 if (Arg.isInvalid())
4408 return TemplateArgumentLoc();
4409
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004410 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004411 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4412 }
4413
4414 TemplateTemplateParmDecl *TempTempParm
4415 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004416 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004417 return TemplateArgumentLoc();
4418
Richard Smithc87b9382013-07-04 01:01:24 +00004419 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004420 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004421 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004423 RAngleLoc,
4424 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004425 Converted,
4426 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004427 if (TName.isNull())
4428 return TemplateArgumentLoc();
4429
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004430 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004431 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004432 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4433}
4434
Richard Smith11255ec2017-01-18 19:19:22 +00004435/// Convert a template-argument that we parsed as a type into a template, if
4436/// possible. C++ permits injected-class-names to perform dual service as
4437/// template template arguments and as template type arguments.
4438static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4439 // Extract and step over any surrounding nested-name-specifier.
4440 NestedNameSpecifierLoc QualLoc;
4441 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4442 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4443 return TemplateArgumentLoc();
4444
4445 QualLoc = ETLoc.getQualifierLoc();
4446 TLoc = ETLoc.getNamedTypeLoc();
4447 }
4448
4449 // If this type was written as an injected-class-name, it can be used as a
4450 // template template argument.
4451 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4452 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4453 QualLoc, InjLoc.getNameLoc());
4454
4455 // If this type was written as an injected-class-name, it may have been
4456 // converted to a RecordType during instantiation. If the RecordType is
4457 // *not* wrapped in a TemplateSpecializationType and denotes a class
4458 // template specialization, it must have come from an injected-class-name.
4459 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4460 if (auto *CTSD =
4461 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4462 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4463 QualLoc, RecLoc.getNameLoc());
4464
4465 return TemplateArgumentLoc();
4466}
4467
Douglas Gregorda0fb532009-11-11 19:31:23 +00004468/// \brief Check that the given template argument corresponds to the given
4469/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004470///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004471/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004472/// checked.
4473///
Richard Trieu15b66532015-01-24 02:48:32 +00004474/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004475///
4476/// \param Template The template in which the template argument resides.
4477///
4478/// \param TemplateLoc The location of the template name for the template
4479/// whose argument list we're matching.
4480///
4481/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4482/// the template argument list.
4483///
4484/// \param ArgumentPackIndex The index into the argument pack where this
4485/// argument will be placed. Only valid if the parameter is a parameter pack.
4486///
4487/// \param Converted The checked, converted argument will be added to the
4488/// end of this small vector.
4489///
4490/// \param CTAK Describes how we arrived at this particular template argument:
4491/// explicitly written, deduced, etc.
4492///
4493/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004494bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004495 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004496 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004497 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004498 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004499 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004500 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004501 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004502 // Check template type parameters.
4503 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004504 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004505
Douglas Gregoreebed722009-11-11 19:41:09 +00004506 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004507 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004508 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004509 // with the template arguments we've seen thus far. But if the
4510 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004511 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004512 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4513 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004514
Peter Collingbourne01687632010-12-10 17:08:53 +00004515 if (NTTPType->isDependentType() &&
4516 !isa<TemplateTemplateParmDecl>(Template) &&
4517 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004518 // Do substitution on the type of the non-type template parameter.
4519 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004520 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004521 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004522 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004523 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004524
4525 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004526 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004527 NTTPType = SubstType(NTTPType,
4528 MultiLevelTemplateArgumentList(TemplateArgs),
4529 NTTP->getLocation(),
4530 NTTP->getDeclName());
4531 // If that worked, check the non-type template parameter type
4532 // for validity.
4533 if (!NTTPType.isNull())
4534 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4535 NTTP->getLocation());
4536 if (NTTPType.isNull())
4537 return true;
4538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004539
Douglas Gregorda0fb532009-11-11 19:31:23 +00004540 switch (Arg.getArgument().getKind()) {
4541 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004542 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004543
Douglas Gregorda0fb532009-11-11 19:31:23 +00004544 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004545 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00004546 ExprResult Res =
4547 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4548 Result, CTAK);
4549 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004550 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004551
Richard Trieu15b66532015-01-24 02:48:32 +00004552 // If the resulting expression is new, then use it in place of the
4553 // old expression in the template argument.
4554 if (Res.get() != Arg.getArgument().getAsExpr()) {
4555 TemplateArgument TA(Res.get());
4556 Arg = TemplateArgumentLoc(TA, Res.get());
4557 }
4558
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004559 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004560 break;
4561 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004562
Douglas Gregorda0fb532009-11-11 19:31:23 +00004563 case TemplateArgument::Declaration:
4564 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004565 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004566 // We've already checked this template argument, so just copy
4567 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004568 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004569 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004570
Douglas Gregorda0fb532009-11-11 19:31:23 +00004571 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004572 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004573 // We were given a template template argument. It may not be ill-formed;
4574 // see below.
4575 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004576 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4577 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004578 // We have a template argument such as \c T::template X, which we
4579 // parsed as a template template argument. However, since we now
4580 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004581 // template name into an expression.
4582
4583 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4584 Arg.getTemplateNameLoc());
4585
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004586 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004587 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004588 // FIXME: the template-template arg was a DependentTemplateName,
4589 // so it was provided with a template keyword. However, its source
4590 // location is not stored in the template argument structure.
4591 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004592 ExprResult E = DependentScopeDeclRefExpr::Create(
4593 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4594 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004595
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004596 // If we parsed the template argument as a pack expansion, create a
4597 // pack expansion expression.
4598 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004599 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004600 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004601 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004603
Douglas Gregorda0fb532009-11-11 19:31:23 +00004604 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004605 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004606 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004607 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004608
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004609 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004610 break;
4611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004612
Douglas Gregorda0fb532009-11-11 19:31:23 +00004613 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004614 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004615 // therefore cannot be a non-type template argument.
4616 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4617 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004618
Douglas Gregorda0fb532009-11-11 19:31:23 +00004619 Diag(Param->getLocation(), diag::note_template_param_here);
4620 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621
Douglas Gregorda0fb532009-11-11 19:31:23 +00004622 case TemplateArgument::Type: {
4623 // We have a non-type template parameter but the template
4624 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004625
Douglas Gregorda0fb532009-11-11 19:31:23 +00004626 // C++ [temp.arg]p2:
4627 // In a template-argument, an ambiguity between a type-id and
4628 // an expression is resolved to a type-id, regardless of the
4629 // form of the corresponding template-parameter.
4630 //
4631 // We warn specifically about this case, since it can be rather
4632 // confusing for users.
4633 QualType T = Arg.getArgument().getAsType();
4634 SourceRange SR = Arg.getSourceRange();
4635 if (T->isFunctionType())
4636 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4637 else
4638 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4639 Diag(Param->getLocation(), diag::note_template_param_here);
4640 return true;
4641 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004642
Douglas Gregorda0fb532009-11-11 19:31:23 +00004643 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004644 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004646
Douglas Gregorda0fb532009-11-11 19:31:23 +00004647 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004648 }
4649
4650
Douglas Gregorda0fb532009-11-11 19:31:23 +00004651 // Check template template parameters.
4652 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004653
Douglas Gregorda0fb532009-11-11 19:31:23 +00004654 // Substitute into the template parameter list of the template
4655 // template parameter, since previously-supplied template arguments
4656 // may appear within the template template parameter.
4657 {
4658 // Set up a template instantiation context.
4659 LocalInstantiationScope Scope(*this);
4660 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004661 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004662 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004663 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004664 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004665
David Majnemer8b622692016-07-03 21:17:51 +00004666 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004667 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004669 MultiLevelTemplateArgumentList(TemplateArgs)));
4670 if (!TempParm)
4671 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004672 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673
Richard Smith11255ec2017-01-18 19:19:22 +00004674 // C++1z [temp.local]p1: (DR1004)
4675 // When [the injected-class-name] is used [...] as a template-argument for
4676 // a template template-parameter [...] it refers to the class template
4677 // itself.
4678 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4679 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4680 Arg.getTypeSourceInfo()->getTypeLoc());
4681 if (!ConvertedArg.getArgument().isNull())
4682 Arg = ConvertedArg;
4683 }
4684
Douglas Gregorda0fb532009-11-11 19:31:23 +00004685 switch (Arg.getArgument().getKind()) {
4686 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004687 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004688
Douglas Gregorda0fb532009-11-11 19:31:23 +00004689 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004690 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00004691 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004692 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004693
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004694 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004695 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004696
Douglas Gregorda0fb532009-11-11 19:31:23 +00004697 case TemplateArgument::Expression:
4698 case TemplateArgument::Type:
4699 // We have a template template parameter but the template
4700 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004701 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004702 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004703 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004704
Douglas Gregorda0fb532009-11-11 19:31:23 +00004705 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004706 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004707 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004708 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004709 case TemplateArgument::NullPtr:
4710 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004711
Douglas Gregorda0fb532009-11-11 19:31:23 +00004712 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004713 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004715
Douglas Gregorda0fb532009-11-11 19:31:23 +00004716 return false;
4717}
4718
Simon Pilgrim6905d222016-12-30 22:55:33 +00004719/// \brief Diagnose an arity mismatch in the
Douglas Gregor8e072612012-02-03 07:34:46 +00004720static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4721 SourceLocation TemplateLoc,
4722 TemplateArgumentListInfo &TemplateArgs) {
4723 TemplateParameterList *Params = Template->getTemplateParameters();
4724 unsigned NumParams = Params->size();
4725 unsigned NumArgs = TemplateArgs.size();
4726
4727 SourceRange Range;
4728 if (NumArgs > NumParams)
Simon Pilgrim6905d222016-12-30 22:55:33 +00004729 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
Douglas Gregor8e072612012-02-03 07:34:46 +00004730 TemplateArgs.getRAngleLoc());
4731 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4732 << (NumArgs > NumParams)
Richard Smith0c062b42017-01-14 02:19:59 +00004733 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
Douglas Gregor8e072612012-02-03 07:34:46 +00004734 << Template << Range;
4735 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4736 << Params->getSourceRange();
4737 return true;
4738}
4739
Richard Smith1fde8ec2012-09-07 02:06:42 +00004740/// \brief Check whether the template parameter is a pack expansion, and if so,
4741/// determine the number of parameters produced by that expansion. For instance:
4742///
4743/// \code
4744/// template<typename ...Ts> struct A {
4745/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4746/// };
4747/// \endcode
4748///
4749/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4750/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004751static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004752 if (NonTypeTemplateParmDecl *NTTP
4753 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4754 if (NTTP->isExpandedParameterPack())
4755 return NTTP->getNumExpansionTypes();
4756 }
4757
4758 if (TemplateTemplateParmDecl *TTP
4759 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4760 if (TTP->isExpandedParameterPack())
4761 return TTP->getNumExpansionTemplateParameters();
4762 }
4763
David Blaikie7a30dc52013-02-21 01:47:18 +00004764 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00004765}
4766
Richard Smith35c1df52015-06-17 20:16:32 +00004767/// Diagnose a missing template argument.
4768template<typename TemplateParmDecl>
4769static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4770 TemplateDecl *TD,
4771 const TemplateParmDecl *D,
4772 TemplateArgumentListInfo &Args) {
4773 // Dig out the most recent declaration of the template parameter; there may be
4774 // declarations of the template that are more recent than TD.
4775 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4776 ->getTemplateParameters()
4777 ->getParam(D->getIndex()));
4778
4779 // If there's a default argument that's not visible, diagnose that we're
4780 // missing a module import.
4781 llvm::SmallVector<Module*, 8> Modules;
4782 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4783 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4784 D->getDefaultArgumentLoc(), Modules,
4785 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00004786 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00004787 return true;
4788 }
4789
4790 // FIXME: If there's a more recent default argument that *is* visible,
4791 // diagnose that it was declared too late.
4792
4793 return diagnoseArityMismatch(S, TD, Loc, Args);
4794}
4795
Douglas Gregord32e0282009-02-09 23:23:08 +00004796/// \brief Check that the given template argument list is well-formed
4797/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00004798bool Sema::CheckTemplateArgumentList(
4799 TemplateDecl *Template, SourceLocation TemplateLoc,
4800 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4801 SmallVectorImpl<TemplateArgument> &Converted,
4802 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00004803 // Make a copy of the template arguments for processing. Only make the
4804 // changes at the end when successful in matching the arguments to the
4805 // template.
4806 TemplateArgumentListInfo NewArgs = TemplateArgs;
4807
Erich Keaneaf0795b2017-10-24 01:39:56 +00004808 // Make sure we get the template parameter list from the most
4809 // recentdeclaration, since that is the only one that has is guaranteed to
4810 // have all the default template argument information.
4811 TemplateParameterList *Params =
4812 cast<TemplateDecl>(Template->getMostRecentDecl())
4813 ->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00004814
Richard Trieu15b66532015-01-24 02:48:32 +00004815 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00004816
Mike Stump11289f42009-09-09 15:08:12 +00004817 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00004818 // [...] The type and form of each template-argument specified in
4819 // a template-id shall match the type and form specified for the
4820 // corresponding parameter declared by the template in its
4821 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00004822 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004823 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00004824 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00004825 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00004826 for (TemplateParameterList::iterator Param = Params->begin(),
4827 ParamEnd = Params->end();
4828 Param != ParamEnd; /* increment in loop */) {
4829 // If we have an expanded parameter pack, make sure we don't have too
4830 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00004831 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004832 if (*Expansions == ArgumentPack.size()) {
4833 // We're done with this parameter pack. Pack up its arguments and add
4834 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00004835 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00004836 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004837 ArgumentPack.clear();
4838
Richard Smith1fde8ec2012-09-07 02:06:42 +00004839 // This argument is assigned to the next parameter.
4840 ++Param;
4841 continue;
4842 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4843 // Not enough arguments for this parameter pack.
4844 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4845 << false
Richard Smith0c062b42017-01-14 02:19:59 +00004846 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00004847 << Template;
4848 Diag(Template->getLocation(), diag::note_template_decl_here)
4849 << Params->getSourceRange();
4850 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004851 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004853
Richard Smith1fde8ec2012-09-07 02:06:42 +00004854 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00004855 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00004856 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004857 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004858 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00004859 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004860
Richard Smith96d71c32014-11-12 23:38:38 +00004861 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00004862 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00004863 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4864 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00004865 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00004866 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00004867 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00004868 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00004869 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00004870 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00004871 Diag((*Param)->getLocation(), diag::note_template_param_here);
4872 return true;
4873 }
4874
Richard Smith1fde8ec2012-09-07 02:06:42 +00004875 // We're now done with this argument.
4876 ++ArgIdx;
4877
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004878 if ((*Param)->isTemplateParameterPack()) {
4879 // The template parameter was a template parameter pack, so take the
4880 // deduced argument and place it on the argument pack. Note that we
4881 // stay on the same template parameter so that we can deduce more
4882 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004883 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004884 } else {
4885 // Move to the next template parameter.
4886 ++Param;
4887 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004888
Richard Smith96d71c32014-11-12 23:38:38 +00004889 // If we just saw a pack expansion into a non-pack, then directly convert
4890 // the remaining arguments, because we don't know what parameters they'll
4891 // match up with.
4892 if (PackExpansionIntoNonPack) {
4893 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004894 // If we were part way through filling in an expanded parameter pack,
4895 // fall back to just producing individual arguments.
4896 Converted.insert(Converted.end(),
4897 ArgumentPack.begin(), ArgumentPack.end());
4898 ArgumentPack.clear();
4899 }
4900
4901 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00004902 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00004903 ++ArgIdx;
4904 }
4905
Richard Smith1fde8ec2012-09-07 02:06:42 +00004906 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00004907 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004908
Douglas Gregor84d49a22009-11-11 21:54:23 +00004909 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004910 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911
Douglas Gregor2f157c92011-06-03 02:59:40 +00004912 // If we're checking a partial template argument list, we're done.
4913 if (PartialTemplateArgs) {
4914 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00004915 Converted.push_back(
4916 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4917
Richard Smith1fde8ec2012-09-07 02:06:42 +00004918 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00004919 }
4920
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004921 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004922 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00004923 if ((*Param)->isTemplateParameterPack()) {
4924 assert(!getExpandedPackSize(*Param) &&
4925 "Should have dealt with this already");
4926
4927 // A non-expanded parameter pack before the end of the parameter list
4928 // only occurs for an ill-formed template parameter list, unless we've
4929 // got a partial argument list for a function template, so just bail out.
4930 if (Param + 1 != ParamEnd)
4931 return true;
4932
Benjamin Kramercce63472015-08-05 09:40:22 +00004933 Converted.push_back(
4934 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004935 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00004936
4937 ++Param;
4938 continue;
4939 }
4940
Douglas Gregor8e072612012-02-03 07:34:46 +00004941 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00004942 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004943
Douglas Gregor84d49a22009-11-11 21:54:23 +00004944 // Retrieve the default template argument from the template
4945 // parameter. For each kind of template parameter, we substitute the
4946 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004947 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004948 // the default argument.
4949 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004950 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004951 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4952 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004953
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004954 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004955 Template,
4956 TemplateLoc,
4957 RAngleLoc,
4958 TTP,
4959 Converted);
4960 if (!ArgType)
4961 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004962
Douglas Gregor84d49a22009-11-11 21:54:23 +00004963 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4964 ArgType);
4965 } else if (NonTypeTemplateParmDecl *NTTP
4966 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004967 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004968 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4969 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004970
John McCalldadc5752010-08-24 06:29:42 +00004971 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004972 TemplateLoc,
4973 RAngleLoc,
4974 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004975 Converted);
4976 if (E.isInvalid())
4977 return true;
4978
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004979 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004980 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4981 } else {
4982 TemplateTemplateParmDecl *TempParm
4983 = cast<TemplateTemplateParmDecl>(*Param);
4984
Richard Smith95d83952015-06-10 20:36:34 +00004985 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004986 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4987 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004988
Douglas Gregordf846d12011-03-02 18:46:51 +00004989 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004990 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004991 TemplateLoc,
4992 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004993 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004994 Converted,
4995 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004996 if (Name.isNull())
4997 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998
Douglas Gregor9d802122011-03-02 17:09:35 +00004999 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5000 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00005001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005002
Douglas Gregor84d49a22009-11-11 21:54:23 +00005003 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00005004 // the default template argument. We're not actually instantiating a
5005 // template here, we just create this object to put a note into the
5006 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00005007 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5008 SourceRange(TemplateLoc, RAngleLoc));
5009 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005010 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011
Douglas Gregor84d49a22009-11-11 21:54:23 +00005012 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00005013 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005014 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005015 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005016
Richard Trieu15b66532015-01-24 02:48:32 +00005017 // Core issue 150 (assumed resolution): if this is a template template
5018 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00005019 // template definition.
5020 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00005021 NewArgs.addArgument(Arg);
5022
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005023 // Move to the next template parameter and argument.
5024 ++Param;
5025 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00005026 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005027
Richard Smith07f79912014-06-06 16:00:50 +00005028 // If we're performing a partial argument substitution, allow any trailing
5029 // pack expansions; they might be empty. This can happen even if
5030 // PartialTemplateArgs is false (the list of arguments is complete but
5031 // still dependent).
5032 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5033 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00005034 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5035 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00005036 }
5037
Douglas Gregor8e072612012-02-03 07:34:46 +00005038 // If we have any leftover arguments, then there were too many arguments.
5039 // Complain and fail.
5040 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00005041 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
5042
5043 // No problems found with the new argument list, propagate changes back
5044 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00005045 if (UpdateArgsWithConversions)
5046 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005047
Richard Smith1fde8ec2012-09-07 02:06:42 +00005048 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00005049}
5050
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005051namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005052 class UnnamedLocalNoLinkageFinder
5053 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005054 {
5055 Sema &S;
5056 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005057
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005058 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005059
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005060 public:
5061 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5062
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005063 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00005064 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005066
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005067#define TYPE(Class, Parent) \
5068 bool Visit##Class##Type(const Class##Type *);
5069#define ABSTRACT_TYPE(Class, Parent) \
5070 bool Visit##Class##Type(const Class##Type *) { return false; }
5071#define NON_CANONICAL_TYPE(Class, Parent) \
5072 bool Visit##Class##Type(const Class##Type *) { return false; }
5073#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005074
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005075 bool VisitTagDecl(const TagDecl *Tag);
5076 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5077 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005078} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005079
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005080bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005081 return false;
5082}
5083
5084bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5085 return Visit(T->getElementType());
5086}
5087
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005088bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005089 return Visit(T->getPointeeType());
5090}
5091
5092bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005093 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005094 return Visit(T->getPointeeType());
5095}
5096
5097bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005098 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005099 return Visit(T->getPointeeType());
5100}
5101
5102bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005103 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005104 return Visit(T->getPointeeType());
5105}
5106
5107bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005108 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005109 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5110}
5111
5112bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005113 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005114 return Visit(T->getElementType());
5115}
5116
5117bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005118 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005119 return Visit(T->getElementType());
5120}
5121
5122bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005123 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005124 return Visit(T->getElementType());
5125}
5126
5127bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005128 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005129 return Visit(T->getElementType());
5130}
5131
5132bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005133 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005134 return Visit(T->getElementType());
5135}
5136
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005137bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5138 const DependentAddressSpaceType *T) {
5139 return Visit(T->getPointeeType());
5140}
5141
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005142bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5143 return Visit(T->getElementType());
5144}
5145
5146bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5147 return Visit(T->getElementType());
5148}
5149
5150bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5151 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005152 for (const auto &A : T->param_types()) {
5153 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005154 return true;
5155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005156
Alp Toker314cc812014-01-25 16:55:45 +00005157 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005158}
5159
5160bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5161 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00005162 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005163}
5164
5165bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5166 const UnresolvedUsingType*) {
5167 return false;
5168}
5169
5170bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5171 return false;
5172}
5173
5174bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5175 return Visit(T->getUnderlyingType());
5176}
5177
5178bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5179 return false;
5180}
5181
Alexis Hunte852b102011-05-24 22:41:36 +00005182bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5183 const UnaryTransformType*) {
5184 return false;
5185}
5186
Richard Smith30482bc2011-02-20 03:19:35 +00005187bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5188 return Visit(T->getDeducedType());
5189}
5190
Richard Smith600b5262017-01-26 20:40:47 +00005191bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5192 const DeducedTemplateSpecializationType *T) {
5193 return Visit(T->getDeducedType());
5194}
5195
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005196bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5197 return VisitTagDecl(T->getDecl());
5198}
5199
5200bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5201 return VisitTagDecl(T->getDecl());
5202}
5203
5204bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5205 const TemplateTypeParmType*) {
5206 return false;
5207}
5208
Douglas Gregorada4b792011-01-14 02:55:32 +00005209bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5210 const SubstTemplateTypeParmPackType *) {
5211 return false;
5212}
5213
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005214bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5215 const TemplateSpecializationType*) {
5216 return false;
5217}
5218
5219bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5220 const InjectedClassNameType* T) {
5221 return VisitTagDecl(T->getDecl());
5222}
5223
5224bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5225 const DependentNameType* T) {
5226 return VisitNestedNameSpecifier(T->getQualifier());
5227}
5228
5229bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5230 const DependentTemplateSpecializationType* T) {
5231 return VisitNestedNameSpecifier(T->getQualifier());
5232}
5233
Douglas Gregord2fa7662010-12-20 02:24:11 +00005234bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5235 const PackExpansionType* T) {
5236 return Visit(T->getPattern());
5237}
5238
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005239bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5240 return false;
5241}
5242
5243bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5244 const ObjCInterfaceType *) {
5245 return false;
5246}
5247
5248bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5249 const ObjCObjectPointerType *) {
5250 return false;
5251}
5252
Eli Friedman0dfb8892011-10-06 23:00:33 +00005253bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5254 return Visit(T->getValueType());
5255}
5256
Xiuli Pan9c14e282016-01-09 12:53:17 +00005257bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5258 return false;
5259}
5260
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005261bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5262 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005263 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005264 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005265 diag::warn_cxx98_compat_template_arg_local_type :
5266 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005267 << S.Context.getTypeDeclType(Tag) << SR;
5268 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005269 }
5270
John McCall5ea95772013-03-09 00:54:27 +00005271 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005272 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005273 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005274 diag::warn_cxx98_compat_template_arg_unnamed_type :
5275 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005276 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5277 return true;
5278 }
5279
5280 return false;
5281}
5282
5283bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5284 NestedNameSpecifier *NNS) {
5285 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5286 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005287
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005288 switch (NNS->getKind()) {
5289 case NestedNameSpecifier::Identifier:
5290 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005291 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005292 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005293 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005294 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005295
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005296 case NestedNameSpecifier::TypeSpec:
5297 case NestedNameSpecifier::TypeSpecWithTemplate:
5298 return Visit(QualType(NNS->getAsType(), 0));
5299 }
David Blaikie8a40f702012-01-17 06:56:22 +00005300 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005301}
5302
Douglas Gregord32e0282009-02-09 23:23:08 +00005303/// \brief Check a template argument against its corresponding
5304/// template type parameter.
5305///
5306/// This routine implements the semantics of C++ [temp.arg.type]. It
5307/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005308bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005309 TypeSourceInfo *ArgInfo) {
5310 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005311 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005312 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005313
5314 if (Arg->isVariablyModifiedType()) {
5315 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005316 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005317 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005318 }
5319
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005320 // C++03 [temp.arg.type]p2:
5321 // A local type, a type with no linkage, an unnamed type or a type
5322 // compounded from any of these types shall not be used as a
5323 // template-argument for a template type-parameter.
5324 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005325 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005326 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005327 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005328 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5329 (void)Finder.Visit(Context.getCanonicalType(Arg));
5330 }
5331
Douglas Gregord32e0282009-02-09 23:23:08 +00005332 return false;
5333}
5334
Douglas Gregor20fdef32012-04-10 17:08:25 +00005335enum NullPointerValueKind {
5336 NPV_NotNullPointer,
5337 NPV_NullPointer,
5338 NPV_Error
5339};
5340
5341/// \brief Determine whether the given template argument is a null pointer
5342/// value of the appropriate type.
5343static NullPointerValueKind
5344isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
Reid Klecknercd016d82017-07-07 22:04:29 +00005345 QualType ParamType, Expr *Arg,
5346 Decl *Entity = nullptr) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005347 if (Arg->isValueDependent() || Arg->isTypeDependent())
5348 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005349
Reid Klecknercd016d82017-07-07 22:04:29 +00005350 // dllimport'd entities aren't constant but are available inside of template
5351 // arguments.
5352 if (Entity && Entity->hasAttr<DLLImportAttr>())
5353 return NPV_NotNullPointer;
5354
Richard Smithdb0ac552015-12-18 22:40:25 +00005355 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005356 llvm_unreachable(
5357 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005358
David Majnemer5c734ad2014-08-14 00:49:23 +00005359 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005360 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005361
Douglas Gregor20fdef32012-04-10 17:08:25 +00005362 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005363 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5364 if (ArgRV.isInvalid())
5365 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005366 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005367
Douglas Gregor20fdef32012-04-10 17:08:25 +00005368 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005369 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005370 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005371 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005372 EvalResult.HasSideEffects) {
5373 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005374
Douglas Gregor350880c2012-04-10 19:03:30 +00005375 // If our only note is the usual "invalid subexpression" note, just point
5376 // the caret at its location rather than producing an essentially
5377 // redundant note.
5378 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5379 diag::note_invalid_subexpr_in_const_expr) {
5380 DiagLoc = Notes[0].first;
5381 Notes.clear();
5382 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005383
Douglas Gregor350880c2012-04-10 19:03:30 +00005384 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5385 << Arg->getType() << Arg->getSourceRange();
5386 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5387 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005388
Douglas Gregor350880c2012-04-10 19:03:30 +00005389 S.Diag(Param->getLocation(), diag::note_template_param_here);
5390 return NPV_Error;
5391 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005392
Douglas Gregor20fdef32012-04-10 17:08:25 +00005393 // C++11 [temp.arg.nontype]p1:
5394 // - an address constant expression of type std::nullptr_t
5395 if (Arg->getType()->isNullPtrType())
5396 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005397
Douglas Gregor20fdef32012-04-10 17:08:25 +00005398 // - a constant expression that evaluates to a null pointer value (4.10); or
5399 // - a constant expression that evaluates to a null member pointer value
5400 // (4.11); or
5401 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5402 (EvalResult.Val.isMemberPointer() &&
5403 !EvalResult.Val.getMemberPointerDecl())) {
5404 // If our expression has an appropriate type, we've succeeded.
5405 bool ObjCLifetimeConversion;
5406 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5407 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5408 ObjCLifetimeConversion))
5409 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005410
Douglas Gregor20fdef32012-04-10 17:08:25 +00005411 // The types didn't match, but we know we got a null pointer; complain,
5412 // then recover as if the types were correct.
5413 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5414 << Arg->getType() << ParamType << Arg->getSourceRange();
5415 S.Diag(Param->getLocation(), diag::note_template_param_here);
5416 return NPV_NullPointer;
5417 }
5418
5419 // If we don't have a null pointer value, but we do have a NULL pointer
5420 // constant, suggest a cast to the appropriate type.
5421 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5422 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5423 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005424 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5425 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5426 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005427 S.Diag(Param->getLocation(), diag::note_template_param_here);
5428 return NPV_NullPointer;
5429 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005430
Douglas Gregor20fdef32012-04-10 17:08:25 +00005431 // FIXME: If we ever want to support general, address-constant expressions
5432 // as non-type template arguments, we should return the ExprResult here to
5433 // be interpreted by the caller.
5434 return NPV_NotNullPointer;
5435}
5436
David Majnemer61c39a12013-08-23 05:39:39 +00005437/// \brief Checks whether the given template argument is compatible with its
5438/// template parameter.
5439static bool CheckTemplateArgumentIsCompatibleWithParameter(
5440 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5441 Expr *Arg, QualType ArgType) {
5442 bool ObjCLifetimeConversion;
5443 if (ParamType->isPointerType() &&
5444 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5445 S.IsQualificationConversion(ArgType, ParamType, false,
5446 ObjCLifetimeConversion)) {
5447 // For pointer-to-object types, qualification conversions are
5448 // permitted.
5449 } else {
5450 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5451 if (!ParamRef->getPointeeType()->isFunctionType()) {
5452 // C++ [temp.arg.nontype]p5b3:
5453 // For a non-type template-parameter of type reference to
5454 // object, no conversions apply. The type referred to by the
5455 // reference may be more cv-qualified than the (otherwise
5456 // identical) type of the template- argument. The
5457 // template-parameter is bound directly to the
5458 // template-argument, which shall be an lvalue.
5459
5460 // FIXME: Other qualifiers?
5461 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5462 unsigned ArgQuals = ArgType.getCVRQualifiers();
5463
5464 if ((ParamQuals | ArgQuals) != ParamQuals) {
5465 S.Diag(Arg->getLocStart(),
5466 diag::err_template_arg_ref_bind_ignores_quals)
5467 << ParamType << Arg->getType() << Arg->getSourceRange();
5468 S.Diag(Param->getLocation(), diag::note_template_param_here);
5469 return true;
5470 }
5471 }
5472 }
5473
5474 // At this point, the template argument refers to an object or
5475 // function with external linkage. We now need to check whether the
5476 // argument and parameter types are compatible.
5477 if (!S.Context.hasSameUnqualifiedType(ArgType,
5478 ParamType.getNonReferenceType())) {
5479 // We can't perform this conversion or binding.
5480 if (ParamType->isReferenceType())
5481 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5482 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5483 else
5484 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5485 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5486 S.Diag(Param->getLocation(), diag::note_template_param_here);
5487 return true;
5488 }
5489 }
5490
5491 return false;
5492}
5493
Douglas Gregorccb07762009-02-11 19:52:55 +00005494/// \brief Checks whether the given template argument is the address
5495/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005496static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005497CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5498 NonTypeTemplateParmDecl *Param,
5499 QualType ParamType,
5500 Expr *ArgIn,
5501 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005502 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005503 Expr *Arg = ArgIn;
5504 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005505
Douglas Gregorb242683d2010-04-01 18:32:35 +00005506 bool AddressTaken = false;
5507 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005508 if (S.getLangOpts().MicrosoftExt) {
5509 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5510 // dereference and address-of operators.
5511 Arg = Arg->IgnoreParenCasts();
5512
5513 bool ExtWarnMSTemplateArg = false;
5514 UnaryOperatorKind FirstOpKind;
5515 SourceLocation FirstOpLoc;
5516 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5517 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5518 if (UnOpKind == UO_Deref)
5519 ExtWarnMSTemplateArg = true;
5520 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5521 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5522 if (!AddrOpLoc.isValid()) {
5523 FirstOpKind = UnOpKind;
5524 FirstOpLoc = UnOp->getOperatorLoc();
5525 }
5526 } else
5527 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005528 }
David Majnemer61c39a12013-08-23 05:39:39 +00005529 if (FirstOpLoc.isValid()) {
5530 if (ExtWarnMSTemplateArg)
5531 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5532 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005533
David Majnemer61c39a12013-08-23 05:39:39 +00005534 if (FirstOpKind == UO_AddrOf)
5535 AddressTaken = true;
5536 else if (Arg->getType()->isPointerType()) {
5537 // We cannot let pointers get dereferenced here, that is obviously not a
5538 // constant expression.
5539 assert(FirstOpKind == UO_Deref);
5540 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5541 << Arg->getSourceRange();
5542 }
5543 }
5544 } else {
5545 // See through any implicit casts we added to fix the type.
5546 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005547
David Majnemer61c39a12013-08-23 05:39:39 +00005548 // C++ [temp.arg.nontype]p1:
5549 //
5550 // A template-argument for a non-type, non-template
5551 // template-parameter shall be one of: [...]
5552 //
5553 // -- the address of an object or function with external
5554 // linkage, including function templates and function
5555 // template-ids but excluding non-static class members,
5556 // expressed as & id-expression where the & is optional if
5557 // the name refers to a function or array, or if the
5558 // corresponding template-parameter is a reference; or
5559
5560 // In C++98/03 mode, give an extension warning on any extra parentheses.
5561 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5562 bool ExtraParens = false;
5563 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5564 if (!Invalid && !ExtraParens) {
5565 S.Diag(Arg->getLocStart(),
5566 S.getLangOpts().CPlusPlus11
5567 ? diag::warn_cxx98_compat_template_arg_extra_parens
5568 : diag::ext_template_arg_extra_parens)
5569 << Arg->getSourceRange();
5570 ExtraParens = true;
5571 }
5572
5573 Arg = Parens->getSubExpr();
5574 }
5575
5576 while (SubstNonTypeTemplateParmExpr *subst =
5577 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5578 Arg = subst->getReplacement()->IgnoreImpCasts();
5579
5580 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5581 if (UnOp->getOpcode() == UO_AddrOf) {
5582 Arg = UnOp->getSubExpr();
5583 AddressTaken = true;
5584 AddrOpLoc = UnOp->getOperatorLoc();
5585 }
5586 }
5587
5588 while (SubstNonTypeTemplateParmExpr *subst =
5589 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5590 Arg = subst->getReplacement()->IgnoreImpCasts();
5591 }
John McCall7c454bb2011-07-15 05:09:51 +00005592
David Majnemer07910d62014-06-26 07:48:46 +00005593 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5594 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5595
5596 // If our parameter has pointer type, check for a null template value.
5597 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
Reid Klecknercd016d82017-07-07 22:04:29 +00005598 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5599 Entity)) {
David Majnemer07910d62014-06-26 07:48:46 +00005600 case NPV_NullPointer:
5601 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005602 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5603 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005604 return false;
5605
5606 case NPV_Error:
5607 return true;
5608
5609 case NPV_NotNullPointer:
5610 break;
5611 }
5612 }
5613
Chandler Carruth724a8a12010-01-31 10:01:20 +00005614 // Stop checking the precise nature of the argument if it is value dependent,
5615 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005616 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005617 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005618 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005619 }
David Majnemer61c39a12013-08-23 05:39:39 +00005620
5621 if (isa<CXXUuidofExpr>(Arg)) {
5622 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5623 ArgIn, Arg, ArgType))
5624 return true;
5625
5626 Converted = TemplateArgument(ArgIn);
5627 return false;
5628 }
5629
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005630 if (!DRE) {
5631 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5632 << Arg->getSourceRange();
5633 S.Diag(Param->getLocation(), diag::note_template_param_here);
5634 return true;
5635 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00005636
Douglas Gregorccb07762009-02-11 19:52:55 +00005637 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00005638 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005639 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00005640 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005641 S.Diag(Param->getLocation(), diag::note_template_param_here);
5642 return true;
5643 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005644
5645 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00005646 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005647 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005648 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00005649 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005650 S.Diag(Param->getLocation(), diag::note_template_param_here);
5651 return true;
5652 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005653 }
Mike Stump11289f42009-09-09 15:08:12 +00005654
Richard Smith9380e0e2012-04-04 21:11:30 +00005655 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5656 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00005657
Richard Smith9380e0e2012-04-04 21:11:30 +00005658 // A non-type template argument must refer to an object or function.
5659 if (!Func && !Var) {
5660 // We found something, but we don't know specifically what it is.
5661 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5662 << Arg->getSourceRange();
5663 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5664 return true;
5665 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005666
Richard Smith9380e0e2012-04-04 21:11:30 +00005667 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00005668 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005669 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00005670 diag::warn_cxx98_compat_template_arg_object_internal :
5671 diag::ext_template_arg_object_internal)
5672 << !Func << Entity << Arg->getSourceRange();
5673 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5674 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00005675 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005676 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5677 << !Func << Entity << Arg->getSourceRange();
5678 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5679 << !Func;
5680 return true;
5681 }
5682
5683 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005684 // If the template parameter has pointer type, the function decays.
5685 if (ParamType->isPointerType() && !AddressTaken)
5686 ArgType = S.Context.getPointerType(Func->getType());
5687 else if (AddressTaken && ParamType->isReferenceType()) {
5688 // If we originally had an address-of operator, but the
5689 // parameter has reference type, complain and (if things look
5690 // like they will work) drop the address-of operator.
5691 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5692 ParamType.getNonReferenceType())) {
5693 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5694 << ParamType;
5695 S.Diag(Param->getLocation(), diag::note_template_param_here);
5696 return true;
5697 }
5698
5699 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5700 << ParamType
5701 << FixItHint::CreateRemoval(AddrOpLoc);
5702 S.Diag(Param->getLocation(), diag::note_template_param_here);
5703
5704 ArgType = Func->getType();
5705 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005706 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005707 // A value of reference type is not an object.
5708 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005709 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00005710 diag::err_template_arg_reference_var)
5711 << Var->getType() << Arg->getSourceRange();
5712 S.Diag(Param->getLocation(), diag::note_template_param_here);
5713 return true;
5714 }
5715
Richard Smith9380e0e2012-04-04 21:11:30 +00005716 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005717 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005718 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5719 << Arg->getSourceRange();
5720 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5721 return true;
5722 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005723
5724 // If the template parameter has pointer type, we must have taken
5725 // the address of this object.
5726 if (ParamType->isReferenceType()) {
5727 if (AddressTaken) {
5728 // If we originally had an address-of operator, but the
5729 // parameter has reference type, complain and (if things look
5730 // like they will work) drop the address-of operator.
5731 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5732 ParamType.getNonReferenceType())) {
5733 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5734 << ParamType;
5735 S.Diag(Param->getLocation(), diag::note_template_param_here);
5736 return true;
5737 }
5738
5739 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5740 << ParamType
5741 << FixItHint::CreateRemoval(AddrOpLoc);
5742 S.Diag(Param->getLocation(), diag::note_template_param_here);
5743
5744 ArgType = Var->getType();
5745 }
5746 } else if (!AddressTaken && ParamType->isPointerType()) {
5747 if (Var->getType()->isArrayType()) {
5748 // Array-to-pointer decay.
5749 ArgType = S.Context.getArrayDecayedType(Var->getType());
5750 } else {
5751 // If the template parameter has pointer type but the address of
5752 // this object was not taken, complain and (possibly) recover by
5753 // taking the address of the entity.
5754 ArgType = S.Context.getPointerType(Var->getType());
5755 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5756 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5757 << ParamType;
5758 S.Diag(Param->getLocation(), diag::note_template_param_here);
5759 return true;
5760 }
5761
5762 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5763 << ParamType
5764 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5765
5766 S.Diag(Param->getLocation(), diag::note_template_param_here);
5767 }
5768 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005769 }
Mike Stump11289f42009-09-09 15:08:12 +00005770
David Majnemer61c39a12013-08-23 05:39:39 +00005771 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5772 Arg, ArgType))
5773 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005774
5775 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00005776 Converted =
5777 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00005778 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00005779 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005780}
5781
5782/// \brief Checks whether the given template argument is a pointer to
5783/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005784static bool CheckTemplateArgumentPointerToMember(Sema &S,
5785 NonTypeTemplateParmDecl *Param,
5786 QualType ParamType,
5787 Expr *&ResultArg,
5788 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005789 bool Invalid = false;
5790
Douglas Gregor20fdef32012-04-10 17:08:25 +00005791 Expr *Arg = ResultArg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005792 bool ObjCLifetimeConversion;
Douglas Gregorccb07762009-02-11 19:52:55 +00005793
5794 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005795 //
Douglas Gregorccb07762009-02-11 19:52:55 +00005796 // A template-argument for a non-type, non-template
5797 // template-parameter shall be one of: [...]
5798 //
5799 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00005800 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00005801
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005802 // In C++98/03 mode, give an extension warning on any extra parentheses.
5803 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5804 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005805 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005806 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005807 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005808 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00005809 diag::warn_cxx98_compat_template_arg_extra_parens :
5810 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00005811 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005812 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00005813 }
5814
5815 Arg = Parens->getSubExpr();
5816 }
5817
John McCall7c454bb2011-07-15 05:09:51 +00005818 while (SubstNonTypeTemplateParmExpr *subst =
5819 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5820 Arg = subst->getReplacement()->IgnoreImpCasts();
5821
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005822 // A pointer-to-member constant written &Class::member.
5823 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00005824 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005825 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5826 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005827 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005828 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005829 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005830 // A constant of pointer-to-member type.
5831 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5832 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5833 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00005834 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005835 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005836 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005837 } else {
5838 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005839 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005840 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005841 return Invalid;
5842 }
5843 }
5844 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005845
Craig Topperc3ec1492014-05-26 06:22:03 +00005846 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005847 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005848
Reid Klecknercd016d82017-07-07 22:04:29 +00005849 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5850
5851 // Check for a null pointer value.
5852 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
5853 Entity)) {
5854 case NPV_Error:
5855 return true;
5856 case NPV_NullPointer:
5857 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5858 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5859 /*isNullPtr*/true);
5860 return false;
5861 case NPV_NotNullPointer:
5862 break;
5863 }
5864
5865 if (S.IsQualificationConversion(ResultArg->getType(),
5866 ParamType.getNonReferenceType(), false,
5867 ObjCLifetimeConversion)) {
5868 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
5869 ResultArg->getValueKind())
5870 .get();
5871 } else if (!S.Context.hasSameUnqualifiedType(
5872 ResultArg->getType(), ParamType.getNonReferenceType())) {
5873 // We can't perform this conversion.
5874 S.Diag(ResultArg->getLocStart(), diag::err_template_arg_not_convertible)
5875 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
5876 S.Diag(Param->getLocation(), diag::note_template_param_here);
5877 return true;
5878 }
5879
Douglas Gregorccb07762009-02-11 19:52:55 +00005880 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005881 return S.Diag(Arg->getLocStart(),
5882 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00005883 << Arg->getSourceRange();
5884
David Majnemer3ac84e62013-10-22 21:56:38 +00005885 if (isa<FieldDecl>(DRE->getDecl()) ||
5886 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5887 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005888 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00005889 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00005890 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5891 "Only non-static member pointers can make it here");
5892
5893 // Okay: this is the address of a non-static member, and therefore
5894 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00005895 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005896 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005897 } else {
5898 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005899 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005900 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005901 return Invalid;
5902 }
5903
5904 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005905 S.Diag(Arg->getLocStart(),
5906 diag::err_template_arg_not_pointer_to_member_form)
5907 << Arg->getSourceRange();
5908 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00005909 return true;
5910}
5911
Douglas Gregord32e0282009-02-09 23:23:08 +00005912/// \brief Check a template argument against its corresponding
5913/// non-type template parameter.
5914///
Douglas Gregor463421d2009-03-03 04:44:36 +00005915/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00005916/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00005917/// returns the converted template argument. \p ParamType is the
5918/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00005919ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00005920 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00005921 TemplateArgument &Converted,
5922 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005923 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00005924
Richard Smith5f274382016-09-28 23:55:27 +00005925 // If the parameter type somehow involves auto, deduce the type now.
5926 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
Richard Smith4ae5ec82017-02-22 20:01:55 +00005927 // During template argument deduction, we allow 'decltype(auto)' to
5928 // match an arbitrary dependent argument.
5929 // FIXME: The language rules don't say what happens in this case.
5930 // FIXME: We get an opaque dependent type out of decltype(auto) if the
5931 // expression is merely instantiation-dependent; is this enough?
5932 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
5933 auto *AT = dyn_cast<AutoType>(ParamType);
5934 if (AT && AT->isDecltypeAuto()) {
5935 Converted = TemplateArgument(Arg);
5936 return Arg;
5937 }
5938 }
5939
Richard Smith87d263e2016-12-25 08:05:23 +00005940 // When checking a deduced template argument, deduce from its type even if
5941 // the type is dependent, in order to check the types of non-type template
5942 // arguments line up properly in partial ordering.
5943 Optional<unsigned> Depth;
5944 if (CTAK != CTAK_Specified)
5945 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00005946 if (DeduceAutoType(
5947 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00005948 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00005949 Diag(Arg->getExprLoc(),
5950 diag::err_non_type_template_parm_type_deduction_failure)
5951 << Param->getDeclName() << Param->getType() << Arg->getType()
5952 << Arg->getSourceRange();
5953 Diag(Param->getLocation(), diag::note_template_param_here);
5954 return ExprError();
5955 }
5956 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5957 // an error. The error message normally references the parameter
5958 // declaration, but here we'll pass the argument location because that's
5959 // where the parameter type is deduced.
5960 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5961 if (ParamType.isNull()) {
5962 Diag(Param->getLocation(), diag::note_template_param_here);
5963 return ExprError();
5964 }
5965 }
5966
Richard Smithd663fdd2014-12-17 20:42:37 +00005967 // We should have already dropped all cv-qualifiers by now.
5968 assert(!ParamType.hasQualifiers() &&
5969 "non-type template parameter type cannot be qualified");
5970
5971 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00005972 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00005973 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00005974 // FIXME: If either type is dependent, we skip the check. This isn't
5975 // correct, since during deduction we're supposed to have replaced each
5976 // template parameter with some unique (non-dependent) placeholder.
5977 // FIXME: If the argument type contains 'auto', we carry on and fail the
5978 // type check in order to force specific types to be more specialized than
5979 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5980 // work.
5981 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5982 !Arg->getType()->getContainedAutoType()) {
5983 Converted = TemplateArgument(Arg);
5984 return Arg;
5985 }
5986 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5987 // we should actually be checking the type of the template argument in P,
5988 // not the type of the template argument deduced from A, against the
5989 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00005990 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00005991 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00005992 << ParamType.getUnqualifiedType();
5993 Diag(Param->getLocation(), diag::note_template_param_here);
5994 return ExprError();
5995 }
5996
Richard Smith87d263e2016-12-25 08:05:23 +00005997 // If either the parameter has a dependent type or the argument is
5998 // type-dependent, there's nothing we can check now.
5999 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6000 // FIXME: Produce a cloned, canonical expression?
6001 Converted = TemplateArgument(Arg);
6002 return Arg;
6003 }
6004
Richard Smithe5945872017-01-06 22:52:53 +00006005 // The initialization of the parameter from the argument is
6006 // a constant-evaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006007 EnterExpressionEvaluationContext ConstantEvaluated(
6008 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smithe5945872017-01-06 22:52:53 +00006009
Richard Smith410cc892014-11-26 03:26:53 +00006010 if (getLangOpts().CPlusPlus1z) {
Richard Smith410cc892014-11-26 03:26:53 +00006011 // C++1z [temp.arg.nontype]p1:
6012 // A template-argument for a non-type template parameter shall be
6013 // a converted constant expression of the type of the template-parameter.
6014 APValue Value;
6015 ExprResult ArgResult = CheckConvertedConstantExpression(
6016 Arg, ParamType, Value, CCEK_TemplateArg);
6017 if (ArgResult.isInvalid())
6018 return ExprError();
6019
Richard Smith52e624f2016-12-21 21:42:57 +00006020 // For a value-dependent argument, CheckConvertedConstantExpression is
6021 // permitted (and expected) to be unable to determine a value.
6022 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00006023 Converted = TemplateArgument(ArgResult.get());
6024 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00006025 }
6026
Richard Smithd663fdd2014-12-17 20:42:37 +00006027 QualType CanonParamType = Context.getCanonicalType(ParamType);
6028
Richard Smith410cc892014-11-26 03:26:53 +00006029 // Convert the APValue to a TemplateArgument.
6030 switch (Value.getKind()) {
6031 case APValue::Uninitialized:
6032 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006033 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006034 break;
6035 case APValue::Int:
6036 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006037 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00006038 break;
6039 case APValue::MemberPointer: {
6040 assert(ParamType->isMemberPointerType());
6041
6042 // FIXME: We need TemplateArgument representation and mangling for these.
6043 if (!Value.getMemberPointerPath().empty()) {
6044 Diag(Arg->getLocStart(),
6045 diag::err_template_arg_member_ptr_base_derived_not_supported)
6046 << Value.getMemberPointerDecl() << ParamType
6047 << Arg->getSourceRange();
6048 return ExprError();
6049 }
6050
6051 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00006052 Converted = VD ? TemplateArgument(VD, CanonParamType)
6053 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006054 break;
6055 }
6056 case APValue::LValue: {
6057 // For a non-type template-parameter of pointer or reference type,
6058 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00006059 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6060 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00006061 // -- a temporary object
6062 // -- a string literal
6063 // -- the result of a typeid expression, or
Eric Christopher0d2c56a2017-03-31 01:45:39 +00006064 // -- a predefined __func__ variable
Richard Smith410cc892014-11-26 03:26:53 +00006065 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6066 if (isa<CXXUuidofExpr>(E)) {
6067 Converted = TemplateArgument(const_cast<Expr*>(E));
6068 break;
6069 }
6070 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
6071 << Arg->getSourceRange();
6072 return ExprError();
6073 }
6074 auto *VD = const_cast<ValueDecl *>(
6075 Value.getLValueBase().dyn_cast<const ValueDecl *>());
6076 // -- a subobject
6077 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6078 VD && VD->getType()->isArrayType() &&
6079 Value.getLValuePath()[0].ArrayIndex == 0 &&
6080 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6081 // Per defect report (no number yet):
6082 // ... other than a pointer to the first element of a complete array
6083 // object.
6084 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6085 Value.isLValueOnePastTheEnd()) {
6086 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6087 << Value.getAsString(Context, ParamType);
6088 return ExprError();
6089 }
Richard Smithd663fdd2014-12-17 20:42:37 +00006090 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00006091 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00006092 assert((!VD || !ParamType->isNullPtrType()) &&
6093 "non-null value of type nullptr_t?");
6094 Converted = VD ? TemplateArgument(VD, CanonParamType)
6095 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006096 break;
6097 }
6098 case APValue::AddrLabelDiff:
6099 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6100 case APValue::Float:
6101 case APValue::ComplexInt:
6102 case APValue::ComplexFloat:
6103 case APValue::Vector:
6104 case APValue::Array:
6105 case APValue::Struct:
6106 case APValue::Union:
6107 llvm_unreachable("invalid kind for template argument");
6108 }
6109
6110 return ArgResult.get();
6111 }
6112
Douglas Gregor86560402009-02-10 23:36:10 +00006113 // C++ [temp.arg.nontype]p5:
6114 // The following conversions are performed on each expression used
6115 // as a non-type template-argument. If a non-type
6116 // template-argument cannot be converted to the type of the
6117 // corresponding template-parameter then the program is
6118 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00006119 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00006120 // C++11:
6121 // -- for a non-type template-parameter of integral or
6122 // enumeration type, conversions permitted in a converted
6123 // constant expression are applied.
6124 //
6125 // C++98:
6126 // -- for a non-type template-parameter of integral or
6127 // enumeration type, integral promotions (4.5) and integral
6128 // conversions (4.7) are applied.
6129
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006130 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00006131 // C++ [temp.arg.nontype]p1:
6132 // A template-argument for a non-type, non-template template-parameter
6133 // shall be one of:
6134 //
6135 // -- for a non-type template-parameter of integral or enumeration
6136 // type, a converted constant expression of the type of the
6137 // template-parameter; or
6138 llvm::APSInt Value;
6139 ExprResult ArgResult =
6140 CheckConvertedConstantExpression(Arg, ParamType, Value,
6141 CCEK_TemplateArg);
6142 if (ArgResult.isInvalid())
6143 return ExprError();
6144
Richard Smith01bfa682016-12-27 02:02:09 +00006145 // We can't check arbitrary value-dependent arguments.
6146 if (ArgResult.get()->isValueDependent()) {
6147 Converted = TemplateArgument(ArgResult.get());
6148 return ArgResult;
6149 }
6150
Richard Smithf8379a02012-01-18 23:55:52 +00006151 // Widen the argument value to sizeof(parameter type). This is almost
6152 // always a no-op, except when the parameter type is bool. In
6153 // that case, this may extend the argument from 1 bit to 8 bits.
6154 QualType IntegerType = ParamType;
6155 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6156 IntegerType = Enum->getDecl()->getIntegerType();
6157 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6158
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006159 Converted = TemplateArgument(Context, Value,
6160 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00006161 return ArgResult;
6162 }
6163
Richard Smith08b12f12011-10-27 22:11:44 +00006164 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6165 if (ArgResult.isInvalid())
6166 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006167 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00006168
6169 QualType ArgType = Arg->getType();
6170
Douglas Gregor86560402009-02-10 23:36:10 +00006171 // C++ [temp.arg.nontype]p1:
6172 // A template-argument for a non-type, non-template
6173 // template-parameter shall be one of:
6174 //
6175 // -- an integral constant-expression of integral or enumeration
6176 // type; or
6177 // -- the name of a non-type template-parameter; or
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006178 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00006179 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006180 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00006181 diag::err_template_arg_not_integral_or_enumeral)
6182 << ArgType << Arg->getSourceRange();
6183 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006184 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00006185 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00006186 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6187 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006188
Douglas Gregore2b37442012-05-04 22:38:52 +00006189 public:
6190 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00006191
6192 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6193 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00006194 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6195 }
6196 } Diagnoser(ArgType);
6197
6198 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006199 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00006200 if (!Arg)
6201 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006202 }
6203
Richard Smithd663fdd2014-12-17 20:42:37 +00006204 // From here on out, all we care about is the unqualified form
6205 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006206 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00006207
6208 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00006209 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00006210 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00006211 } else if (ParamType->isBooleanType()) {
6212 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006213 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006214 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6215 !ParamType->isEnumeralType()) {
6216 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006217 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006218 } else {
6219 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006220 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00006221 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00006222 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006223 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006224 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006225 }
6226
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006227 // Add the value of this argument to the list of converted
6228 // arguments. We use the bitwidth and signedness of the template
6229 // parameter.
6230 if (Arg->isValueDependent()) {
6231 // The argument is value-dependent. Create a new
6232 // TemplateArgument with the converted expression.
6233 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006234 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006235 }
6236
Douglas Gregor52aba872009-03-14 00:20:21 +00006237 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00006238 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00006239 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00006240
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006241 if (ParamType->isBooleanType()) {
6242 // Value must be zero or one.
6243 Value = Value != 0;
6244 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6245 if (Value.getBitWidth() != AllowedBits)
6246 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006247 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006248 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006249 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006250
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006251 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006252 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006253 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006254 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006255 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006256 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00006257
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006258 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006259 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006260 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006261 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006262 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6263 << Arg->getSourceRange();
6264 Diag(Param->getLocation(), diag::note_template_param_here);
6265 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006266
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006267 // Complain if we overflowed the template parameter's type.
6268 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006269 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006270 RequiredBits = OldValue.getActiveBits();
6271 else if (OldValue.isUnsigned())
6272 RequiredBits = OldValue.getActiveBits() + 1;
6273 else
6274 RequiredBits = OldValue.getMinSignedBits();
6275 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006276 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006277 diag::warn_template_arg_too_large)
6278 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6279 << Arg->getSourceRange();
6280 Diag(Param->getLocation(), diag::note_template_param_here);
6281 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006282 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006283
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006284 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006285 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006286 ? Context.getCanonicalType(ParamType)
6287 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006288 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006289 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006290
Richard Smith08b12f12011-10-27 22:11:44 +00006291 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006292 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6293
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006294 // Handle pointer-to-function, reference-to-function, and
6295 // pointer-to-member-function all in (roughly) the same way.
6296 if (// -- For a non-type template-parameter of type pointer to
6297 // function, only the function-to-pointer conversion (4.3) is
6298 // applied. If the template-argument represents a set of
6299 // overloaded functions (or a pointer to such), the matching
6300 // function is selected from the set (13.4).
6301 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006302 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006303 // -- For a non-type template-parameter of type reference to
6304 // function, no conversions apply. If the template-argument
6305 // represents a set of overloaded functions, the matching
6306 // function is selected from the set (13.4).
6307 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006308 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006309 // -- For a non-type template-parameter of type pointer to
6310 // member function, no conversions apply. If the
6311 // template-argument represents a set of overloaded member
6312 // functions, the matching member function is selected from
6313 // the set (13.4).
6314 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006315 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006316 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006317
Douglas Gregor064fdb22010-04-14 23:11:21 +00006318 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006319 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006320 true,
6321 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006322 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006323 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006324
6325 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6326 ArgType = Arg->getType();
6327 } else
John Wiegley01296292011-04-08 18:41:53 +00006328 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006329 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006330
John Wiegley01296292011-04-08 18:41:53 +00006331 if (!ParamType->isMemberPointerType()) {
6332 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6333 ParamType,
6334 Arg, Converted))
6335 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006336 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006337 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006338
Douglas Gregor20fdef32012-04-10 17:08:25 +00006339 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6340 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006341 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006342 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006343 }
6344
Chris Lattner696197c2009-02-20 21:37:53 +00006345 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006346 // -- for a non-type template-parameter of type pointer to
6347 // object, qualification conversions (4.4) and the
6348 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006349 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006350 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006351 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006352
John Wiegley01296292011-04-08 18:41:53 +00006353 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6354 ParamType,
6355 Arg, Converted))
6356 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006357 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006358 }
Mike Stump11289f42009-09-09 15:08:12 +00006359
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006360 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006361 // -- For a non-type template-parameter of type reference to
6362 // object, no conversions apply. The type referred to by the
6363 // reference may be more cv-qualified than the (otherwise
6364 // identical) type of the template-argument. The
6365 // template-parameter is bound directly to the
6366 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006367 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006368 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006369
Douglas Gregor064fdb22010-04-14 23:11:21 +00006370 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006371 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6372 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006373 true,
6374 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006375 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006376 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006377
6378 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6379 ArgType = Arg->getType();
6380 } else
John Wiegley01296292011-04-08 18:41:53 +00006381 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006382 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006383
John Wiegley01296292011-04-08 18:41:53 +00006384 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6385 ParamType,
6386 Arg, Converted))
6387 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006388 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006389 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006390
Douglas Gregor20fdef32012-04-10 17:08:25 +00006391 // Deal with parameters of type std::nullptr_t.
6392 if (ParamType->isNullPtrType()) {
6393 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6394 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006395 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006396 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006397
Douglas Gregor20fdef32012-04-10 17:08:25 +00006398 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6399 case NPV_NotNullPointer:
6400 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6401 << Arg->getType() << ParamType;
6402 Diag(Param->getLocation(), diag::note_template_param_here);
6403 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006404
Douglas Gregor20fdef32012-04-10 17:08:25 +00006405 case NPV_Error:
6406 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006407
Douglas Gregor20fdef32012-04-10 17:08:25 +00006408 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006409 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006410 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6411 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006412 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006413 }
6414 }
6415
Douglas Gregor0e558532009-02-11 16:16:59 +00006416 // -- For a non-type template-parameter of type pointer to data
6417 // member, qualification conversions (4.4) are applied.
6418 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6419
Douglas Gregor20fdef32012-04-10 17:08:25 +00006420 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6421 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006422 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006423 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006424}
6425
Richard Smith26b86ea2016-12-31 21:41:23 +00006426static void DiagnoseTemplateParameterListArityMismatch(
6427 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6428 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6429
Douglas Gregord32e0282009-02-09 23:23:08 +00006430/// \brief Check a template argument against its corresponding
6431/// template template parameter.
6432///
6433/// This routine implements the semantics of C++ [temp.arg.template].
6434/// It returns true if an error occurred, and false otherwise.
6435bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00006436 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00006437 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006438 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006439 TemplateDecl *Template = Name.getAsTemplateDecl();
6440 if (!Template) {
6441 // Any dependent template name is fine.
6442 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6443 return false;
6444 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006445
Richard Smith26b86ea2016-12-31 21:41:23 +00006446 if (Template->isInvalidDecl())
6447 return true;
6448
Richard Smith3f1b5d02011-05-05 21:57:07 +00006449 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006450 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006451 // the name of a class template or an alias template, expressed as an
6452 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006453 // primary class templates are considered when matching the
6454 // template template argument with the corresponding parameter;
6455 // partial specializations are not considered even if their
6456 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006457 //
6458 // Note that we also allow template template parameters here, which
6459 // will happen when we are dealing with, e.g., class template
6460 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006461 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006462 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006463 !isa<TypeAliasTemplateDecl>(Template) &&
6464 !isa<BuiltinTemplateDecl>(Template)) {
6465 assert(isa<FunctionTemplateDecl>(Template) &&
6466 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006467 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006468 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6469 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006470 }
6471
Richard Smith1fde8ec2012-09-07 02:06:42 +00006472 TemplateParameterList *Params = Param->getTemplateParameters();
6473 if (Param->isExpandedParameterPack())
6474 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6475
Richard Smith26b86ea2016-12-31 21:41:23 +00006476 // C++1z [temp.arg.template]p3: (DR 150)
6477 // A template-argument matches a template template-parameter P when P
6478 // is at least as specialized as the template-argument A.
6479 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6480 // Quick check for the common case:
6481 // If P contains a parameter pack, then A [...] matches P if each of A's
6482 // template parameters matches the corresponding template parameter in
6483 // the template-parameter-list of P.
6484 if (TemplateParameterListsAreEqual(
6485 Template->getTemplateParameters(), Params, false,
6486 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6487 return false;
6488
6489 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6490 Arg.getLocation()))
6491 return false;
6492 // FIXME: Produce better diagnostics for deduction failures.
6493 }
6494
Douglas Gregor85e0f662009-02-10 00:24:35 +00006495 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006496 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006497 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006498 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006499 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006500}
6501
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006502/// \brief Given a non-type template argument that refers to a
6503/// declaration and the type of its corresponding non-type template
6504/// parameter, produce an expression that properly refers to that
6505/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006506ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006507Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6508 QualType ParamType,
6509 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006510 // C++ [temp.param]p8:
6511 //
6512 // A non-type template-parameter of type "array of T" or
6513 // "function returning T" is adjusted to be of type "pointer to
6514 // T" or "pointer to function returning T", respectively.
6515 if (ParamType->isArrayType())
6516 ParamType = Context.getArrayDecayedType(ParamType);
6517 else if (ParamType->isFunctionType())
6518 ParamType = Context.getPointerType(ParamType);
6519
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006520 // For a NULL non-type template argument, return nullptr casted to the
6521 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006522 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006523 return ImpCastExprToType(
6524 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6525 ParamType,
6526 ParamType->getAs<MemberPointerType>()
6527 ? CK_NullToMemberPointer
6528 : CK_NullToPointer);
6529 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006530 assert(Arg.getKind() == TemplateArgument::Declaration &&
6531 "Only declaration template arguments permitted here");
6532
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006533 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6534
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006535 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006536 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6537 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006538 // If the value is a class member, we might have a pointer-to-member.
6539 // Determine whether the non-type template template parameter is of
6540 // pointer-to-member type. If so, we need to build an appropriate
6541 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6542 // would refer to the member itself.
6543 if (ParamType->isMemberPointerType()) {
6544 QualType ClassType
6545 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6546 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006547 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006548 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006549 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006550 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006551
6552 // The actual value-ness of this is unimportant, but for
6553 // internal consistency's sake, references to instance methods
6554 // are r-values.
6555 ExprValueKind VK = VK_LValue;
6556 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6557 VK = VK_RValue;
6558
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006559 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006560 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006561 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006562 Loc,
6563 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006564 if (RefExpr.isInvalid())
6565 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006566
John McCalle3027922010-08-25 11:45:40 +00006567 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006568
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006569 // We might need to perform a trailing qualification conversion, since
6570 // the element type on the parameter could be more qualified than the
6571 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006572 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006573 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006574 ParamType.getUnqualifiedType(), false,
6575 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006576 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006577
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006578 assert(!RefExpr.isInvalid() &&
6579 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006580 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006581 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006582 }
6583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006584
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006585 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006586
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006587 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006588 // When the non-type template parameter is a pointer, take the
6589 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006590 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006591 if (RefExpr.isInvalid())
6592 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006593
Richard Smithfc6fca12017-01-28 00:38:35 +00006594 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6595 (T->isFunctionType() || T->isArrayType())) {
6596 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006597 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006598 if (RefExpr.isInvalid())
6599 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006600
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006601 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006603
Douglas Gregorb242683d2010-04-01 18:32:35 +00006604 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006605 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006606 }
6607
John McCall7decc9e2010-11-18 06:31:45 +00006608 ExprValueKind VK = VK_RValue;
6609
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006610 // If the non-type template parameter has reference type, qualify the
6611 // resulting declaration reference with the extra qualifiers on the
6612 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006613 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6614 VK = VK_LValue;
6615 T = Context.getQualifiedType(T,
6616 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006617 } else if (isa<FunctionDecl>(VD)) {
6618 // References to functions are always lvalues.
6619 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006621
John McCall7decc9e2010-11-18 06:31:45 +00006622 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006623}
6624
6625/// \brief Construct a new expression that refers to the given
6626/// integral template argument with the given source-location
6627/// information.
6628///
6629/// This routine takes care of the mapping from an integral template
6630/// argument (which may have any integral type) to the appropriate
6631/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006632ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006633Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6634 SourceLocation Loc) {
6635 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006636 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006637 QualType OrigT = Arg.getIntegralType();
6638
6639 // If this is an enum type that we're instantiating, we need to use an integer
6640 // type the same size as the enumerator. We don't want to build an
6641 // IntegerLiteral with enum type. The integer type of an enum type can be of
6642 // any integral type with C++11 enum classes, make sure we create the right
6643 // type of literal for it.
6644 QualType T = OrigT;
6645 if (const EnumType *ET = OrigT->getAs<EnumType>())
6646 T = ET->getDecl()->getIntegerType();
6647
6648 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006649 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00006650 // This does not need to handle u8 character literals because those are
6651 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00006652 CharacterLiteral::CharacterKind Kind;
6653 if (T->isWideCharType())
6654 Kind = CharacterLiteral::Wide;
6655 else if (T->isChar16Type())
6656 Kind = CharacterLiteral::UTF16;
6657 else if (T->isChar32Type())
6658 Kind = CharacterLiteral::UTF32;
6659 else
6660 Kind = CharacterLiteral::Ascii;
6661
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006662 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6663 Kind, T, Loc);
6664 } else if (T->isBooleanType()) {
6665 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6666 T, Loc);
6667 } else if (T->isNullPtrType()) {
6668 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6669 } else {
6670 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00006671 }
6672
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006673 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00006674 // FIXME: This is a hack. We need a better way to handle substituted
6675 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00006676 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6677 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006678 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00006679 Loc, Loc);
6680 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006681
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006682 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006683}
6684
Douglas Gregor641040a2011-01-12 23:45:44 +00006685/// \brief Match two template parameters within template parameter lists.
6686static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6687 bool Complain,
6688 Sema::TemplateParameterListEqualKind Kind,
6689 SourceLocation TemplateArgLoc) {
6690 // Check the actual kind (type, non-type, template).
6691 if (Old->getKind() != New->getKind()) {
6692 if (Complain) {
6693 unsigned NextDiag = diag::err_template_param_different_kind;
6694 if (TemplateArgLoc.isValid()) {
6695 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6696 NextDiag = diag::note_template_param_different_kind;
6697 }
6698 S.Diag(New->getLocation(), NextDiag)
6699 << (Kind != Sema::TPL_TemplateMatch);
6700 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6701 << (Kind != Sema::TPL_TemplateMatch);
6702 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006703
Douglas Gregor641040a2011-01-12 23:45:44 +00006704 return false;
6705 }
6706
Richard Smith26b86ea2016-12-31 21:41:23 +00006707 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006708 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006709 // template template parameter, the template template parameter can have
6710 // a parameter pack where the template template argument does not.
6711 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6712 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6713 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006714 if (Complain) {
6715 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6716 if (TemplateArgLoc.isValid()) {
6717 S.Diag(TemplateArgLoc,
6718 diag::err_template_arg_template_params_mismatch);
6719 NextDiag = diag::note_template_parameter_pack_non_pack;
6720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006721
Douglas Gregor641040a2011-01-12 23:45:44 +00006722 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6723 : isa<NonTypeTemplateParmDecl>(New)? 1
6724 : 2;
6725 S.Diag(New->getLocation(), NextDiag)
6726 << ParamKind << New->isParameterPack();
6727 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6728 << ParamKind << Old->isParameterPack();
6729 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006730
Douglas Gregor641040a2011-01-12 23:45:44 +00006731 return false;
6732 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006733
Douglas Gregor641040a2011-01-12 23:45:44 +00006734 // For non-type template parameters, check the type of the parameter.
6735 if (NonTypeTemplateParmDecl *OldNTTP
6736 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6737 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006738
Douglas Gregor641040a2011-01-12 23:45:44 +00006739 // If we are matching a template template argument to a template
6740 // template parameter and one of the non-type template parameter types
Richard Smith13894182017-04-13 21:37:24 +00006741 // is dependent, then we must wait until template instantiation time
6742 // to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00006743 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith13894182017-04-13 21:37:24 +00006744 (OldNTTP->getType()->isDependentType() ||
6745 NewNTTP->getType()->isDependentType()))
Douglas Gregor641040a2011-01-12 23:45:44 +00006746 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006747
Douglas Gregor641040a2011-01-12 23:45:44 +00006748 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6749 if (Complain) {
6750 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6751 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006752 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00006753 diag::err_template_arg_template_params_mismatch);
6754 NextDiag = diag::note_template_nontype_parm_different_type;
6755 }
6756 S.Diag(NewNTTP->getLocation(), NextDiag)
6757 << NewNTTP->getType()
6758 << (Kind != Sema::TPL_TemplateMatch);
6759 S.Diag(OldNTTP->getLocation(),
6760 diag::note_template_nontype_parm_prev_declaration)
6761 << OldNTTP->getType();
6762 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006763
Douglas Gregor641040a2011-01-12 23:45:44 +00006764 return false;
6765 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006766
Douglas Gregor641040a2011-01-12 23:45:44 +00006767 return true;
6768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006769
Douglas Gregor641040a2011-01-12 23:45:44 +00006770 // For template template parameters, check the template parameter types.
6771 // The template parameter lists of template template
6772 // parameters must agree.
6773 if (TemplateTemplateParmDecl *OldTTP
6774 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006775 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00006776 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6777 OldTTP->getTemplateParameters(),
6778 Complain,
6779 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006780 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00006781 : Kind),
6782 TemplateArgLoc);
6783 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006784
Douglas Gregor641040a2011-01-12 23:45:44 +00006785 return true;
6786}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006787
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006788/// \brief Diagnose a known arity mismatch when comparing template argument
6789/// lists.
6790static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006791void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006792 TemplateParameterList *New,
6793 TemplateParameterList *Old,
6794 Sema::TemplateParameterListEqualKind Kind,
6795 SourceLocation TemplateArgLoc) {
6796 unsigned NextDiag = diag::err_template_param_list_different_arity;
6797 if (TemplateArgLoc.isValid()) {
6798 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6799 NextDiag = diag::note_template_param_list_different_arity;
6800 }
6801 S.Diag(New->getTemplateLoc(), NextDiag)
6802 << (New->size() > Old->size())
6803 << (Kind != Sema::TPL_TemplateMatch)
6804 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6805 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6806 << (Kind != Sema::TPL_TemplateMatch)
6807 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6808}
6809
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006810/// \brief Determine whether the given template parameter lists are
6811/// equivalent.
6812///
Mike Stump11289f42009-09-09 15:08:12 +00006813/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006814/// source code as part of a new template declaration.
6815///
6816/// \param Old The old template parameter list, typically found via
6817/// name lookup of the template declared with this template parameter
6818/// list.
6819///
6820/// \param Complain If true, this routine will produce a diagnostic if
6821/// the template parameter lists are not equivalent.
6822///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006823/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00006824///
6825/// \param TemplateArgLoc If this source location is valid, then we
6826/// are actually checking the template parameter list of a template
6827/// argument (New) against the template parameter list of its
6828/// corresponding template template parameter (Old). We produce
6829/// slightly different diagnostics in this scenario.
6830///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006831/// \returns True if the template parameter lists are equal, false
6832/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00006833bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006834Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6835 TemplateParameterList *Old,
6836 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006837 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00006838 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006839 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6840 if (Complain)
6841 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6842 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006843
6844 return false;
6845 }
6846
Douglas Gregor641040a2011-01-12 23:45:44 +00006847 // C++0x [temp.arg.template]p3:
6848 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006849 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00006850 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006851 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006852 // template-parameter-list of P. [...]
6853 TemplateParameterList::iterator NewParm = New->begin();
6854 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006855 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006856 OldParmEnd = Old->end();
6857 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00006858 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6859 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006860 if (NewParm == NewParmEnd) {
6861 if (Complain)
6862 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6863 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006864
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006865 return false;
6866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006867
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006868 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6869 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006870 return false;
6871
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006872 ++NewParm;
6873 continue;
6874 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006875
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006876 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006877 // [...] When P's template- parameter-list contains a template parameter
6878 // pack (14.5.3), the template parameter pack will match zero or more
6879 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006880 // template-parameter-list of A with the same type and form as the
6881 // template parameter pack in P (ignoring whether those template
6882 // parameters are template parameter packs).
6883 for (; NewParm != NewParmEnd; ++NewParm) {
6884 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6885 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006886 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006887 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006888 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006889
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006890 // Make sure we exhausted all of the arguments.
6891 if (NewParm != NewParmEnd) {
6892 if (Complain)
6893 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6894 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006895
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006896 return false;
6897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006898
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006899 return true;
6900}
6901
6902/// \brief Check whether a template can be declared within this scope.
6903///
6904/// If the template declaration is valid in this scope, returns
6905/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00006906bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006907Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00006908 if (!S)
6909 return false;
6910
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006911 // Find the nearest enclosing declaration scope.
6912 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6913 (S->getFlags() & Scope::TemplateParamScope) != 0)
6914 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006915
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006916 // C++ [temp]p4:
6917 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00006918 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00006919 if (Ctx && Ctx->isExternCContext()) {
6920 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6921 << TemplateParams->getSourceRange();
6922 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6923 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6924 return true;
6925 }
Richard Smith8df390f2016-09-08 23:14:54 +00006926 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006927
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006928 // C++ [temp]p2:
6929 // A template-declaration can appear only as a namespace scope or
6930 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00006931 if (Ctx) {
6932 if (Ctx->isFileContext())
6933 return false;
6934 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6935 // C++ [temp.mem]p2:
6936 // A local class shall not have member templates.
6937 if (RD->isLocalClass())
6938 return Diag(TemplateParams->getTemplateLoc(),
6939 diag::err_template_inside_local_class)
6940 << TemplateParams->getSourceRange();
6941 else
6942 return false;
6943 }
6944 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006945
Mike Stump11289f42009-09-09 15:08:12 +00006946 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006947 diag::err_template_outside_namespace_or_class_scope)
6948 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006949}
Douglas Gregor67a65642009-02-17 23:15:12 +00006950
Douglas Gregor54888652009-10-07 00:13:32 +00006951/// \brief Determine what kind of template specialization the given declaration
6952/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006953static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00006954 if (!D)
6955 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006956
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006957 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6958 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00006959 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6960 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006961 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6962 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006963
Douglas Gregor54888652009-10-07 00:13:32 +00006964 return TSK_Undeclared;
6965}
6966
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006968/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00006969///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006970/// This routine determines whether a template specialization can be declared
6971/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00006972///
6973/// \param S the semantic analysis object for which this check is being
6974/// performed.
6975///
6976/// \param Specialized the entity being specialized or instantiated, which
6977/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006978/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00006979/// member class).
6980///
6981/// \param PrevDecl the previous declaration of this entity, if any.
6982///
6983/// \param Loc the location of the explicit specialization or instantiation of
6984/// this entity.
6985///
6986/// \param IsPartialSpecialization whether this is a partial specialization of
6987/// a class template.
6988///
Douglas Gregor54888652009-10-07 00:13:32 +00006989/// \returns true if there was an error that we cannot recover from, false
6990/// otherwise.
6991static bool CheckTemplateSpecializationScope(Sema &S,
6992 NamedDecl *Specialized,
6993 NamedDecl *PrevDecl,
6994 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006995 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00006996 // Keep these "kind" numbers in sync with the %select statements in the
6997 // various diagnostics emitted by this routine.
6998 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006999 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007000 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007001 else if (isa<VarTemplateDecl>(Specialized))
7002 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007003 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007004 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007005 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007006 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007007 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00007008 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007009 else if (isa<RecordDecl>(Specialized))
7010 EntityKind = 7;
7011 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7012 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00007013 else {
Richard Smith7d137e32012-03-23 03:33:32 +00007014 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007015 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007016 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00007017 return true;
7018 }
7019
Douglas Gregorf47b9112009-02-25 22:02:03 +00007020 // C++ [temp.expl.spec]p2:
7021 // An explicit specialization shall be declared in the namespace
7022 // of which the template is a member, or, for member templates, in
7023 // the namespace of which the enclosing class or enclosing class
7024 // template is a member. An explicit specialization of a member
7025 // function, member class or static data member of a class
7026 // template shall be declared in the namespace of which the class
7027 // template is a member. Such a declaration may also be a
7028 // definition. If the declaration is not a definition, the
7029 // specialization may be defined later in the name- space in which
7030 // the explicit specialization was declared, or in a namespace
7031 // that encloses the one in which the explicit specialization was
7032 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00007033 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00007034 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007035 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007036 return true;
7037 }
Douglas Gregore4b05162009-10-07 17:21:34 +00007038
Douglas Gregor40fb7442009-10-07 17:30:37 +00007039 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007040 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007041 // Do not warn for class scope explicit specialization during
7042 // instantiation, warning was already emitted during pattern
7043 // semantic analysis.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007044 if (!S.inTemplateInstantiation())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007045 S.Diag(Loc, diag::ext_function_specialization_in_class)
7046 << Specialized;
7047 } else {
7048 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
7049 << Specialized;
7050 return true;
7051 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00007052 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007053
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00007054 if (S.CurContext->isRecord() &&
7055 !S.CurContext->Equals(Specialized->getDeclContext())) {
7056 // Make sure that we're specializing in the right record context.
7057 // Otherwise, things can go horribly wrong.
7058 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
7059 << Specialized;
7060 return true;
7061 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00007062
Douglas Gregore4b05162009-10-07 17:21:34 +00007063 // C++ [temp.class.spec]p6:
7064 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007065 // in any namespace scope in which its definition may be defined (14.5.1
7066 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00007067 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00007068 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00007069 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00007070
7071 // Make sure that this redeclaration (or definition) occurs in an enclosing
7072 // namespace.
7073 // Note that HandleDeclarator() performs this check for explicit
7074 // specializations of function templates, static data members, and member
7075 // functions, so we skip the check here for those kinds of entities.
7076 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
7077 // Should we refactor that check, so that it occurs later?
7078 if (!DC->Encloses(SpecializedContext) &&
7079 !(isa<FunctionTemplateDecl>(Specialized) ||
7080 isa<FunctionDecl>(Specialized) ||
7081 isa<VarTemplateDecl>(Specialized) ||
7082 isa<VarDecl>(Specialized))) {
7083 if (isa<TranslationUnitDecl>(SpecializedContext))
7084 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7085 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00007086 else if (isa<NamespaceDecl>(SpecializedContext)) {
7087 int Diag = diag::err_template_spec_redecl_out_of_scope;
7088 if (S.getLangOpts().MicrosoftExt)
7089 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7090 S.Diag(Loc, Diag) << EntityKind << Specialized
7091 << cast<NamedDecl>(SpecializedContext);
7092 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00007093 llvm_unreachable("unexpected namespace context for specialization");
7094
7095 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7096 } else if ((!PrevDecl ||
7097 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
7098 getTemplateSpecializationKind(PrevDecl) ==
7099 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00007100 // C++ [temp.exp.spec]p2:
7101 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007102 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00007103 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007104 // An explicit specialization of a member function, member class or
7105 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00007106 // namespace of which the class template is a member.
7107 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00007108 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007109 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00007110 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00007111 // C++11 [temp.explicit]p3:
7112 // An explicit instantiation shall appear in an enclosing namespace of its
7113 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00007114 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007115 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00007116 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007117 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00007118 "DC encloses TU but isn't in enclosing namespace set");
7119 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00007120 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00007121 } else if (isa<NamespaceDecl>(SpecializedContext)) {
7122 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007123 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007124 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007125 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007126 Diag = diag::ext_template_spec_decl_out_of_scope;
7127 else
7128 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
7129 S.Diag(Loc, Diag)
7130 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
7131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007132
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007133 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00007134 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007135 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007136
Douglas Gregorf47b9112009-02-25 22:02:03 +00007137 return false;
7138}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007139
Richard Smith57aae072016-12-28 02:37:25 +00007140static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7141 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00007142 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007143 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007144 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00007145 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007146 return E->getSourceRange();
7147 return Checker.MatchLoc;
7148}
7149
7150static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7151 if (!TL.getType()->isDependentType())
7152 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007153 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007154 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00007155 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007156 return TL.getSourceRange();
7157 return Checker.MatchLoc;
7158}
7159
Larisse Voufo39a1e502013-08-06 01:03:05 +00007160/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007161/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007162static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007163 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7164 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007165 for (unsigned I = 0; I != NumArgs; ++I) {
7166 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007167 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007168 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7169 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007170 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007171
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007172 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007174
Eli Friedmanb826a002012-09-26 02:36:12 +00007175 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007176 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00007177
7178 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007179
Douglas Gregor98318c22011-01-03 21:37:45 +00007180 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007181 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7182 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00007183
7184 // Strip off any implicit casts we added as part of type checking.
7185 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7186 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007187
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007188 // C++ [temp.class.spec]p8:
7189 // A non-type argument is non-specialized if it is the name of a
7190 // non-type parameter. All other non-type arguments are
7191 // specialized.
7192 //
7193 // Below, we check the two conditions that only apply to
7194 // specialized non-type arguments, so skip any non-specialized
7195 // arguments.
7196 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00007197 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007198 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007199
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007200 // C++ [temp.class.spec]p9:
7201 // Within the argument list of a class template partial
7202 // specialization, the following restrictions apply:
7203 // -- A partially specialized non-type argument expression
7204 // shall not involve a template parameter of the partial
7205 // specialization except when the argument expression is a
7206 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00007207 // -- The type of a template parameter corresponding to a
7208 // specialized non-type argument shall not be dependent on a
7209 // parameter of the specialization.
7210 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7211 // We implement a compromise between the original rules and DR1315:
7212 // -- A specialized non-type template argument shall not be
7213 // type-dependent and the corresponding template parameter
7214 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00007215 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00007216 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00007217 if (ParamUseRange.isValid()) {
7218 if (IsDefaultArgument) {
7219 S.Diag(TemplateNameLoc,
7220 diag::err_dependent_non_type_arg_in_partial_spec);
7221 S.Diag(ParamUseRange.getBegin(),
7222 diag::note_dependent_non_type_default_arg_in_partial_spec)
7223 << ParamUseRange;
7224 } else {
7225 S.Diag(ParamUseRange.getBegin(),
7226 diag::err_dependent_non_type_arg_in_partial_spec)
7227 << ParamUseRange;
7228 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007229 return true;
7230 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007231
Richard Smith6056d5e2014-02-09 00:54:43 +00007232 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00007233 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00007234 if (ParamUseRange.isValid()) {
7235 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7236 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Richard Smith57aae072016-12-28 02:37:25 +00007237 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00007238 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00007239 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7240 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007241 return true;
7242 }
7243 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007244
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007245 return false;
7246}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007247
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007248/// \brief Check the non-type template arguments of a class template
7249/// partial specialization according to C++ [temp.class.spec]p9.
7250///
Richard Smith6056d5e2014-02-09 00:54:43 +00007251/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00007252/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00007253/// template.
7254/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00007255/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00007256/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007257///
Richard Smith6056d5e2014-02-09 00:54:43 +00007258/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00007259bool Sema::CheckTemplatePartialSpecializationArgs(
7260 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7261 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7262 // We have to be conservative when checking a template in a dependent
7263 // context.
7264 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7265 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007266
Richard Smith57aae072016-12-28 02:37:25 +00007267 TemplateParameterList *TemplateParams =
7268 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007269 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7270 NonTypeTemplateParmDecl *Param
7271 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7272 if (!Param)
7273 continue;
7274
Richard Smith57aae072016-12-28 02:37:25 +00007275 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7276 Param, &TemplateArgs[I],
7277 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007278 return true;
7279 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007280
7281 return false;
7282}
7283
John McCall48871652010-08-21 09:40:31 +00007284DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00007285Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
7286 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00007287 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007288 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007289 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00007290 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00007291 MultiTemplateParamsArg
7292 TemplateParameterLists,
7293 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007294 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007295
Richard Smith4b55a9c2014-04-17 03:29:33 +00007296 CXXScopeSpec &SS = TemplateId.SS;
7297
Abramo Bagnara60804e12011-03-18 15:16:37 +00007298 // NOTE: KWLoc is the location of the tag keyword. This will instead
7299 // store the location of the outermost template keyword in the declaration.
7300 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007301 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7302 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7303 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7304 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007305
Douglas Gregor67a65642009-02-17 23:15:12 +00007306 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007307 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007308 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007309 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7310
7311 if (!ClassTemplate) {
7312 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007313 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007314 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7315 return true;
7316 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007317
Richard Smithf445f192017-02-09 21:04:43 +00007318 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007319 bool isPartialSpecialization = false;
7320
Douglas Gregorf47b9112009-02-25 22:02:03 +00007321 // Check the validity of the template headers that introduce this
7322 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007323 // FIXME: We probably shouldn't complain about these headers for
7324 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007325 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007326 TemplateParameterList *TemplateParams =
7327 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007328 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007329 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007330 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007331 if (Invalid)
7332 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007333
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007334 if (TemplateParams && TemplateParams->size() > 0) {
7335 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007336
Douglas Gregorec9518b2010-12-21 08:14:57 +00007337 if (TUK == TUK_Friend) {
7338 Diag(KWLoc, diag::err_partial_specialization_friend)
7339 << SourceRange(LAngleLoc, RAngleLoc);
7340 return true;
7341 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007342
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007343 // C++ [temp.class.spec]p10:
7344 // The template parameter list of a specialization shall not
7345 // contain default template argument values.
7346 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7347 Decl *Param = TemplateParams->getParam(I);
7348 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7349 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007350 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007351 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007352 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007353 }
7354 } else if (NonTypeTemplateParmDecl *NTTP
7355 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7356 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007357 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007358 diag::err_default_arg_in_partial_spec)
7359 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007360 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007361 }
7362 } else {
7363 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007364 if (TTP->hasDefaultArgument()) {
7365 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007366 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007367 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007368 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007369 }
7370 }
7371 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007372 } else if (TemplateParams) {
7373 if (TUK == TUK_Friend)
7374 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007375 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007376 SourceRange(TemplateParams->getTemplateLoc(),
7377 TemplateParams->getRAngleLoc()))
7378 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007379 } else {
7380 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007381 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007382
Douglas Gregor67a65642009-02-17 23:15:12 +00007383 // Check that the specialization uses the same tag kind as the
7384 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007385 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7386 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007387 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007388 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007389 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007390 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007391 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007392 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007393 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007394 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007395 diag::note_previous_use);
7396 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7397 }
7398
Douglas Gregorc40290e2009-03-09 23:48:35 +00007399 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007400 TemplateArgumentListInfo TemplateArgs =
7401 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007402
Douglas Gregor14406932011-01-03 20:35:03 +00007403 // Check for unexpanded parameter packs in any of the template arguments.
7404 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007405 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007406 UPPC_PartialSpecialization))
7407 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007408
Douglas Gregor67a65642009-02-17 23:15:12 +00007409 // Check that the template argument list is well-formed for this
7410 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007411 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007412 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7413 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007414 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007415
Douglas Gregor2373c592009-05-31 09:31:02 +00007416 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007417 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007418 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007419 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7420 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007421 return true;
7422
Richard Smith57aae072016-12-28 02:37:25 +00007423 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7424 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007425 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007426 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007427 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007428 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007429 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7430 << ClassTemplate->getDeclName();
7431 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007432 }
7433 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007434
Craig Topperc3ec1492014-05-26 06:22:03 +00007435 void *InsertPos = nullptr;
7436 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007437
7438 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007439 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007440 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007441 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007442 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007443
Craig Topperc3ec1492014-05-26 06:22:03 +00007444 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007445
Douglas Gregorf47b9112009-02-25 22:02:03 +00007446 // Check whether we can declare a class template specialization in
7447 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007448 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007449 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7450 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007451 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007452 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007453
Douglas Gregor15301382009-07-30 17:40:51 +00007454 // The canonical type
7455 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007456 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007457 // Build the canonical type that describes the converted template
7458 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007459 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7460 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007461 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007462
7463 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007464 ClassTemplate->getInjectedClassNameSpecialization())) {
7465 // C++ [temp.class.spec]p9b3:
7466 //
7467 // -- The argument list of the specialization shall not be identical
7468 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007469 //
7470 // This rule has since been removed, because it's redundant given DR1495,
7471 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007472 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007473 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007474 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007475 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7476 ClassTemplate->getIdentifier(),
7477 TemplateNameLoc,
7478 Attr,
7479 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007480 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007481 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007482 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007483 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007484 }
Douglas Gregor15301382009-07-30 17:40:51 +00007485
Douglas Gregor2373c592009-05-31 09:31:02 +00007486 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007487 ClassTemplatePartialSpecializationDecl *PrevPartial
7488 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007489 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007490 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007491 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007492 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007493 TemplateParams,
7494 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007495 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007496 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007497 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007498 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00007499 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007500 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007501 Partial->setTemplateParameterListsInfo(
7502 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007503 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007504
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007505 if (!PrevPartial)
7506 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007507 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007508
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007509 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007510 // template specialization, make a note of that.
7511 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7512 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007513
Richard Smith57aae072016-12-28 02:37:25 +00007514 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007515 } else {
7516 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007517 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007518 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007519 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007520 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007521 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007522 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007523 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007524 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007525 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007526 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007527 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007528 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007529 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007530
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007531 if (!PrevDecl)
7532 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007533
David Majnemer678f50b2015-11-18 19:49:19 +00007534 if (CurContext->isDependentContext()) {
7535 // -fms-extensions permits specialization of nested classes without
7536 // fully specializing the outer class(es).
7537 assert(getLangOpts().MicrosoftExt &&
7538 "Only possible with -fms-extensions!");
7539 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7540 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007541 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007542 } else {
7543 CanonType = Context.getTypeDeclType(Specialization);
7544 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007545 }
7546
Douglas Gregor06db9f52009-10-12 20:18:28 +00007547 // C++ [temp.expl.spec]p6:
7548 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007549 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007550 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007551 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007552 // use occurs; no diagnostic is required.
7553 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007554 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007555 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007556 // Is there any previous explicit specialization declaration?
7557 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7558 Okay = true;
7559 break;
7560 }
7561 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007562
Douglas Gregorc854c662010-02-26 06:03:23 +00007563 if (!Okay) {
7564 SourceRange Range(TemplateNameLoc, RAngleLoc);
7565 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7566 << Context.getTypeDeclType(Specialization) << Range;
7567
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007568 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007569 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007570 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007571 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007572 return true;
7573 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007575
Douglas Gregor2208a292009-09-26 20:57:03 +00007576 // If this is not a friend, note that this is an explicit specialization.
7577 if (TUK != TUK_Friend)
7578 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007579
7580 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007581 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007582 RecordDecl *Def = Specialization->getDefinition();
7583 NamedDecl *Hidden = nullptr;
7584 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7585 SkipBody->ShouldSkip = true;
Richard Smith858e0e02017-05-11 23:11:16 +00007586 makeMergedDefinitionVisible(Hidden);
Richard Smithc7e6ff02015-05-18 20:36:47 +00007587 // From here on out, treat this as just a redeclaration.
7588 TUK = TUK_Declaration;
7589 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007590 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007591 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007592 Diag(Def->getLocation(), diag::note_previous_definition);
7593 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007594 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007595 }
7596 }
7597
John McCall659a3372010-12-18 03:30:47 +00007598 if (Attr)
7599 ProcessDeclAttributeList(S, Specialization, Attr);
7600
Richard Smith034b94a2012-08-17 03:20:55 +00007601 // Add alignment attributes if necessary; these attributes are checked when
7602 // the ASTContext lays out the structure.
7603 if (TUK == TUK_Definition) {
7604 AddAlignmentAttributesForRecord(Specialization);
7605 AddMsStructLayoutForRecord(Specialization);
7606 }
7607
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007608 if (ModulePrivateLoc.isValid())
7609 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7610 << (isPartialSpecialization? 1 : 0)
7611 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007612
Douglas Gregord56a91e2009-02-26 22:19:44 +00007613 // Build the fully-sugared type for this class template
7614 // specialization as the user wrote in the specialization
7615 // itself. This means that we'll pretty-print the type retrieved
7616 // from the specialization's declaration the way that the user
7617 // actually wrote the specialization, rather than formatting the
7618 // name based on the "canonical" representation used to store the
7619 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007620 TypeSourceInfo *WrittenTy
7621 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7622 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007623 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007624 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007625 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007626 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007627
Douglas Gregor1e249f82009-02-25 22:18:32 +00007628 // C++ [temp.expl.spec]p9:
7629 // A template explicit specialization is in the scope of the
7630 // namespace in which the template was defined.
7631 //
7632 // We actually implement this paragraph where we set the semantic
7633 // context (in the creation of the ClassTemplateSpecializationDecl),
7634 // but we also maintain the lexical context where the actual
7635 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007636 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007637
Douglas Gregor67a65642009-02-17 23:15:12 +00007638 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007639 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00007640 Specialization->startDefinition();
7641
Douglas Gregor2208a292009-09-26 20:57:03 +00007642 if (TUK == TUK_Friend) {
7643 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7644 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007645 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007646 /*FIXME:*/KWLoc);
7647 Friend->setAccess(AS_public);
7648 CurContext->addDecl(Friend);
7649 } else {
7650 // Add the specialization into its lexical context, so that it can
7651 // be seen when iterating through the list of declarations in that
7652 // context. However, specializations are not found by name lookup.
7653 CurContext->addDecl(Specialization);
7654 }
John McCall48871652010-08-21 09:40:31 +00007655 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007656}
Douglas Gregor333489b2009-03-27 23:10:48 +00007657
John McCall48871652010-08-21 09:40:31 +00007658Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007659 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007660 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007661 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007662 ActOnDocumentableDecl(NewDecl);
7663 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007664}
7665
John McCall4f7ced62010-02-11 01:33:53 +00007666/// \brief Strips various properties off an implicit instantiation
7667/// that has just been explicitly specialized.
7668static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007669 D->dropAttr<DLLImportAttr>();
7670 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007671
Nico Webere4974382014-12-19 23:52:45 +00007672 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007673 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007674}
7675
Nico Webera8f80b32012-01-09 19:52:25 +00007676/// \brief Compute the diagnostic location for an explicit instantiation
7677// declaration or definition.
7678static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007679 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007680 // Explicit instantiations following a specialization have no effect and
7681 // hence no PointOfInstantiation. In that case, walk decl backwards
7682 // until a valid name loc is found.
7683 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007684 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7685 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007686 PrevDiagLoc = Prev->getLocation();
7687 }
7688 assert(PrevDiagLoc.isValid() &&
7689 "Explicit instantiation without point of instantiation?");
7690 return PrevDiagLoc;
7691}
7692
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007693/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007694/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007695/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007696/// new specialization/instantiation will have any effect.
7697///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007698/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007699/// instantiation.
7700///
7701/// \param NewTSK the kind of the new explicit specialization or instantiation.
7702///
7703/// \param PrevDecl the previous declaration of the entity.
7704///
7705/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7706///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007707/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007708/// declaration was instantiated (either implicitly or explicitly).
7709///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007710/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007711/// specialization or instantiation has no effect and should be ignored.
7712///
7713/// \returns true if there was an error that should prevent the introduction of
7714/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007715bool
7716Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7717 TemplateSpecializationKind NewTSK,
7718 NamedDecl *PrevDecl,
7719 TemplateSpecializationKind PrevTSK,
7720 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007721 bool &HasNoEffect) {
7722 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007723
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007724 switch (NewTSK) {
7725 case TSK_Undeclared:
7726 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007727 assert(
7728 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7729 "previous declaration must be implicit!");
7730 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007731
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007732 case TSK_ExplicitSpecialization:
7733 switch (PrevTSK) {
7734 case TSK_Undeclared:
7735 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007736 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007737 // explicitly specialized or has merely been mentioned without any
7738 // instantiation.
7739 return false;
7740
7741 case TSK_ImplicitInstantiation:
7742 if (PrevPointOfInstantiation.isInvalid()) {
7743 // The declaration itself has not actually been instantiated, so it is
7744 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007745 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007746 return false;
7747 }
7748 // Fall through
Galina Kistanova3779cb32017-06-07 06:25:05 +00007749 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007750
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007751 case TSK_ExplicitInstantiationDeclaration:
7752 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007753 assert((PrevTSK == TSK_ImplicitInstantiation ||
7754 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007755 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007756
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007757 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007758 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007759 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007760 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007761 // implicit instantiation to take place, in every translation unit in
7762 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007763 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007764 // Is there any previous explicit specialization declaration?
7765 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7766 return false;
7767 }
7768
Douglas Gregor1d957a32009-10-27 18:42:08 +00007769 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007770 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007771 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007772 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007773
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007774 return true;
7775 }
Galina Kistanova1d36e832017-06-08 18:20:32 +00007776 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007777
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007778 case TSK_ExplicitInstantiationDeclaration:
7779 switch (PrevTSK) {
7780 case TSK_ExplicitInstantiationDeclaration:
7781 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007782 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007783 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007784
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007785 case TSK_Undeclared:
7786 case TSK_ImplicitInstantiation:
7787 // We're explicitly instantiating something that may have already been
7788 // implicitly instantiated; that's fine.
7789 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007790
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007791 case TSK_ExplicitSpecialization:
7792 // C++0x [temp.explicit]p4:
7793 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007794 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007795 // specialization for that template, the explicit instantiation has no
7796 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007797 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007798 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007799
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007800 case TSK_ExplicitInstantiationDefinition:
7801 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007802 // If an entity is the subject of both an explicit instantiation
7803 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007804 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007805 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007806 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007807
7808 // Explicit instantiations following a specialization have no effect and
7809 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7810 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007811 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7812 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007813 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007814 return false;
7815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007816
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007817 case TSK_ExplicitInstantiationDefinition:
7818 switch (PrevTSK) {
7819 case TSK_Undeclared:
7820 case TSK_ImplicitInstantiation:
7821 // We're explicitly instantiating something that may have already been
7822 // implicitly instantiated; that's fine.
7823 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007824
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007825 case TSK_ExplicitSpecialization:
7826 // C++ DR 259, C++0x [temp.explicit]p4:
7827 // For a given set of template parameters, if an explicit
7828 // instantiation of a template appears after a declaration of
7829 // an explicit specialization for that template, the explicit
7830 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00007831 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007832 << PrevDecl;
7833 Diag(PrevDecl->getLocation(),
7834 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007835 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007836 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007837
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007838 case TSK_ExplicitInstantiationDeclaration:
7839 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007840 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00007841
7842 // C++0x [temp.explicit]p4:
7843 // For a given set of template parameters, if an explicit instantiation
7844 // of a template appears after a declaration of an explicit
7845 // specialization for that template, the explicit instantiation has no
7846 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007847 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00007848 // Is there any previous explicit specialization declaration?
7849 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7850 HasNoEffect = true;
7851 break;
7852 }
7853 }
7854
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007855 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007856
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007857 case TSK_ExplicitInstantiationDefinition:
7858 // C++0x [temp.spec]p5:
7859 // For a given template and a given set of template-arguments,
7860 // - an explicit instantiation definition shall appear at most once
7861 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007862
7863 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7864 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00007865 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007866 : diag::err_explicit_instantiation_duplicate)
7867 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00007868 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00007869 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007870 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007871 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007872 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007874
David Blaikie83d382b2011-09-23 05:06:16 +00007875 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007876}
7877
John McCallb9c78482010-04-08 09:05:18 +00007878/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00007879/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00007880///
James Dennettf14a6e52012-06-15 22:23:43 +00007881/// The only possible way to get a dependent function template specialization
7882/// is with a friend declaration, like so:
7883///
7884/// \code
7885/// template \<class T> void foo(T);
7886/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00007887/// friend void foo<>(T);
7888/// };
James Dennettf14a6e52012-06-15 22:23:43 +00007889/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00007890///
7891/// There really isn't any useful analysis we can do here, so we
7892/// just store the information.
7893bool
7894Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7895 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7896 LookupResult &Previous) {
7897 // Remove anything from Previous that isn't a function template in
7898 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00007899 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00007900 LookupResult::Filter F = Previous.makeFilter();
7901 while (F.hasNext()) {
7902 NamedDecl *D = F.next()->getUnderlyingDecl();
7903 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00007904 !FDLookupContext->InEnclosingNamespaceSetOf(
7905 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00007906 F.erase();
7907 }
7908 F.done();
7909
7910 // Should this be diagnosed here?
7911 if (Previous.empty()) return true;
7912
7913 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7914 ExplicitTemplateArgs);
7915 return false;
7916}
7917
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007918/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007919/// specialization.
7920///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007921/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007922/// explicit function template specialization. On successful completion,
7923/// the function declaration \p FD will become a function template
7924/// specialization.
7925///
7926/// \param FD the function declaration, which will be updated to become a
7927/// function template specialization.
7928///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007929/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7930/// if any. Note that this may be valid info even when 0 arguments are
7931/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7932/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007933///
Francois Pichet3a44e432011-07-08 06:21:47 +00007934/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007935/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007936bool Sema::CheckFunctionTemplateSpecialization(
7937 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7938 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007939 // The set of function template specializations that could match this
7940 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00007941 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007942 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7943 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007944
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007945 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7946 ConvertedTemplateArgs;
7947
Sebastian Redl50c68252010-08-31 00:36:30 +00007948 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00007949 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7950 I != E; ++I) {
7951 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7952 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007953 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007954 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007955 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7956 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007957 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007958
Richard Smith574f4f62013-01-14 05:37:29 +00007959 // When matching a constexpr member function template specialization
7960 // against the primary template, we don't yet know whether the
7961 // specialization has an implicit 'const' (because we don't know whether
7962 // it will be a static member function until we know which template it
7963 // specializes), so adjust it now assuming it specializes this template.
7964 QualType FT = FD->getType();
7965 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007966 CXXMethodDecl *OldMD =
7967 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00007968 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007969 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00007970 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7971 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007972 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007973 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00007974 }
7975 }
7976
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007977 TemplateArgumentListInfo Args;
7978 if (ExplicitTemplateArgs)
7979 Args = *ExplicitTemplateArgs;
7980
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007981 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007982 // A trailing template-argument can be left unspecified in the
7983 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007984 // provided it can be deduced from the function argument type.
7985 // Perform template argument deduction to determine whether we may be
7986 // specializing this template.
7987 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00007988 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007989 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00007990 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7991 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00007992 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7993 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007994 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007995 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00007996 FailedCandidates.addCandidate().set(
7997 I.getPair(), FunTmpl->getTemplatedDecl(),
7998 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007999 (void)TDK;
8000 continue;
8001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008002
Artem Belevich64135c32016-12-08 19:38:13 +00008003 // Target attributes are part of the cuda function signature, so
8004 // the deduced template's cuda target must match that of the
8005 // specialization. Given that C++ template deduction does not
8006 // take target attributes into account, we reject candidates
8007 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008008 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00008009 IdentifyCUDATarget(Specialization,
8010 /* IgnoreImplicitHDAttributes = */ true) !=
8011 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008012 FailedCandidates.addCandidate().set(
8013 I.getPair(), FunTmpl->getTemplatedDecl(),
8014 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8015 continue;
8016 }
8017
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008018 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008019 if (ExplicitTemplateArgs)
8020 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00008021 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008022 }
8023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008024
Douglas Gregor5de279c2009-09-26 03:41:46 +00008025 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008026 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008027 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008028 FD->getLocation(),
8029 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8030 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00008031 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008032 PDiag(diag::note_function_template_spec_matched));
8033
John McCall58cc69d2010-01-27 01:50:18 +00008034 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008035 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008036
8037 // Ignore access information; it doesn't figure into redeclaration checking.
8038 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00008039
Nathan Wilson83839122016-04-09 02:55:27 +00008040 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
8041 // an explicit specialization (14.8.3) [...] of a concept definition.
8042 if (Specialization->getPrimaryTemplate()->isConcept()) {
8043 Diag(FD->getLocation(), diag::err_concept_specialized)
8044 << 0 /*function*/ << 1 /*explicitly specialized*/;
8045 Diag(Specialization->getLocation(), diag::note_previous_declaration);
8046 return true;
8047 }
8048
Abramo Bagnarab9893d62011-03-04 17:20:30 +00008049 FunctionTemplateSpecializationInfo *SpecInfo
8050 = Specialization->getTemplateSpecializationInfo();
8051 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00008052
8053 // Note: do not overwrite location info if previous template
8054 // specialization kind was explicit.
8055 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00008056 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00008057 Specialization->setLocation(FD->getLocation());
Richard Smith54f04402017-05-18 02:29:20 +00008058 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
Richard Smith5b8b3db2012-02-20 23:28:05 +00008059 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8060 // function can differ from the template declaration with respect to
8061 // the constexpr specifier.
Richard Smith77e9e842017-05-09 23:02:10 +00008062 // FIXME: We need an update record for this AST mutation.
8063 // FIXME: What if there are multiple such prior declarations (for instance,
8064 // from different modules)?
Richard Smith5b8b3db2012-02-20 23:28:05 +00008065 Specialization->setConstexpr(FD->isConstexpr());
8066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008067
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008068 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00008069 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00008070
8071 // If this is a friend declaration, then we're not really declaring
8072 // an explicit specialization.
8073 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008074
Douglas Gregor54888652009-10-07 00:13:32 +00008075 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00008076 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008077 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00008078 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008079 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008080 false))
Douglas Gregor54888652009-10-07 00:13:32 +00008081 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008082
8083 // C++ [temp.expl.spec]p6:
8084 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008085 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008086 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008087 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008088 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008089 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00008090 if (!isFriend &&
8091 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00008092 TSK_ExplicitSpecialization,
8093 Specialization,
8094 SpecInfo->getTemplateSpecializationKind(),
8095 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008096 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008097 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008098
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008099 // Mark the prior declaration as an explicit specialization, so that later
8100 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008101 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00008102 // Since explicit specializations do not inherit '=delete' from their
8103 // primary function template - check if the 'specialization' that was
8104 // implicitly generated (during template argument deduction for partial
8105 // ordering) from the most specialized of all the function templates that
8106 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8107 // first check that it was implicitly generated during template argument
8108 // deduction by making sure it wasn't referenced, and then reset the deleted
8109 // flag to not-deleted, so that we can inherit that information from 'FD'.
8110 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8111 !Specialization->getCanonicalDecl()->isReferenced()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008112 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali81a88be2016-06-14 03:23:15 +00008113 assert(
8114 Specialization->getCanonicalDecl() == Specialization &&
8115 "This must be the only existing declaration of this specialization");
Richard Smith77e9e842017-05-09 23:02:10 +00008116 // FIXME: We need an update record for this AST mutation.
Faisal Vali81a88be2016-06-14 03:23:15 +00008117 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008118 }
Richard Smith54f04402017-05-18 02:29:20 +00008119 // FIXME: We need an update record for this AST mutation.
John McCall816d75b2010-03-24 07:46:06 +00008120 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008121 MarkUnusedFileScopedDecl(Specialization);
8122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008123
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008124 // Turn the given function declaration into a function template
8125 // specialization, with the template arguments from the previous
8126 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008127 // Take copies of (semantic and syntactic) template argument lists.
8128 const TemplateArgumentList* TemplArgs = new (Context)
8129 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008130 FD->setFunctionTemplateSpecialization(
8131 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8132 SpecInfo->getTemplateSpecializationKind(),
8133 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008134
Artem Belevich64135c32016-12-08 19:38:13 +00008135 // A function template specialization inherits the target attributes
8136 // of its template. (We require the attributes explicitly in the
8137 // code to match, but a template may have implicit attributes by
8138 // virtue e.g. of being constexpr, and it passes these implicit
8139 // attributes on to its specializations.)
8140 if (LangOpts.CUDA)
8141 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8142
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008143 // The "previous declaration" for this function template specialization is
8144 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00008145 Previous.clear();
8146 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008147 return false;
8148}
8149
Douglas Gregor86d142a2009-10-08 07:24:58 +00008150/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008151/// specialization.
8152///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008153/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008154/// explicit member function specialization. On successful completion,
8155/// the function declaration \p FD will become a member function
8156/// specialization.
8157///
Douglas Gregor86d142a2009-10-08 07:24:58 +00008158/// \param Member the member declaration, which will be updated to become a
8159/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008160///
John McCall1f82f242009-11-18 22:49:29 +00008161/// \param Previous the set of declarations, one of which may be specialized
8162/// by this function specialization; the set will be modified to contain the
8163/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008164bool
John McCall1f82f242009-11-18 22:49:29 +00008165Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008166 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00008167
Douglas Gregor86d142a2009-10-08 07:24:58 +00008168 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00008169 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00008170 NamedDecl *Instantiation = nullptr;
8171 NamedDecl *InstantiatedFrom = nullptr;
8172 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008173
John McCall1f82f242009-11-18 22:49:29 +00008174 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008175 // Nowhere to look anyway.
8176 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008177 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8178 I != E; ++I) {
8179 NamedDecl *D = (*I)->getUnderlyingDecl();
8180 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00008181 QualType Adjusted = Function->getType();
8182 if (!hasExplicitCallingConv(Adjusted))
8183 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8184 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008185 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008186 Instantiation = Method;
8187 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008188 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008189 break;
8190 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008191 }
8192 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00008193 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008194 VarDecl *PrevVar;
8195 if (Previous.isSingleResult() &&
8196 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00008197 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008198 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008199 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008200 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008201 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008202 }
8203 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008204 CXXRecordDecl *PrevRecord;
8205 if (Previous.isSingleResult() &&
8206 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008207 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008208 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008209 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008210 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008211 }
Richard Smith7d137e32012-03-23 03:33:32 +00008212 } else if (isa<EnumDecl>(Member)) {
8213 EnumDecl *PrevEnum;
8214 if (Previous.isSingleResult() &&
8215 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008216 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00008217 Instantiation = PrevEnum;
8218 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8219 MSInfo = PrevEnum->getMemberSpecializationInfo();
8220 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008221 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008222
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008223 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008224 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008225 // specializations are always out-of-line, the caller will complain about
8226 // this mismatch later.
8227 return false;
8228 }
John McCalle820e5e2010-04-13 20:37:33 +00008229
Richard Smith77e9e842017-05-09 23:02:10 +00008230 // A member specialization in a friend declaration isn't really declaring
8231 // an explicit specialization, just identifying a specific (possibly implicit)
8232 // specialization. Don't change the template specialization kind.
8233 //
8234 // FIXME: Is this really valid? Other compilers reject.
John McCalle820e5e2010-04-13 20:37:33 +00008235 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8236 // Preserve instantiation information.
8237 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8238 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8239 cast<CXXMethodDecl>(InstantiatedFrom),
8240 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8241 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8242 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8243 cast<CXXRecordDecl>(InstantiatedFrom),
8244 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8245 }
8246
8247 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008248 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00008249 return false;
8250 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008251
Douglas Gregor86d142a2009-10-08 07:24:58 +00008252 // Make sure that this is a specialization of a member.
8253 if (!InstantiatedFrom) {
8254 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8255 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008256 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8257 return true;
8258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008259
Douglas Gregor06db9f52009-10-12 20:18:28 +00008260 // C++ [temp.expl.spec]p6:
8261 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00008262 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008263 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008264 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008265 // use occurs; no diagnostic is required.
8266 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00008267
Abramo Bagnara8075c852010-06-12 07:44:57 +00008268 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00008269 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8270 TSK_ExplicitSpecialization,
8271 Instantiation,
8272 MSInfo->getTemplateSpecializationKind(),
8273 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008274 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008275 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008276
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008277 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008278 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008279 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008280 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008281 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008282 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008283
Richard Smith77e9e842017-05-09 23:02:10 +00008284 // Note that this member specialization is an "instantiation of" the
8285 // corresponding member of the original template.
8286 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008287 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8288 if (InstantiationFunction->getTemplateSpecializationKind() ==
8289 TSK_ImplicitInstantiation) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008290 // Explicit specializations of member functions of class templates do not
8291 // inherit '=delete' from the member function they are specializing.
8292 if (InstantiationFunction->isDeleted()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008293 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008294 assert(InstantiationFunction->getCanonicalDecl() ==
8295 InstantiationFunction);
Richard Smith77e9e842017-05-09 23:02:10 +00008296 // FIXME: We need an update record for this AST mutation.
Richard Smith5f274382016-09-28 23:55:27 +00008297 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008298 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008299 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008300
Richard Smith77e9e842017-05-09 23:02:10 +00008301 MemberFunction->setInstantiationOfMemberFunction(
8302 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8303 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8304 MemberVar->setInstantiationOfStaticDataMember(
Larisse Voufo39a1e502013-08-06 01:03:05 +00008305 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008306 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8307 MemberClass->setInstantiationOfMemberClass(
8308 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8309 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8310 MemberEnum->setInstantiationOfMemberEnum(
Richard Smith7d137e32012-03-23 03:33:32 +00008311 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008312 } else {
8313 llvm_unreachable("unknown member specialization kind");
Douglas Gregor86d142a2009-10-08 07:24:58 +00008314 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008315
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008316 // Save the caller the trouble of having to figure out which declaration
8317 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008318 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008319 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008320 return false;
8321}
8322
Richard Smith77e9e842017-05-09 23:02:10 +00008323/// Complete the explicit specialization of a member of a class template by
8324/// updating the instantiated member to be marked as an explicit specialization.
8325///
8326/// \param OrigD The member declaration instantiated from the template.
8327/// \param Loc The location of the explicit specialization of the member.
8328template<typename DeclT>
8329static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8330 SourceLocation Loc) {
8331 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8332 return;
8333
8334 // FIXME: Inform AST mutation listeners of this AST mutation.
8335 // FIXME: If there are multiple in-class declarations of the member (from
8336 // multiple modules, or a declaration and later definition of a member type),
8337 // should we update all of them?
8338 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8339 OrigD->setLocation(Loc);
8340}
8341
8342void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8343 LookupResult &Previous) {
8344 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8345 if (Instantiation == Member)
8346 return;
8347
8348 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8349 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8350 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8351 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8352 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8353 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8354 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8355 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8356 else
8357 llvm_unreachable("unknown member specialization kind");
8358}
8359
Douglas Gregore47f5a72009-10-14 23:41:34 +00008360/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008361///
8362/// \returns true if a serious error occurs, false otherwise.
8363static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008364 SourceLocation InstLoc,
8365 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008366 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8367 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008368
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008369 if (CurContext->isRecord()) {
8370 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8371 << D;
8372 return true;
8373 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008374
Richard Smith050d2612011-10-18 02:28:33 +00008375 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008376 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008377 // template. If the name declared in the explicit instantiation is an
8378 // unqualified name, the explicit instantiation shall appear in the
8379 // namespace where its template is declared or, if that namespace is inline
8380 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008381 //
8382 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008383 if (WasQualifiedName) {
8384 if (CurContext->Encloses(OrigContext))
8385 return false;
8386 } else {
8387 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8388 return false;
8389 }
8390
8391 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8392 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008393 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008394 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008395 diag::err_explicit_instantiation_out_of_scope :
8396 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008397 << D << NS;
8398 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008399 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008400 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008401 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8402 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8403 << D << NS;
8404 } else
8405 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008406 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008407 diag::err_explicit_instantiation_must_be_global :
8408 diag::warn_explicit_instantiation_must_be_global_0x)
8409 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008410 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008411 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008412}
8413
8414/// \brief Determine whether the given scope specifier has a template-id in it.
8415static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8416 if (!SS.isSet())
8417 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008418
Richard Smith050d2612011-10-18 02:28:33 +00008419 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008420 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008421 // or a static data member of a class template specialization, the name of
8422 // the class template specialization in the qualified-id for the member
8423 // name shall be a simple-template-id.
8424 //
8425 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008426 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8427 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008428 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008429 if (isa<TemplateSpecializationType>(T))
8430 return true;
8431
8432 return false;
8433}
8434
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008435/// Make a dllexport or dllimport attr on a class template specialization take
8436/// effect.
8437static void dllExportImportClassTemplateSpecialization(
8438 Sema &S, ClassTemplateSpecializationDecl *Def) {
8439 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8440 assert(A && "dllExportImportClassTemplateSpecialization called "
8441 "on Def without dllexport or dllimport");
8442
8443 // We reject explicit instantiations in class scope, so there should
8444 // never be any delayed exported classes to worry about.
8445 assert(S.DelayedDllExportClasses.empty() &&
8446 "delayed exports present at explicit instantiation");
8447 S.checkClassLevelDLLAttribute(Def);
8448
8449 // Propagate attribute to base class templates.
8450 for (auto &B : Def->bases()) {
8451 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8452 B.getType()->getAsCXXRecordDecl()))
8453 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8454 }
8455
8456 S.referenceDLLExportedClassMethods();
8457}
8458
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008459// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00008460DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008461Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008462 SourceLocation ExternLoc,
8463 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008464 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00008465 SourceLocation KWLoc,
8466 const CXXScopeSpec &SS,
8467 TemplateTy TemplateD,
8468 SourceLocation TemplateNameLoc,
8469 SourceLocation LAngleLoc,
8470 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00008471 SourceLocation RAngleLoc,
8472 AttributeList *Attr) {
8473 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008474 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008475 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008476 // Check that the specialization uses the same tag kind as the
8477 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008478 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8479 assert(Kind != TTK_Enum &&
8480 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008481
Richard Trieu265c3442016-04-05 21:13:54 +00008482 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8483
8484 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008485 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8486 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008487 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008488 return true;
8489 }
8490
Douglas Gregord9034f02009-05-14 16:41:31 +00008491 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008492 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008493 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008494 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008495 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008496 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008497 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008498 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008499 diag::note_previous_use);
8500 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8501 }
8502
Douglas Gregore47f5a72009-10-14 23:41:34 +00008503 // C++0x [temp.explicit]p2:
8504 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008505 // definition and an explicit instantiation declaration. An explicit
8506 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008507 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8508 ? TSK_ExplicitInstantiationDefinition
8509 : TSK_ExplicitInstantiationDeclaration;
8510
8511 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8512 // Check for dllexport class template instantiation declarations.
8513 for (AttributeList *A = Attr; A; A = A->getNext()) {
8514 if (A->getKind() == AttributeList::AT_DLLExport) {
8515 Diag(ExternLoc,
8516 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8517 Diag(A->getLoc(), diag::note_attribute);
8518 break;
8519 }
8520 }
8521
8522 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8523 Diag(ExternLoc,
8524 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8525 Diag(A->getLocation(), diag::note_attribute);
8526 }
8527 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008528
Hans Wennborga86a83b2016-05-26 19:42:56 +00008529 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8530 // instantiation declarations for most purposes.
8531 bool DLLImportExplicitInstantiationDef = false;
8532 if (TSK == TSK_ExplicitInstantiationDefinition &&
8533 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8534 // Check for dllimport class template instantiation definitions.
8535 bool DLLImport =
8536 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8537 for (AttributeList *A = Attr; A; A = A->getNext()) {
8538 if (A->getKind() == AttributeList::AT_DLLImport)
8539 DLLImport = true;
8540 if (A->getKind() == AttributeList::AT_DLLExport) {
8541 // dllexport trumps dllimport here.
8542 DLLImport = false;
8543 break;
8544 }
8545 }
8546 if (DLLImport) {
8547 TSK = TSK_ExplicitInstantiationDeclaration;
8548 DLLImportExplicitInstantiationDef = true;
8549 }
8550 }
8551
Douglas Gregora1f49972009-05-13 00:25:59 +00008552 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008553 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008554 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008555
8556 // Check that the template argument list is well-formed for this
8557 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008558 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008559 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8560 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008561 return true;
8562
Douglas Gregora1f49972009-05-13 00:25:59 +00008563 // Find the class template specialization declaration that
8564 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008565 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008566 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008567 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008568
Abramo Bagnara8075c852010-06-12 07:44:57 +00008569 TemplateSpecializationKind PrevDecl_TSK
8570 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8571
Douglas Gregor54888652009-10-07 00:13:32 +00008572 // C++0x [temp.explicit]p2:
8573 // [...] An explicit instantiation shall appear in an enclosing
8574 // namespace of its template. [...]
8575 //
8576 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008577 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8578 SS.isSet()))
8579 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008580
Craig Topperc3ec1492014-05-26 06:22:03 +00008581 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008582
Abramo Bagnara8075c852010-06-12 07:44:57 +00008583 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008584 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008585 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008586 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008587 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008588 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008589 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008590
Abramo Bagnara8075c852010-06-12 07:44:57 +00008591 // Even though HasNoEffect == true means that this explicit instantiation
8592 // has no effect on semantics, we go on to put its syntax in the AST.
8593
8594 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8595 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008596 // Since the only prior class template specialization with these
8597 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008598 // declaration node as our own, updating the source location
8599 // for the template name to reflect our new declaration.
8600 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008601 Specialization = PrevDecl;
8602 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008603 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008604 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008605
8606 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8607 DLLImportExplicitInstantiationDef) {
8608 // The new specialization might add a dllimport attribute.
8609 HasNoEffect = false;
8610 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008611 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008612
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008613 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008614 // Create a new class template specialization declaration node for
8615 // this explicit specialization.
8616 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008617 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008618 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008619 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008620 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008621 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008622 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00008623 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008624
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008625 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008626 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008627 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008628 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008629 }
8630
8631 // Build the fully-sugared type for this explicit instantiation as
8632 // the user wrote in the explicit instantiation itself. This means
8633 // that we'll pretty-print the type retrieved from the
8634 // specialization's declaration the way that the user actually wrote
8635 // the explicit instantiation, rather than formatting the name based
8636 // on the "canonical" representation used to store the template
8637 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008638 TypeSourceInfo *WrittenTy
8639 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8640 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008641 Context.getTypeDeclType(Specialization));
8642 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008643
Abramo Bagnara8075c852010-06-12 07:44:57 +00008644 // Set source locations for keywords.
8645 Specialization->setExternLoc(ExternLoc);
8646 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008647 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008648
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008649 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Rafael Espindola0b062072012-01-03 06:04:21 +00008650 if (Attr)
8651 ProcessDeclAttributeList(S, Specialization, Attr);
8652
Abramo Bagnara8075c852010-06-12 07:44:57 +00008653 // Add the explicit instantiation into its lexical context. However,
8654 // since explicit instantiations are never found by name lookup, we
8655 // just put it into the declaration context directly.
8656 Specialization->setLexicalDeclContext(CurContext);
8657 CurContext->addDecl(Specialization);
8658
8659 // Syntax is now OK, so return if it has no other effect on semantics.
8660 if (HasNoEffect) {
8661 // Set the template specialization kind.
8662 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008663 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008664 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008665
8666 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008667 // A definition of a class template or class member template
8668 // shall be in scope at the point of the explicit instantiation of
8669 // the class template or class member template.
8670 //
8671 // This check comes when we actually try to perform the
8672 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008673 ClassTemplateSpecializationDecl *Def
8674 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008675 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008676 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00008677 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008678 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008679 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008680 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8681 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008682
Douglas Gregor1d957a32009-10-27 18:42:08 +00008683 // Instantiate the members of this class template specialization.
8684 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008685 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00008686 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008687 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008688 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8689 // TSK_ExplicitInstantiationDefinition
8690 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00008691 (TSK == TSK_ExplicitInstantiationDefinition ||
8692 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00008693 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008694 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008695
Hans Wennborgc0875502015-06-09 00:39:05 +00008696 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00008697 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8698 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00008699 // In the MS ABI, an explicit instantiation definition can add a dll
8700 // attribute to a template with a previous instantiation declaration.
8701 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008702 auto *A = cast<InheritableAttr>(
8703 getDLLAttr(Specialization)->clone(getASTContext()));
8704 A->setInherited(true);
8705 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008706 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008707 }
8708 }
8709
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008710 // Fix a TSK_ImplicitInstantiation followed by a
8711 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008712 bool NewlyDLLExported =
8713 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8714 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008715 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8716 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8717 // In the MS ABI, an explicit instantiation definition can add a dll
8718 // attribute to a template with a previous implicit instantiation.
8719 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8720 // avoid potentially strange codegen behavior. For example, if we extend
8721 // this conditional to dllimport, and we have a source file calling a
8722 // method on an implicitly instantiated template class instance and then
8723 // declaring a dllimport explicit instantiation definition for the same
8724 // template class, the codegen for the method call will not respect the
8725 // dllimport, while it will with cl. The Def will already have the DLL
8726 // attribute, since the Def and Specialization will be the same in the
8727 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8728 // attribute to the Specialization; we just need to make it take effect.
8729 assert(Def == Specialization &&
8730 "Def and Specialization should match for implicit instantiation");
8731 dllExportImportClassTemplateSpecialization(*this, Def);
8732 }
8733
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008734 // Set the template specialization kind. Make sure it is set before
8735 // instantiating the members which will trigger ASTConsumer callbacks.
8736 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008737 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008738 } else {
8739
8740 // Set the template specialization kind.
8741 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008742 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008743
John McCall48871652010-08-21 09:40:31 +00008744 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008745}
8746
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008747// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008748DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008749Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008750 SourceLocation ExternLoc,
8751 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008752 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008753 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008754 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008755 IdentifierInfo *Name,
8756 SourceLocation NameLoc,
8757 AttributeList *Attr) {
8758
Douglas Gregord6ab8742009-05-28 23:31:59 +00008759 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008760 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008761 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008762 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008763 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008764 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008765 SourceLocation(), false, TypeResult(),
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00008766 /*IsTypeSpecifier*/false,
8767 /*IsTemplateParamOrArg*/false);
John McCall7f41d982009-09-11 04:59:25 +00008768 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8769
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008770 if (!TagD)
8771 return true;
8772
John McCall48871652010-08-21 09:40:31 +00008773 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00008774 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008775
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008776 if (Tag->isInvalidDecl())
8777 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008778
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008779 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8780 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8781 if (!Pattern) {
8782 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8783 << Context.getTypeDeclType(Record);
8784 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8785 return true;
8786 }
8787
Douglas Gregore47f5a72009-10-14 23:41:34 +00008788 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008789 // If the explicit instantiation is for a class or member class, the
8790 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00008791 // simple-template-id.
8792 //
8793 // C++98 has the same restriction, just worded differently.
8794 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00008795 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008796 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008797
Douglas Gregore47f5a72009-10-14 23:41:34 +00008798 // C++0x [temp.explicit]p2:
8799 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008800 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00008801 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00008802 TemplateSpecializationKind TSK
8803 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8804 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008805
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008806 // C++0x [temp.explicit]p2:
8807 // [...] An explicit instantiation shall appear in an enclosing
8808 // namespace of its template. [...]
8809 //
8810 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008811 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008812
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008813 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008814 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00008815 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008816 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00008817 PrevDecl = Record;
8818 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008819 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008820 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008821 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008822 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008823 PrevDecl,
8824 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008825 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008826 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008827 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00008828 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008829 return TagD;
8830 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008831
Douglas Gregor12e49d32009-10-15 22:53:21 +00008832 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008833 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008834 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00008835 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008836 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00008837 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008838 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008839 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00008840 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00008841 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8842 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00008843 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8844 << Pattern;
8845 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008846 } else {
8847 if (InstantiateClass(NameLoc, Record, Def,
8848 getTemplateInstantiationArgs(Record),
8849 TSK))
8850 return true;
8851
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008852 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00008853 if (!RecordDef)
8854 return true;
8855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008856 }
8857
Douglas Gregor1d957a32009-10-27 18:42:08 +00008858 // Instantiate all of the members of the class.
8859 InstantiateClassMembers(NameLoc, RecordDef,
8860 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008861
Douglas Gregor88d292c2010-05-13 16:44:06 +00008862 if (TSK == TSK_ExplicitInstantiationDefinition)
8863 MarkVTableUsed(NameLoc, RecordDef, true);
8864
Mike Stump87c57ac2009-05-16 07:39:55 +00008865 // FIXME: We don't have any representation for explicit instantiations of
8866 // member classes. Such a representation is not needed for compilation, but it
8867 // should be available for clients that want to see all of the declarations in
8868 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008869 return TagD;
8870}
8871
John McCallfaf5fb42010-08-26 23:41:50 +00008872DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8873 SourceLocation ExternLoc,
8874 SourceLocation TemplateLoc,
8875 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008876 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008877 // TODO: check if/when DNInfo should replace Name.
8878 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8879 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00008880 if (!Name) {
8881 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008882 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008883 diag::err_explicit_instantiation_requires_name)
8884 << D.getDeclSpec().getSourceRange()
8885 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008886
Douglas Gregor450f00842009-09-25 18:43:00 +00008887 return true;
8888 }
8889
8890 // The scope passed in may not be a decl scope. Zip up the scope tree until
8891 // we find one that is.
8892 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8893 (S->getFlags() & Scope::TemplateParamScope) != 0)
8894 S = S->getParent();
8895
8896 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00008897 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8898 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00008899 if (R.isNull())
8900 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008901
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008902 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00008903 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008904 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00008905 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008906 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8907 << Name;
8908 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008909 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008910 != DeclSpec::SCS_unspecified) {
8911 // Complain about then remove the storage class specifier.
8912 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8913 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008914
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008915 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00008916 }
8917
Douglas Gregor3c74d412009-10-14 20:14:33 +00008918 // C++0x [temp.explicit]p1:
8919 // [...] An explicit instantiation of a function template shall not use the
8920 // inline or constexpr specifiers.
8921 // Presumably, this also applies to member functions of class templates as
8922 // well.
Richard Smith83c19292011-10-18 03:44:03 +00008923 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008924 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008925 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00008926 diag::err_explicit_instantiation_inline :
8927 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00008928 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00008929 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00008930 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8931 // not already specified.
8932 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8933 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008934
Nathan Wilsonde498452016-02-08 05:34:00 +00008935 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8936 // applied only to the definition of a function template or variable template,
8937 // declared in namespace scope.
8938 if (D.getDeclSpec().isConceptSpecified()) {
8939 Diag(D.getDeclSpec().getConceptSpecLoc(),
8940 diag::err_concept_specified_specialization) << 0;
8941 return true;
8942 }
8943
Richard Smith19a311a2017-02-09 22:47:51 +00008944 // A deduction guide is not on the list of entities that can be explicitly
8945 // instantiated.
8946 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8947 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8948 << /*explicit instantiation*/ 0;
8949 return true;
8950 }
8951
Douglas Gregore47f5a72009-10-14 23:41:34 +00008952 // C++0x [temp.explicit]p2:
8953 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008954 // definition and an explicit instantiation declaration. An explicit
8955 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00008956 TemplateSpecializationKind TSK
8957 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8958 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008959
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008960 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00008961 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00008962
8963 if (!R->isFunctionType()) {
8964 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008965 // A [...] static data member of a class template can be explicitly
8966 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008967 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008968 // C++1y [temp.explicit]p1:
8969 // A [...] variable [...] template specialization can be explicitly
8970 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00008971 if (Previous.isAmbiguous())
8972 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008973
John McCall67c00872009-12-02 08:25:40 +00008974 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00008975 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008976
Larisse Voufo39a1e502013-08-06 01:03:05 +00008977 if (!PrevTemplate) {
8978 if (!Prev || !Prev->isStaticDataMember()) {
8979 // We expect to see a data data member here.
8980 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8981 << Name;
8982 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8983 P != PEnd; ++P)
8984 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8985 return true;
8986 }
8987
8988 if (!Prev->getInstantiatedFromStaticDataMember()) {
8989 // FIXME: Check for explicit specialization?
8990 Diag(D.getIdentifierLoc(),
8991 diag::err_explicit_instantiation_data_member_not_instantiated)
8992 << Prev;
8993 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8994 // FIXME: Can we provide a note showing where this was declared?
8995 return true;
8996 }
8997 } else {
8998 // Explicitly instantiate a variable template.
8999
9000 // C++1y [dcl.spec.auto]p6:
9001 // ... A program that uses auto or decltype(auto) in a context not
9002 // explicitly allowed in this section is ill-formed.
9003 //
9004 // This includes auto-typed variable template instantiations.
9005 if (R->isUndeducedType()) {
9006 Diag(T->getTypeLoc().getLocStart(),
9007 diag::err_auto_not_allowed_var_inst);
9008 return true;
9009 }
9010
Richard Smithef985ac2013-09-18 02:10:12 +00009011 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
9012 // C++1y [temp.explicit]p3:
9013 // If the explicit instantiation is for a variable, the unqualified-id
9014 // in the declaration shall be a template-id.
9015 Diag(D.getIdentifierLoc(),
9016 diag::err_explicit_instantiation_without_template_id)
9017 << PrevTemplate;
9018 Diag(PrevTemplate->getLocation(),
9019 diag::note_explicit_instantiation_here);
9020 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00009021 }
9022
Nathan Wilson83839122016-04-09 02:55:27 +00009023 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
9024 // explicit instantiation (14.8.2) [...] of a concept definition.
9025 if (PrevTemplate->isConcept()) {
9026 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
9027 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
9028 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
9029 return true;
9030 }
9031
Richard Smithef985ac2013-09-18 02:10:12 +00009032 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00009033 TemplateArgumentListInfo TemplateArgs =
9034 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00009035
Larisse Voufo39a1e502013-08-06 01:03:05 +00009036 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9037 D.getIdentifierLoc(), TemplateArgs);
9038 if (Res.isInvalid())
9039 return true;
9040
9041 // Ignore access control bits, we don't need them for redeclaration
9042 // checking.
9043 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00009044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009045
Douglas Gregore47f5a72009-10-14 23:41:34 +00009046 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009047 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009048 // or a static data member of a class template specialization, the name of
9049 // the class template specialization in the qualified-id for the member
9050 // name shall be a simple-template-id.
9051 //
9052 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009053 //
Richard Smith5977d872013-09-18 21:55:14 +00009054 // This does not apply to variable template specializations, where the
9055 // template-id is in the unqualified-id instead.
9056 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009057 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009058 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009059 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009060
Douglas Gregore47f5a72009-10-14 23:41:34 +00009061 // Check the scope of this explicit instantiation.
9062 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009063
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009064 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00009065 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9066 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009067 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009068 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00009069 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009070 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009071
Larisse Voufo39a1e502013-08-06 01:03:05 +00009072 if (!HasNoEffect) {
9073 // Instantiate static data member or variable template.
9074
9075 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9076 if (PrevTemplate) {
9077 // Merge attributes.
9078 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
9079 ProcessDeclAttributeList(S, Prev, Attr);
9080 }
9081 if (TSK == TSK_ExplicitInstantiationDefinition)
9082 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9083 }
9084
9085 // Check the new variable specialization against the parsed input.
9086 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9087 Diag(T->getTypeLoc().getLocStart(),
9088 diag::err_invalid_var_template_spec_type)
9089 << 0 << PrevTemplate << R << Prev->getType();
9090 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9091 << 2 << PrevTemplate->getDeclName();
9092 return true;
9093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009094
Douglas Gregor450f00842009-09-25 18:43:00 +00009095 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00009096 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009097 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009098
9099 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00009100 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00009101 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00009102 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00009103 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00009104 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00009105 HasExplicitTemplateArgs = true;
9106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009107
Douglas Gregor450f00842009-09-25 18:43:00 +00009108 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009109 // A [...] function [...] can be explicitly instantiated from its template.
9110 // A member function [...] of a class template can be explicitly
9111 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009112 // template.
John McCall27c11dd2017-06-07 23:00:05 +00009113 UnresolvedSet<8> TemplateMatches;
9114 FunctionDecl *NonTemplateMatch = nullptr;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009115 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009116 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00009117 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9118 P != PEnd; ++P) {
9119 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00009120 if (!HasExplicitTemplateArgs) {
9121 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00009122 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9123 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00009124 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
John McCall27c11dd2017-06-07 23:00:05 +00009125 if (Method->getPrimaryTemplate()) {
9126 TemplateMatches.addDecl(Method, P.getAccess());
9127 } else {
9128 // FIXME: Can this assert ever happen? Needs a test.
9129 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9130 NonTemplateMatch = Method;
9131 }
Douglas Gregord90fd522009-09-25 21:45:23 +00009132 }
Douglas Gregor450f00842009-09-25 18:43:00 +00009133 }
9134 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009135
Douglas Gregor450f00842009-09-25 18:43:00 +00009136 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9137 if (!FunTmpl)
9138 continue;
9139
Larisse Voufo98b20f12013-07-19 23:00:19 +00009140 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00009141 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009142 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009143 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00009144 (HasExplicitTemplateArgs ? &TemplateArgs
9145 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00009146 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009147 // Keep track of almost-matches.
9148 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00009149 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009150 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00009151 (void)TDK;
9152 continue;
9153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009154
Artem Belevich64135c32016-12-08 19:38:13 +00009155 // Target attributes are part of the cuda function signature, so
9156 // the cuda target of the instantiated function must match that of its
9157 // template. Given that C++ template deduction does not take
9158 // target attributes into account, we reject candidates here that
9159 // have a different target.
9160 if (LangOpts.CUDA &&
9161 IdentifyCUDATarget(Specialization,
9162 /* IgnoreImplicitHDAttributes = */ true) !=
9163 IdentifyCUDATarget(Attr)) {
9164 FailedCandidates.addCandidate().set(
9165 P.getPair(), FunTmpl->getTemplatedDecl(),
9166 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9167 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009168 }
9169
John McCall27c11dd2017-06-07 23:00:05 +00009170 TemplateMatches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00009171 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009172
John McCall27c11dd2017-06-07 23:00:05 +00009173 FunctionDecl *Specialization = NonTemplateMatch;
9174 if (!Specialization) {
9175 // Find the most specialized function template specialization.
9176 UnresolvedSetIterator Result = getMostSpecialized(
9177 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9178 D.getIdentifierLoc(),
9179 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9180 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9181 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00009182
John McCall27c11dd2017-06-07 23:00:05 +00009183 if (Result == TemplateMatches.end())
9184 return true;
John McCall58cc69d2010-01-27 01:50:18 +00009185
John McCall27c11dd2017-06-07 23:00:05 +00009186 // Ignore access control bits, we don't need them for redeclaration checking.
9187 Specialization = cast<FunctionDecl>(*Result);
9188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009189
Alexey Bataev73983912014-11-06 10:10:50 +00009190 // C++11 [except.spec]p4
9191 // In an explicit instantiation an exception-specification may be specified,
9192 // but is not required.
9193 // If an exception-specification is specified in an explicit instantiation
9194 // directive, it shall be compatible with the exception-specifications of
9195 // other declarations of that function.
9196 if (auto *FPT = R->getAs<FunctionProtoType>())
9197 if (FPT->hasExceptionSpec()) {
9198 unsigned DiagID =
9199 diag::err_mismatched_exception_spec_explicit_instantiation;
9200 if (getLangOpts().MicrosoftExt)
9201 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9202 bool Result = CheckEquivalentExceptionSpec(
9203 PDiag(DiagID) << Specialization->getType(),
9204 PDiag(diag::note_explicit_instantiation_here),
9205 Specialization->getType()->getAs<FunctionProtoType>(),
9206 Specialization->getLocation(), FPT, D.getLocStart());
9207 // In Microsoft mode, mismatching exception specifications just cause a
9208 // warning.
9209 if (!getLangOpts().MicrosoftExt && Result)
9210 return true;
9211 }
9212
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009213 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009214 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009215 diag::err_explicit_instantiation_member_function_not_instantiated)
9216 << Specialization
9217 << (Specialization->getTemplateSpecializationKind() ==
9218 TSK_ExplicitSpecialization);
9219 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9220 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009221 }
9222
Douglas Gregorec9fd132012-01-14 16:38:05 +00009223 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00009224 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9225 PrevDecl = Specialization;
9226
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009227 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00009228 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009229 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009230 PrevDecl,
9231 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009232 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009233 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009234 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009235
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009236 // FIXME: We may still want to build some representation of this
9237 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00009238 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00009239 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009240 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00009241
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00009242 if (Attr)
9243 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009244
Hans Wennborgb8304a62017-11-29 23:44:11 +00009245 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9246 // instantiation declarations.
9247 if (TSK == TSK_ExplicitInstantiationDefinition &&
9248 Specialization->hasAttr<DLLImportAttr>() &&
9249 Context.getTargetInfo().getCXXABI().isMicrosoft())
9250 TSK = TSK_ExplicitInstantiationDeclaration;
9251
9252 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9253
Richard Smitheb36ddf2014-04-24 22:45:46 +00009254 if (Specialization->isDefined()) {
9255 // Let the ASTConsumer know that this function has been explicitly
9256 // instantiated now, and its linkage might have changed.
9257 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9258 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00009259 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009260
Douglas Gregore47f5a72009-10-14 23:41:34 +00009261 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009262 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009263 // or a static data member of a class template specialization, the name of
9264 // the class template specialization in the qualified-id for the member
9265 // name shall be a simple-template-id.
9266 //
9267 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009268 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00009269 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009270 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00009271 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009272 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009273 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009274 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009275
Nathan Wilson83839122016-04-09 02:55:27 +00009276 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
9277 // explicit instantiation (14.8.2) [...] of a concept definition.
9278 if (FunTmpl && FunTmpl->isConcept() &&
9279 !D.getDeclSpec().isConceptSpecified()) {
9280 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
9281 << 0 /*function*/ << 0 /*explicitly instantiated*/;
9282 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
9283 return true;
9284 }
9285
Douglas Gregore47f5a72009-10-14 23:41:34 +00009286 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009287 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00009288 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009289 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00009290 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009291
Douglas Gregor450f00842009-09-25 18:43:00 +00009292 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00009293 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009294}
9295
John McCallfaf5fb42010-08-26 23:41:50 +00009296TypeResult
John McCall7f41d982009-09-11 04:59:25 +00009297Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9298 const CXXScopeSpec &SS, IdentifierInfo *Name,
9299 SourceLocation TagLoc, SourceLocation NameLoc) {
9300 // This has to hold, because SS is expected to be defined.
9301 assert(Name && "Expected a name in a dependent tag");
9302
Aaron Ballman4a979672014-01-03 13:56:08 +00009303 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009304 if (!NNS)
9305 return true;
9306
Abramo Bagnara6150c882010-05-11 21:36:43 +00009307 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009308
Douglas Gregorba41d012010-04-24 16:38:41 +00009309 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9310 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009311 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009312 return true;
9313 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009314
Douglas Gregore7c20652011-03-02 00:47:37 +00009315 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009316 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009317 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009318
Douglas Gregore7c20652011-03-02 00:47:37 +00009319 // Create type-source location information for this type.
9320 TypeLocBuilder TLB;
9321 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009322 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009323 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9324 TL.setNameLoc(NameLoc);
9325 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009326}
9327
John McCallfaf5fb42010-08-26 23:41:50 +00009328TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009329Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9330 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009331 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009332 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009333 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009334
Richard Smith0bf8a4922011-10-18 20:49:44 +00009335 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9336 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009337 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009338 diag::warn_cxx98_compat_typename_outside_of_template :
9339 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009340 << FixItHint::CreateRemoval(TypenameLoc);
9341
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009342 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009343 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9344 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009345 if (T.isNull())
9346 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009347
9348 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9349 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009350 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009351 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009352 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009353 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009354 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009355 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009356 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009357 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009358 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009360
John McCallba7bf592010-08-24 05:47:05 +00009361 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009362}
9363
John McCallfaf5fb42010-08-26 23:41:50 +00009364TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009365Sema::ActOnTypenameType(Scope *S,
9366 SourceLocation TypenameLoc,
9367 const CXXScopeSpec &SS,
9368 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009369 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009370 IdentifierInfo *TemplateII,
9371 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009372 SourceLocation LAngleLoc,
9373 ASTTemplateArgsPtr TemplateArgsIn,
9374 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009375 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9376 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009377 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009378 diag::warn_cxx98_compat_typename_outside_of_template :
9379 diag::ext_typename_outside_of_template)
9380 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009381
Richard Smith74f02342017-01-19 21:00:13 +00009382 // Strangely, non-type results are not ignored by this lookup, so the
9383 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009384 if (TypenameLoc.isValid()) {
9385 auto *LookupRD =
9386 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9387 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9388 Diag(TemplateIILoc,
9389 diag::ext_out_of_line_qualified_id_type_names_constructor)
9390 << TemplateII << 0 /*injected-class-name used as template name*/
9391 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9392 }
Richard Smith74f02342017-01-19 21:00:13 +00009393 }
9394
Douglas Gregorb09518c2011-02-27 22:46:49 +00009395 // Translate the parser's template argument list in our AST format.
9396 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9397 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009398
Douglas Gregorb09518c2011-02-27 22:46:49 +00009399 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009400 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9401 // Construct a dependent template specialization type.
9402 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009403 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009404 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9405 DTN->getQualifier(),
9406 DTN->getIdentifier(),
9407 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009408
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009409 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009410 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009411 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009412 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009413 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9414 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009415 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009416 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009417 SpecTL.setLAngleLoc(LAngleLoc);
9418 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009419 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9420 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009421 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009422 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009423
Richard Smith74f02342017-01-19 21:00:13 +00009424 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009425 if (T.isNull())
9426 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009427
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009428 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009429 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009430 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009431 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009432 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009433 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009434 SpecTL.setLAngleLoc(LAngleLoc);
9435 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009436 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9437 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009438
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009439 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9440 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009441 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009442 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009443
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009444 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9445 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009446}
9447
Douglas Gregorb09518c2011-02-27 22:46:49 +00009448
Richard Smith6f8d2c62012-05-09 05:17:00 +00009449/// Determine whether this failed name lookup should be treated as being
9450/// disabled by a usage of std::enable_if.
9451static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009452 SourceRange &CondRange, Expr *&Cond) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009453 // We must be looking for a ::type...
9454 if (!II.isStr("type"))
9455 return false;
9456
9457 // ... within an explicitly-written template specialization...
9458 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9459 return false;
9460 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009461 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9462 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9463 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009464 return false;
9465 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00009466 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00009467
9468 // ... which names a complete class template declaration...
9469 const TemplateDecl *EnableIfDecl =
9470 EnableIfTST->getTemplateName().getAsTemplateDecl();
9471 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9472 return false;
9473
9474 // ... called "enable_if".
9475 const IdentifierInfo *EnableIfII =
9476 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9477 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9478 return false;
9479
9480 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009481 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009482
9483 // Dig out the condition.
9484 Cond = nullptr;
9485 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9486 != TemplateArgument::Expression)
9487 return true;
9488
9489 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9490
9491 // Ignore Boolean literals; they add no value.
9492 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9493 Cond = nullptr;
9494
Richard Smith6f8d2c62012-05-09 05:17:00 +00009495 return true;
9496}
9497
Douglas Gregor333489b2009-03-27 23:10:48 +00009498/// \brief Build the type that describes a C++ typename specifier,
9499/// e.g., "typename T::type".
9500QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009501Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009502 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009503 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009504 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009505 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009506 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009507 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009508
John McCall0b66eb32010-05-01 00:40:08 +00009509 DeclContext *Ctx = computeDeclContext(SS);
9510 if (!Ctx) {
9511 // If the nested-name-specifier is dependent and couldn't be
9512 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009513 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009514 return Context.getDependentNameType(Keyword,
9515 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009516 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009517 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009518
John McCall0b66eb32010-05-01 00:40:08 +00009519 // If the nested-name-specifier refers to the current instantiation,
9520 // the "typename" keyword itself is superfluous. In C++03, the
9521 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9522 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009523 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009524
John McCall0b66eb32010-05-01 00:40:08 +00009525 if (RequireCompleteDeclContext(SS, Ctx))
9526 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009527
9528 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009529 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009530 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009531 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009532 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009533 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009534 case LookupResult::NotFound: {
9535 // If we're looking up 'type' within a template named 'enable_if', produce
9536 // a more specific diagnostic.
9537 SourceRange CondRange;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009538 Expr *Cond = nullptr;
9539 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9540 // If we have a condition, narrow it down to the specific failed
9541 // condition.
9542 if (Cond) {
9543 Expr *FailedCond;
9544 std::string FailedDescription;
9545 std::tie(FailedCond, FailedDescription) =
Douglas Gregor672281a2017-09-14 23:38:42 +00009546 findFailedBooleanCondition(Cond, /*AllowTopLevelCond=*/true);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009547
9548 Diag(FailedCond->getExprLoc(),
9549 diag::err_typename_nested_not_found_requirement)
9550 << FailedDescription
9551 << FailedCond->getSourceRange();
9552 return QualType();
9553 }
9554
Richard Smith6f8d2c62012-05-09 05:17:00 +00009555 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009556 << Ctx << CondRange;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009557 return QualType();
9558 }
9559
Douglas Gregore40876a2009-10-13 21:16:44 +00009560 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009561 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009562 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009563
9564 case LookupResult::FoundUnresolvedValue: {
9565 // We found a using declaration that is a value. Most likely, the using
9566 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009567 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009568 IILoc);
9569 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9570 << Name << Ctx << FullRange;
9571 if (UnresolvedUsingValueDecl *Using
9572 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009573 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009574 Diag(Loc, diag::note_using_value_decl_missing_typename)
9575 << FixItHint::CreateInsertion(Loc, "typename ");
9576 }
9577 }
9578 // Fall through to create a dependent typename type, from which we can recover
9579 // better.
Galina Kistanova3779cb32017-06-07 06:25:05 +00009580 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009581
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009582 case LookupResult::NotFoundInCurrentInstantiation:
9583 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009584 return Context.getDependentNameType(Keyword,
9585 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009586 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009587
9588 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009589 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009590 // C++ [class.qual]p2:
9591 // In a lookup in which function names are not ignored and the
9592 // nested-name-specifier nominates a class C, if the name specified
9593 // after the nested-name-specifier, when looked up in C, is the
9594 // injected-class-name of C [...] then the name is instead considered
9595 // to name the constructor of class C.
9596 //
9597 // Unlike in an elaborated-type-specifier, function names are not ignored
9598 // in typename-specifier lookup. However, they are ignored in all the
9599 // contexts where we form a typename type with no keyword (that is, in
9600 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9601 //
9602 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9603 // ignore functions, but that appears to be an oversight.
9604 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9605 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9606 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9607 FoundRD->isInjectedClassName() &&
9608 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9609 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9610 << &II << 1 << 0 /*'typename' keyword used*/;
9611
Abramo Bagnara6150c882010-05-11 21:36:43 +00009612 // We found a type. Build an ElaboratedType, since the
9613 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009614 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009615 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009616 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009617 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009618 }
9619
Richard Smithee579842017-01-30 20:39:26 +00009620 // C++ [dcl.type.simple]p2:
9621 // A type-specifier of the form
9622 // typename[opt] nested-name-specifier[opt] template-name
9623 // is a placeholder for a deduced class type [...].
9624 if (getLangOpts().CPlusPlus1z) {
9625 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9626 return Context.getElaboratedType(
9627 Keyword, QualifierLoc.getNestedNameSpecifier(),
9628 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9629 QualType(), false));
9630 }
9631 }
Richard Smith600b5262017-01-26 20:40:47 +00009632
Douglas Gregor333489b2009-03-27 23:10:48 +00009633 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009634 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009635 break;
9636
9637 case LookupResult::FoundOverloaded:
9638 DiagID = diag::err_typename_nested_not_type;
9639 Referenced = *Result.begin();
9640 break;
9641
John McCall6538c932009-10-10 05:48:19 +00009642 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009643 return QualType();
9644 }
9645
9646 // If we get here, it's because name lookup did not find a
9647 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009648 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009649 IILoc);
9650 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009651 if (Referenced)
9652 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9653 << Name;
9654 return QualType();
9655}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009656
9657namespace {
9658 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009659 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009660 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009661 SourceLocation Loc;
9662 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009663
Douglas Gregor15acfb92009-08-06 16:20:37 +00009664 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009665 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009666
Mike Stump11289f42009-09-09 15:08:12 +00009667 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009668 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009669 DeclarationName Entity)
9670 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009671 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009672
9673 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009674 /// transformed.
9675 ///
9676 /// For the purposes of type reconstruction, a type has already been
9677 /// transformed if it is NULL or if it is not dependent.
9678 bool AlreadyTransformed(QualType T) {
9679 return T.isNull() || !T->isDependentType();
9680 }
Mike Stump11289f42009-09-09 15:08:12 +00009681
9682 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009683 /// rebuilt.
9684 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009685
Douglas Gregor15acfb92009-08-06 16:20:37 +00009686 /// \brief Returns the name of the entity whose type is being rebuilt.
9687 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009688
Douglas Gregoref6ab412009-10-27 06:26:26 +00009689 /// \brief Sets the "base" location and entity when that
9690 /// information is known based on another transformation.
9691 void setBase(SourceLocation Loc, DeclarationName Entity) {
9692 this->Loc = Loc;
9693 this->Entity = Entity;
9694 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009695
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00009696 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9697 // Lambdas never need to be transformed.
9698 return E;
9699 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00009700 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009701} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00009702
Douglas Gregor15acfb92009-08-06 16:20:37 +00009703/// \brief Rebuilds a type within the context of the current instantiation.
9704///
Mike Stump11289f42009-09-09 15:08:12 +00009705/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00009706/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00009707/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00009708/// partial specialization thereof). This routine will rebuild that type now
9709/// that we have entered the declarator's scope, which may produce different
9710/// canonical types, e.g.,
9711///
9712/// \code
9713/// template<typename T>
9714/// struct X {
9715/// typedef T* pointer;
9716/// pointer data();
9717/// };
9718///
9719/// template<typename T>
9720/// typename X<T>::pointer X<T>::data() { ... }
9721/// \endcode
9722///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00009723/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009724/// since we do not know that we can look into X<T> when we parsed the type.
9725/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00009726/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00009727/// as the canonical type of T*, allowing the return types of the out-of-line
9728/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00009729TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9730 SourceLocation Loc,
9731 DeclarationName Name) {
9732 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00009733 return T;
Mike Stump11289f42009-09-09 15:08:12 +00009734
Douglas Gregor15acfb92009-08-06 16:20:37 +00009735 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9736 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00009737}
Douglas Gregorbe999392009-09-15 16:23:51 +00009738
John McCalldadc5752010-08-24 06:29:42 +00009739ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00009740 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9741 DeclarationName());
9742 return Rebuilder.TransformExpr(E);
9743}
9744
John McCall99b2fe52010-04-29 23:50:39 +00009745bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00009746 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009747 return true;
John McCall2408e322010-04-27 00:57:59 +00009748
Douglas Gregor10176412011-02-25 16:07:42 +00009749 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009750 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9751 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009752 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009753 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009754 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009755 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009756
Douglas Gregor10176412011-02-25 16:07:42 +00009757 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009758 return false;
John McCall2408e322010-04-27 00:57:59 +00009759}
9760
Douglas Gregor041b0842011-10-14 15:31:12 +00009761/// \brief Rebuild the template parameters now that we know we're in a current
9762/// instantiation.
9763bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9764 TemplateParameterList *Params) {
9765 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9766 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009767
Douglas Gregor041b0842011-10-14 15:31:12 +00009768 // There is nothing to rebuild in a type parameter.
9769 if (isa<TemplateTypeParmDecl>(Param))
9770 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009771
Douglas Gregor041b0842011-10-14 15:31:12 +00009772 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009773 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009774 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9775 if (RebuildTemplateParamsInCurrentInstantiation(
9776 TTP->getTemplateParameters()))
9777 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009778
Douglas Gregor041b0842011-10-14 15:31:12 +00009779 continue;
9780 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009781
Douglas Gregor041b0842011-10-14 15:31:12 +00009782 // Rebuild the type of a non-type template parameter.
9783 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009784 TypeSourceInfo *NewTSI
9785 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9786 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009787 NTTP->getDeclName());
9788 if (!NewTSI)
9789 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009790
Douglas Gregor041b0842011-10-14 15:31:12 +00009791 if (NewTSI != NTTP->getTypeSourceInfo()) {
9792 NTTP->setTypeSourceInfo(NewTSI);
9793 NTTP->setType(NewTSI->getType());
9794 }
9795 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009796
Douglas Gregor041b0842011-10-14 15:31:12 +00009797 return false;
9798}
9799
Douglas Gregorbe999392009-09-15 16:23:51 +00009800/// \brief Produces a formatted string that describes the binding of
9801/// template parameters to template arguments.
9802std::string
9803Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9804 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009805 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00009806}
9807
9808std::string
9809Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9810 const TemplateArgument *Args,
9811 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009812 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00009813 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00009814
Douglas Gregore62e6a02009-11-11 19:13:48 +00009815 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009816 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009817
Douglas Gregorbe999392009-09-15 16:23:51 +00009818 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00009819 if (I >= NumArgs)
9820 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009821
Douglas Gregorbe999392009-09-15 16:23:51 +00009822 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009823 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00009824 else
Douglas Gregor0192c232010-12-20 16:52:59 +00009825 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009826
Douglas Gregorbe999392009-09-15 16:23:51 +00009827 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00009828 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00009829 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00009830 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00009831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009832
Douglas Gregor0192c232010-12-20 16:52:59 +00009833 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00009834 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00009835 }
Douglas Gregor0192c232010-12-20 16:52:59 +00009836
9837 Out << ']';
9838 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00009839}
Francois Pichet1c229c02011-04-22 22:18:13 +00009840
Richard Smithe40f2ba2013-08-07 21:41:30 +00009841void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9842 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00009843 if (!FD)
9844 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00009845
Justin Lebar28f09c52016-10-10 16:26:08 +00009846 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00009847
9848 // Take tokens to avoid allocations
9849 LPT->Toks.swap(Toks);
9850 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00009851 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00009852
9853 FD->setLateTemplateParsed(true);
9854}
9855
9856void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9857 if (!FD)
9858 return;
9859 FD->setLateTemplateParsed(false);
9860}
Francois Pichet1c229c02011-04-22 22:18:13 +00009861
9862bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9863 DeclContext *DC = CurContext;
9864
9865 while (DC) {
9866 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9867 const FunctionDecl *FD = RD->isLocalClass();
9868 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9869 } else if (DC->isTranslationUnit() || DC->isNamespace())
9870 return false;
9871
9872 DC = DC->getParent();
9873 }
9874 return false;
9875}
Richard Smith6739a102016-05-05 00:56:12 +00009876
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009877namespace {
Richard Smith6739a102016-05-05 00:56:12 +00009878/// \brief Walk the path from which a declaration was instantiated, and check
9879/// that every explicit specialization along that path is visible. This enforces
9880/// C++ [temp.expl.spec]/6:
9881///
9882/// If a template, a member template or a member of a class template is
9883/// explicitly specialized then that specialization shall be declared before
9884/// the first use of that specialization that would cause an implicit
9885/// instantiation to take place, in every translation unit in which such a
9886/// use occurs; no diagnostic is required.
9887///
9888/// and also C++ [temp.class.spec]/1:
9889///
9890/// A partial specialization shall be declared before the first use of a
9891/// class template specialization that would make use of the partial
9892/// specialization as the result of an implicit or explicit instantiation
9893/// in every translation unit in which such a use occurs; no diagnostic is
9894/// required.
9895class ExplicitSpecializationVisibilityChecker {
9896 Sema &S;
9897 SourceLocation Loc;
9898 llvm::SmallVector<Module *, 8> Modules;
9899
9900public:
9901 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9902 : S(S), Loc(Loc) {}
9903
9904 void check(NamedDecl *ND) {
9905 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9906 return checkImpl(FD);
9907 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9908 return checkImpl(RD);
9909 if (auto *VD = dyn_cast<VarDecl>(ND))
9910 return checkImpl(VD);
9911 if (auto *ED = dyn_cast<EnumDecl>(ND))
9912 return checkImpl(ED);
9913 }
9914
9915private:
9916 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9917 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9918 : Sema::MissingImportKind::ExplicitSpecialization;
9919 const bool Recover = true;
9920
9921 // If we got a custom set of modules (because only a subset of the
9922 // declarations are interesting), use them, otherwise let
9923 // diagnoseMissingImport intelligently pick some.
9924 if (Modules.empty())
9925 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9926 else
9927 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9928 }
9929
9930 // Check a specific declaration. There are three problematic cases:
9931 //
9932 // 1) The declaration is an explicit specialization of a template
9933 // specialization.
9934 // 2) The declaration is an explicit specialization of a member of an
9935 // templated class.
9936 // 3) The declaration is an instantiation of a template, and that template
9937 // is an explicit specialization of a member of a templated class.
9938 //
9939 // We don't need to go any deeper than that, as the instantiation of the
9940 // surrounding class / etc is not triggered by whatever triggered this
9941 // instantiation, and thus should be checked elsewhere.
9942 template<typename SpecDecl>
9943 void checkImpl(SpecDecl *Spec) {
9944 bool IsHiddenExplicitSpecialization = false;
9945 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9946 IsHiddenExplicitSpecialization =
9947 Spec->getMemberSpecializationInfo()
9948 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
Richard Smith54f04402017-05-18 02:29:20 +00009949 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
Richard Smith6739a102016-05-05 00:56:12 +00009950 } else {
9951 checkInstantiated(Spec);
9952 }
9953
9954 if (IsHiddenExplicitSpecialization)
9955 diagnose(Spec->getMostRecentDecl(), false);
9956 }
9957
9958 void checkInstantiated(FunctionDecl *FD) {
9959 if (auto *TD = FD->getPrimaryTemplate())
9960 checkTemplate(TD);
9961 }
9962
9963 void checkInstantiated(CXXRecordDecl *RD) {
9964 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9965 if (!SD)
9966 return;
9967
9968 auto From = SD->getSpecializedTemplateOrPartial();
9969 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9970 checkTemplate(TD);
9971 else if (auto *TD =
9972 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9973 if (!S.hasVisibleDeclaration(TD))
9974 diagnose(TD, true);
9975 checkTemplate(TD);
9976 }
9977 }
9978
9979 void checkInstantiated(VarDecl *RD) {
9980 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9981 if (!SD)
9982 return;
9983
9984 auto From = SD->getSpecializedTemplateOrPartial();
9985 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9986 checkTemplate(TD);
9987 else if (auto *TD =
9988 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9989 if (!S.hasVisibleDeclaration(TD))
9990 diagnose(TD, true);
9991 checkTemplate(TD);
9992 }
9993 }
9994
9995 void checkInstantiated(EnumDecl *FD) {}
9996
9997 template<typename TemplDecl>
9998 void checkTemplate(TemplDecl *TD) {
9999 if (TD->isMemberSpecialization()) {
10000 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10001 diagnose(TD->getMostRecentDecl(), false);
10002 }
10003 }
10004};
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010005} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +000010006
10007void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10008 if (!getLangOpts().Modules)
10009 return;
10010
10011 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10012}
10013
10014/// \brief Check whether a template partial specialization that we've discovered
10015/// is hidden, and produce suitable diagnostics if so.
10016void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10017 NamedDecl *Spec) {
10018 llvm::SmallVector<Module *, 8> Modules;
10019 if (!hasVisibleDeclaration(Spec, &Modules))
10020 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10021 MissingImportKind::PartialSpecialization,
10022 /*Recover*/true);
10023}