blob: e86f287e0c592e0e8cdd21542e607b98717c4cbc [file] [log] [blame]
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +000011
Douglas Gregor15acfb92009-08-06 16:20:37 +000012#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000013#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000015#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000019#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000020#include "clang/AST/TypeVisitor.h"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000021#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedTemplate.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000032#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000034#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000035
Eric Fiselier6ad68552016-07-01 01:24:09 +000036#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000037using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000039
John McCall9b72f892010-11-10 02:40:36 +000040// Exported for use by Parser.
41SourceRange
42clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 unsigned N) {
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46}
47
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000048namespace clang {
49/// \brief [temp.constr.decl]p2: A template's associated constraints are
50/// defined as a single constraint-expression derived from the introduced
51/// constraint-expressions [ ... ].
52///
53/// \param Params The template parameter list and optional requires-clause.
54///
55/// \param FD The underlying templated function declaration for a function
56/// template.
57static Expr *formAssociatedConstraints(TemplateParameterList *Params,
58 FunctionDecl *FD);
59}
60
61static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
62 FunctionDecl *FD) {
63 // FIXME: Concepts: collect additional introduced constraint-expressions
64 assert(!FD && "Cannot collect constraints from function declaration yet.");
65 return Params->getRequiresClause();
66}
67
Douglas Gregorb7bfe792009-09-02 22:59:36 +000068/// \brief Determine whether the declaration found is acceptable as the name
69/// of a template and, if so, return that template declaration. Otherwise,
70/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000071static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000072 NamedDecl *Orig,
73 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000074 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000076 if (isa<TemplateDecl>(D)) {
77 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000078 return nullptr;
79
John McCalle9cccd82010-06-16 08:42:20 +000080 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000081 }
Mike Stump11289f42009-09-09 15:08:12 +000082
Douglas Gregorb7bfe792009-09-02 22:59:36 +000083 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
84 // C++ [temp.local]p1:
85 // Like normal (non-template) classes, class templates have an
86 // injected-class-name (Clause 9). The injected-class-name
87 // can be used with or without a template-argument-list. When
88 // it is used without a template-argument-list, it is
89 // equivalent to the injected-class-name followed by the
90 // template-parameters of the class template enclosed in
91 // <>. When it is used with a template-argument-list, it
92 // refers to the specified class template specialization,
93 // which could be the current specialization or another
94 // specialization.
95 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000096 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000097 if (Record->getDescribedClassTemplate())
98 return Record->getDescribedClassTemplate();
99
100 if (ClassTemplateSpecializationDecl *Spec
101 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
102 return Spec->getSpecializedTemplate();
103 }
Mike Stump11289f42009-09-09 15:08:12 +0000104
Craig Topperc3ec1492014-05-26 06:22:03 +0000105 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106 }
Mike Stump11289f42009-09-09 15:08:12 +0000107
Craig Topperc3ec1492014-05-26 06:22:03 +0000108 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000109}
110
Simon Pilgrim6905d222016-12-30 22:55:33 +0000111void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000112 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000113 // The set of class templates we've already seen.
114 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +0000115 LookupResult::Filter filter = R.makeFilter();
116 while (filter.hasNext()) {
117 NamedDecl *Orig = filter.next();
Simon Pilgrim6905d222016-12-30 22:55:33 +0000118 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000119 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +0000120 if (!Repl)
121 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000122 else if (Repl != Orig) {
123
124 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000125 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000126 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000127 // one base class). If all of the injected-class-names that are found
128 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000129 // is used as a template-name, the reference refers to the class
130 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000131 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000132 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000133 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000134 filter.erase();
135 continue;
136 }
John McCallbd8062d2010-08-13 07:02:08 +0000137
138 // FIXME: we promote access to public here as a workaround to
139 // the fact that LookupResult doesn't let us remember that we
140 // found this template through a particular injected class name,
141 // which means we end up doing nasty things to the invariants.
142 // Pretending that access is public is *much* safer.
143 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000144 }
John McCalle66edc12009-11-24 19:00:30 +0000145 }
146 filter.done();
147}
148
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000149bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
150 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000151 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000152 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000153 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +0000154
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000155 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000156}
157
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000159 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000160 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000161 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000162 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000163 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000164 TemplateTy &TemplateResult,
165 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000166 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000167
Douglas Gregor3cf81312009-11-03 23:16:33 +0000168 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000169 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000170
Douglas Gregor3cf81312009-11-03 23:16:33 +0000171 switch (Name.getKind()) {
172 case UnqualifiedId::IK_Identifier:
173 TName = DeclarationName(Name.Identifier);
174 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000175
Douglas Gregor3cf81312009-11-03 23:16:33 +0000176 case UnqualifiedId::IK_OperatorFunctionId:
177 TName = Context.DeclarationNames.getCXXOperatorName(
178 Name.OperatorFunctionId.Operator);
179 break;
180
Alexis Hunted0530f2009-11-28 08:58:14 +0000181 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000182 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
183 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000184
Douglas Gregor3cf81312009-11-03 23:16:33 +0000185 default:
186 return TNK_Non_template;
187 }
Mike Stump11289f42009-09-09 15:08:12 +0000188
John McCallba7bf592010-08-24 05:47:05 +0000189 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000190
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000191 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000192 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
193 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000194 if (R.empty()) return TNK_Non_template;
195 if (R.isAmbiguous()) {
196 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000197 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000198
199 // FIXME: we might have ambiguous templates, in which case we
200 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000201 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000202 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000203
John McCalld28ae272009-12-02 08:04:21 +0000204 TemplateName Template;
205 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000206
John McCalld28ae272009-12-02 08:04:21 +0000207 unsigned ResultCount = R.end() - R.begin();
208 if (ResultCount > 1) {
209 // We assume that we'll preserve the qualifier from a function
210 // template name in other ways.
211 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
212 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000213
214 // We'll do this lookup again later.
215 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000216 } else {
John McCalld28ae272009-12-02 08:04:21 +0000217 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
218
219 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000220 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000221 Template = Context.getQualifiedTemplateName(Qualifier,
222 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000223 } else {
224 Template = TemplateName(TD);
225 }
226
John McCalldcc71402010-08-13 02:23:42 +0000227 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000228 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000229
230 // We'll do this lookup again later.
231 R.suppressDiagnostics();
232 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000233 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000234 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
235 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000236 TemplateKind =
237 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000238 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000239 }
Mike Stump11289f42009-09-09 15:08:12 +0000240
John McCalld28ae272009-12-02 08:04:21 +0000241 TemplateResult = TemplateTy::make(Template);
242 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000243}
244
Richard Smith278890f2017-02-10 20:39:58 +0000245bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
246 SourceLocation NameLoc,
247 ParsedTemplateTy *Template) {
248 CXXScopeSpec SS;
249 bool MemberOfUnknownSpecialization = false;
250
251 // We could use redeclaration lookup here, but we don't need to: the
252 // syntactic form of a deduction guide is enough to identify it even
253 // if we can't look up the template name at all.
254 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
255 LookupTemplateName(R, S, SS, /*ObjectType*/QualType(),
256 /*EnteringContext*/false, MemberOfUnknownSpecialization);
257
258 if (R.empty()) return false;
259 if (R.isAmbiguous()) {
260 // FIXME: Diagnose an ambiguity if we find at least one template.
261 R.suppressDiagnostics();
262 return false;
263 }
264
265 // We only treat template-names that name type templates as valid deduction
266 // guide names.
267 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
268 if (!TD || !getAsTypeTemplateDecl(TD))
269 return false;
270
271 if (Template)
272 *Template = TemplateTy::make(TemplateName(TD));
273 return true;
274}
275
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000277 SourceLocation IILoc,
278 Scope *S,
279 const CXXScopeSpec *SS,
280 TemplateTy &SuggestedTemplate,
281 TemplateNameKind &SuggestedKind) {
282 // We can't recover unless there's a dependent scope specifier preceding the
283 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000284 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000285 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
286 computeDeclContext(*SS))
287 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000288
Douglas Gregor18473f32010-01-12 21:28:44 +0000289 // The code is missing a 'template' keyword prior to the dependent template
290 // name.
291 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
292 Diag(IILoc, diag::err_template_kw_missing)
293 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000294 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000295 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000296 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
297 SuggestedKind = TNK_Dependent_template_name;
298 return true;
299}
300
John McCalle66edc12009-11-24 19:00:30 +0000301void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000302 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000303 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000304 bool EnteringContext,
305 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000306 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000307 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000308 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000309 bool isDependent = false;
310 if (!ObjectType.isNull()) {
311 // This nested-name-specifier occurs in a member access expression, e.g.,
312 // x->B::f, and we are looking into the type of the object.
313 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
314 LookupCtx = computeDeclContext(ObjectType);
315 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000316 assert((isDependent || !ObjectType->isIncompleteType() ||
317 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000318 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000319
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000320 // Template names cannot appear inside an Objective-C class or object type.
321 if (ObjectType->isObjCObjectOrInterfaceType()) {
322 Found.clear();
323 return;
324 }
John McCalle66edc12009-11-24 19:00:30 +0000325 } else if (SS.isSet()) {
326 // This nested-name-specifier occurs after another nested-name-specifier,
327 // so long into the context associated with the prior nested-name-specifier.
328 LookupCtx = computeDeclContext(SS, EnteringContext);
329 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000330
John McCalle66edc12009-11-24 19:00:30 +0000331 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000332 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000333 return;
334 }
335
336 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000337 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000338 if (LookupCtx) {
339 // Perform "qualified" name lookup into the declaration context we
340 // computed, which is either the type of the base of a member access
341 // expression or the declaration context associated with a prior
342 // nested-name-specifier.
343 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000344 if (!ObjectType.isNull() && Found.empty()) {
345 // C++ [basic.lookup.classref]p1:
346 // In a class member access expression (5.2.5), if the . or -> token is
347 // immediately followed by an identifier followed by a <, the
348 // identifier must be looked up to determine whether the < is the
349 // beginning of a template argument list (14.2) or a less-than operator.
350 // The identifier is first looked up in the class of the object
351 // expression. If the identifier is not found, it is then looked up in
352 // the context of the entire postfix-expression and shall name a class
353 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000354 if (S) LookupName(Found, S);
355 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000356 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000357 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000358 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000359 // We cannot look into a dependent object type or nested nme
360 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000361 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000362 return;
363 } else {
364 // Perform unqualified name lookup in the current scope.
365 LookupName(Found, S);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000366
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000367 if (!ObjectType.isNull())
368 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000369 }
370
Douglas Gregorc119dd52010-01-12 17:06:20 +0000371 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000372 // If we did not find any names, attempt to correct any typos.
373 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000374 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000375 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000376 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
377 FilterCCC->WantTypeSpecifiers = false;
378 FilterCCC->WantExpressionKeywords = false;
379 FilterCCC->WantRemainingKeywords = false;
380 FilterCCC->WantCXXNamedCasts = true;
381 if (TypoCorrection Corrected = CorrectTypo(
382 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
383 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000384 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000385 if (auto *ND = Corrected.getFoundDecl())
386 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000387 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000388 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000389 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000390 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
391 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000392 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000393 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
394 << Name << LookupCtx << DroppedSpecifier
395 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000396 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000397 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000398 }
John McCalle9cccd82010-06-16 08:42:20 +0000399 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000400 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000401 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000402 }
403 }
404
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000405 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000406 if (Found.empty()) {
407 if (isDependent)
408 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000409 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000410 }
John McCalle66edc12009-11-24 19:00:30 +0000411
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000412 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000413 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000414 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000415 // [...] If the lookup in the class of the object expression finds a
416 // template, the name is also looked up in the context of the entire
417 // postfix-expression and [...]
418 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000419 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000420 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
421 LookupOrdinaryName);
422 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000423 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000424
John McCalle66edc12009-11-24 19:00:30 +0000425 if (FoundOuter.empty()) {
426 // - if the name is not found, the name found in the class of the
427 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000428 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
429 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000430 // - if the name is found in the context of the entire
431 // postfix-expression and does not name a class template, the name
432 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000433 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000434 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000435 // - if the name found is a class template, it must refer to the same
436 // entity as the one found in the class of the object expression,
437 // otherwise the program is ill-formed.
438 if (!Found.isSingleResult() ||
439 Found.getFoundDecl()->getCanonicalDecl()
440 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000442 diag::ext_nested_name_member_ref_lookup_ambiguous)
443 << Found.getLookupName()
444 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000445 Diag(Found.getRepresentativeDecl()->getLocation(),
446 diag::note_ambig_member_ref_object_type)
447 << ObjectType;
448 Diag(FoundOuter.getFoundDecl()->getLocation(),
449 diag::note_ambig_member_ref_scope);
450
451 // Recover by taking the template that we found in the object
452 // expression's type.
453 }
454 }
455 }
456}
457
John McCallcd4b4772009-12-02 03:53:29 +0000458/// ActOnDependentIdExpression - Handle a dependent id-expression that
459/// was just parsed. This is only possible with an explicit scope
460/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000461ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000462Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000463 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000464 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000465 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000466 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000467 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000468
Reid Kleckner1af391df2016-03-11 18:59:12 +0000469 // C++11 [expr.prim.general]p12:
470 // An id-expression that denotes a non-static data member or non-static
471 // member function of a class can only be used:
472 // (...)
473 // - if that id-expression denotes a non-static data member and it
474 // appears in an unevaluated operand.
475 //
476 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
477 // CXXDependentScopeMemberExpr. The former can instantiate to either
478 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
479 // always a MemberExpr.
480 bool MightBeCxx11UnevalField =
481 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
482
Akira Hatanakad644e022016-12-16 03:19:41 +0000483 // Check if the nested name specifier is an enum type.
484 bool IsEnum = false;
485 if (NestedNameSpecifier *NNS = SS.getScopeRep())
486 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
487
488 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000489 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000490 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000491
John McCalle66edc12009-11-24 19:00:30 +0000492 // Since the 'this' expression is synthesized, we don't need to
493 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000494 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000495
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000496 return CXXDependentScopeMemberExpr::Create(
497 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
498 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
499 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000500 }
501
Abramo Bagnara7945c982012-01-27 09:46:47 +0000502 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000503}
504
John McCalldadc5752010-08-24 06:29:42 +0000505ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000506Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000507 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000508 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000509 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000510 return DependentScopeDeclRefExpr::Create(
511 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
512 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000513}
514
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000515
516/// Determine whether we would be unable to instantiate this template (because
517/// it either has no definition, or is in the process of being instantiated).
518bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
519 NamedDecl *Instantiation,
520 bool InstantiatedFromMember,
521 const NamedDecl *Pattern,
522 const NamedDecl *PatternDef,
523 TemplateSpecializationKind TSK,
524 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000525 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
526 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000527
Richard Smithedbc6e92016-10-14 21:41:24 +0000528 bool IsEntityBeingDefined = false;
529 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
530 IsEntityBeingDefined = TD->isBeingDefined();
531
532 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000533 NamedDecl *SuggestedDef = nullptr;
534 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
535 /*OnlyNeedComplete*/false)) {
536 // If we're allowed to diagnose this and recover, do so.
537 bool Recover = Complain && !isSFINAEContext();
538 if (Complain)
539 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
540 Sema::MissingImportKind::Definition, Recover);
541 return !Recover;
542 }
543 return false;
544 }
545
Richard Smith6f4e2e02016-08-23 19:41:39 +0000546 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
547 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000548
Richard Smithedbc6e92016-10-14 21:41:24 +0000549 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000550 QualType InstantiationTy;
551 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
552 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000553 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000554 Diag(PointOfInstantiation,
555 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000556 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000557 << InstantiationTy;
558 // Not much point in noting the template declaration here, since
559 // we're lexically inside it.
560 Instantiation->setInvalidDecl();
561 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000562 if (isa<FunctionDecl>(Instantiation)) {
563 Diag(PointOfInstantiation,
564 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000565 << /*member function*/ 1 << Instantiation->getDeclName()
566 << Instantiation->getDeclContext();
567 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000568 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000569 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000570 Diag(PointOfInstantiation,
571 diag::err_implicit_instantiate_member_undefined)
572 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000573 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000574 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000575 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000576 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000577 Diag(PointOfInstantiation,
578 diag::err_explicit_instantiation_undefined_func_template)
579 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000580 Note = diag::note_explicit_instantiation_here;
581 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000582 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
583 << (TSK != TSK_ImplicitInstantiation)
584 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000585 Note = diag::note_template_decl_here;
586 } else {
587 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
588 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
589 Diag(PointOfInstantiation,
590 diag::err_explicit_instantiation_undefined_var_template)
591 << Instantiation;
592 Instantiation->setInvalidDecl();
593 } else
594 Diag(PointOfInstantiation,
595 diag::err_explicit_instantiation_undefined_member)
596 << /*static data member*/ 2 << Instantiation->getDeclName()
597 << Instantiation->getDeclContext();
598 Note = diag::note_explicit_instantiation_here;
599 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000600 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000601 if (Note) // Diagnostics were emitted.
602 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000603
604 // In general, Instantiation isn't marked invalid to get more than one
605 // error for multiple undefined instantiations. But the code that does
606 // explicit declaration -> explicit definition conversion can't handle
607 // invalid declarations, so mark as invalid in that case.
608 if (TSK == TSK_ExplicitInstantiationDeclaration)
609 Instantiation->setInvalidDecl();
610 return true;
611}
612
Douglas Gregor5101c242008-12-05 18:15:24 +0000613/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
614/// that the template parameter 'PrevDecl' is being shadowed by a new
615/// declaration at location Loc. Returns true to indicate that this is
616/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000617void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000618 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000619
620 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000621 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000622 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000623
624 // C++ [temp.local]p4:
625 // A template-parameter shall not be redeclared within its
626 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000627 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000628 << cast<NamedDecl>(PrevDecl)->getDeclName();
629 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000630}
631
Douglas Gregor463421d2009-03-03 04:44:36 +0000632/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000633/// the parameter D to reference the templated declaration and return a pointer
634/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000635TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
636 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
637 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000638 return Temp;
639 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000640 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000641}
642
Douglas Gregoreb29d182011-01-05 17:40:24 +0000643ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
644 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000646 "Only template template arguments can be pack expansions here");
647 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
648 "Template template argument pack expansion without packs");
649 ParsedTemplateArgument Result(*this);
650 Result.EllipsisLoc = EllipsisLoc;
651 return Result;
652}
653
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000654static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
655 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000657 switch (Arg.getKind()) {
658 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000659 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000660 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000662 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000663 return TemplateArgumentLoc(TemplateArgument(T), DI);
664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000666 case ParsedTemplateArgument::NonType: {
667 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
668 return TemplateArgumentLoc(TemplateArgument(E), E);
669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000671 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000672 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000673 TemplateArgument TArg;
674 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000675 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000676 else
677 TArg = Template;
678 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000679 Arg.getScopeSpec().getWithLocInContext(
680 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000681 Arg.getLocation(),
682 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000683 }
684 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000686 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000687}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000689/// \brief Translates template arguments as provided by the parser
690/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000691void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
692 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000693 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000694 TemplateArgs.addArgument(translateTemplateArgument(*this,
695 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000696}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Richard Smithb80d5402013-06-25 22:21:36 +0000698static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
699 SourceLocation Loc,
700 IdentifierInfo *Name) {
701 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
702 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
703 if (PrevDecl && PrevDecl->isTemplateParameter())
704 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
705}
706
Douglas Gregor5101c242008-12-05 18:15:24 +0000707/// ActOnTypeParameter - Called when a C++ template type parameter
708/// (e.g., "typename T") has been parsed. Typename specifies whether
709/// the keyword "typename" was used to declare the type parameter
710/// (otherwise, "class" was used), and KeyLoc is the location of the
711/// "class" or "typename" keyword. ParamName is the name of the
712/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000713/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000714/// If the type parameter has a default argument, it will be added
715/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000716Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000717 SourceLocation EllipsisLoc,
718 SourceLocation KeyLoc,
719 IdentifierInfo *ParamName,
720 SourceLocation ParamNameLoc,
721 unsigned Depth, unsigned Position,
722 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000723 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000724 assert(S->isTemplateParamScope() &&
725 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000726
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000727 SourceLocation Loc = ParamNameLoc;
728 if (!ParamName)
729 Loc = KeyLoc;
730
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000731 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000732 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000733 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000734 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000735 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000736 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000737
738 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000739 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
740
Douglas Gregor5101c242008-12-05 18:15:24 +0000741 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000742 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000743 IdResolver.AddDecl(Param);
744 }
745
Douglas Gregorf5500772011-01-05 15:48:55 +0000746 // C++0x [temp.param]p9:
747 // A default template-argument may be specified for any kind of
748 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000749 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000750 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000751 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000752 }
753
Douglas Gregordc13ded2010-07-01 00:00:45 +0000754 // Handle the default argument, if provided.
755 if (DefaultArg) {
756 TypeSourceInfo *DefaultTInfo;
757 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000758
Douglas Gregordc13ded2010-07-01 00:00:45 +0000759 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000760
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000761 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000763 UPPC_DefaultArgument))
764 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000765
Douglas Gregordc13ded2010-07-01 00:00:45 +0000766 // Check the template argument itself.
767 if (CheckTemplateArgument(Param, DefaultTInfo)) {
768 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000769 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000771
Richard Smith1469b912015-06-10 00:29:03 +0000772 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774
John McCall48871652010-08-21 09:40:31 +0000775 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000776}
777
Douglas Gregor463421d2009-03-03 04:44:36 +0000778/// \brief Check that the type of a non-type template parameter is
779/// well-formed.
780///
781/// \returns the (possibly-promoted) parameter type if valid;
782/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000783QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
784 SourceLocation Loc) {
785 if (TSI->getType()->isUndeducedType()) {
786 // C++1z [temp.dep.expr]p3:
787 // An id-expression is type-dependent if it contains
788 // - an identifier associated by name lookup with a non-type
789 // template-parameter declared with a type that contains a
790 // placeholder type (7.1.7.4),
791 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
792 }
793
794 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
795}
796
797QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
798 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000799 // We don't allow variably-modified types as the type of non-type template
800 // parameters.
801 if (T->isVariablyModifiedType()) {
802 Diag(Loc, diag::err_variably_modified_nontype_template_param)
803 << T;
804 return QualType();
805 }
806
Douglas Gregor463421d2009-03-03 04:44:36 +0000807 // C++ [temp.param]p4:
808 //
809 // A non-type template-parameter shall have one of the following
810 // (optionally cv-qualified) types:
811 //
812 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000813 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000814 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000815 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000816 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000817 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000818 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000819 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000820 // -- std::nullptr_t.
821 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000822 // If T is a dependent type, we can't do the check now, so we
823 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +0000824 T->isDependentType() ||
825 // Allow use of auto in template parameter declarations.
826 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +0000827 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
828 // are ignored when determining its type.
829 return T.getUnqualifiedType();
830 }
831
Douglas Gregor463421d2009-03-03 04:44:36 +0000832 // C++ [temp.param]p8:
833 //
834 // A non-type template-parameter of type "array of T" or
835 // "function returning T" is adjusted to be of type "pointer to
836 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000837 else if (T->isArrayType() || T->isFunctionType())
838 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839
Douglas Gregor463421d2009-03-03 04:44:36 +0000840 Diag(Loc, diag::err_template_nontype_parm_bad_type)
841 << T;
842
843 return QualType();
844}
845
John McCall48871652010-08-21 09:40:31 +0000846Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
847 unsigned Depth,
848 unsigned Position,
849 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000850 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000851 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +0000852
853 if (TInfo->getType()->isUndeducedType()) {
854 Diag(D.getIdentifierLoc(),
855 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
856 << QualType(TInfo->getType()->getContainedAutoType(), 0);
857 }
Douglas Gregor5101c242008-12-05 18:15:24 +0000858
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000859 assert(S->isTemplateParamScope() &&
860 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000861 bool Invalid = false;
862
Richard Smith15361a22016-12-28 06:27:18 +0000863 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000864 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000865 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000866 Invalid = true;
867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868
Richard Smithb80d5402013-06-25 22:21:36 +0000869 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000870 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000871 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000872 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000873 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000874 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000875 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000876 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000877 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000878
Douglas Gregor5101c242008-12-05 18:15:24 +0000879 if (Invalid)
880 Param->setInvalidDecl();
881
Richard Smithb80d5402013-06-25 22:21:36 +0000882 if (ParamName) {
883 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
884 ParamName);
885
Douglas Gregor5101c242008-12-05 18:15:24 +0000886 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000887 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000888 IdResolver.AddDecl(Param);
889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000890
Douglas Gregorf5500772011-01-05 15:48:55 +0000891 // C++0x [temp.param]p9:
892 // A default template-argument may be specified for any kind of
893 // template-parameter that is not a template parameter pack.
894 if (Default && IsParameterPack) {
895 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000896 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000897 }
898
Douglas Gregordc13ded2010-07-01 00:00:45 +0000899 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000900 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000901 // Check for unexpanded parameter packs.
902 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
903 return Param;
904
Douglas Gregordc13ded2010-07-01 00:00:45 +0000905 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000906 ExprResult DefaultRes =
907 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000908 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000909 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000910 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000911 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000912 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000913
Richard Smith1469b912015-06-10 00:29:03 +0000914 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916
John McCall48871652010-08-21 09:40:31 +0000917 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000918}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000919
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000920/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000921/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000922/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000923Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
924 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000925 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000926 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000927 IdentifierInfo *Name,
928 SourceLocation NameLoc,
929 unsigned Depth,
930 unsigned Position,
931 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000932 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000933 assert(S->isTemplateParamScope() &&
934 "Template template parameter not in template parameter scope!");
935
936 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000937 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000938 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000939 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000940 NameLoc.isInvalid()? TmpLoc : NameLoc,
941 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000942 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000943 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000944
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000945 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000946 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000947 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000948 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
949
John McCall48871652010-08-21 09:40:31 +0000950 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000951 IdResolver.AddDecl(Param);
952 }
953
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000954 if (Params->size() == 0) {
955 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
956 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
957 Param->setInvalidDecl();
958 }
959
Douglas Gregorf5500772011-01-05 15:48:55 +0000960 // C++0x [temp.param]p9:
961 // A default template-argument may be specified for any kind of
962 // template-parameter that is not a template parameter pack.
963 if (IsParameterPack && !Default.isInvalid()) {
964 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
965 Default = ParsedTemplateArgument();
966 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967
Douglas Gregordc13ded2010-07-01 00:00:45 +0000968 if (!Default.isInvalid()) {
969 // Check only that we have a template template argument. We don't want to
970 // try to check well-formedness now, because our template template parameter
971 // might have dependent types in its template parameters, which we wouldn't
972 // be able to match now.
973 //
974 // If none of the template template parameter's template arguments mention
975 // other template parameters, we could actually perform more checking here.
976 // However, it isn't worth doing.
977 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
978 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000979 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000980 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000981 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000984 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000986 DefaultArg.getArgument().getAsTemplate(),
987 UPPC_DefaultArgument))
988 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000989
Richard Smith1469b912015-06-10 00:29:03 +0000990 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000992
John McCall48871652010-08-21 09:40:31 +0000993 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000994}
995
Hubert Tongf608c052016-04-29 18:05:37 +0000996/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
997/// constrained by RequiresClause, that contains the template parameters in
998/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000999TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001000Sema::ActOnTemplateParameterList(unsigned Depth,
1001 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001002 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001003 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +00001004 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001005 SourceLocation RAngleLoc,
1006 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001007 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001008 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001009
David Majnemer902f8c62015-12-27 07:16:27 +00001010 return TemplateParameterList::Create(
1011 Context, TemplateLoc, LAngleLoc,
1012 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001013 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001014}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001015
John McCall3e11ebe2010-03-15 10:12:16 +00001016static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1017 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +00001018 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00001019}
1020
John McCallfaf5fb42010-08-26 23:41:50 +00001021DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00001022Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001023 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001024 IdentifierInfo *Name, SourceLocation NameLoc,
1025 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001026 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00001027 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001028 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001029 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +00001030 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +00001031 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001032 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001033 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001034 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001035 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001036
1037 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001038 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001039 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001040
Abramo Bagnara6150c882010-05-11 21:36:43 +00001041 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1042 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001043
1044 // There is no such thing as an unnamed class template.
1045 if (!Name) {
1046 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001047 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001048 }
1049
Richard Smith6483d222012-04-21 01:27:54 +00001050 // Find any previous declaration with this name. For a friend with no
1051 // scope explicitly specified, we only look for tag declarations (per
1052 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001053 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001054 LookupResult Previous(*this, Name, NameLoc,
1055 (SS.isEmpty() && TUK == TUK_Friend)
1056 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00001057 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001058 if (SS.isNotEmpty() && !SS.isInvalid()) {
1059 SemanticContext = computeDeclContext(SS, true);
1060 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001061 // FIXME: Horrible, horrible hack! We can't currently represent this
1062 // in the AST, and historically we have just ignored such friend
1063 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001064 Diag(NameLoc, TUK == TUK_Friend
1065 ? diag::warn_template_qualified_friend_ignored
1066 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001067 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001068 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001069 }
Mike Stump11289f42009-09-09 15:08:12 +00001070
John McCall0b66eb32010-05-01 00:40:08 +00001071 if (RequireCompleteDeclContext(SS, SemanticContext))
1072 return true;
1073
Simon Pilgrim6905d222016-12-30 22:55:33 +00001074 // If we're adding a template to a dependent context, we may need to
1075 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001076 // now that we know what the current instantiation is.
1077 if (SemanticContext->isDependentContext()) {
1078 ContextRAII SavedContext(*this, SemanticContext);
1079 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1080 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001081 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1082 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +00001083
John McCall27b18f82009-11-17 02:14:36 +00001084 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001085 } else {
1086 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001087
1088 // C++14 [class.mem]p14:
1089 // If T is the name of a class, then each of the following shall have a
1090 // name different from T:
1091 // -- every member template of class T
1092 if (TUK != TUK_Friend &&
1093 DiagnoseClassNameShadow(SemanticContext,
1094 DeclarationNameInfo(Name, NameLoc)))
1095 return true;
1096
John McCall27b18f82009-11-17 02:14:36 +00001097 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001098 }
Mike Stump11289f42009-09-09 15:08:12 +00001099
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001100 if (Previous.isAmbiguous())
1101 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001102
Craig Topperc3ec1492014-05-26 06:22:03 +00001103 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001104 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001105 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001106
Serge Pavlove50bf752016-06-10 04:39:07 +00001107 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1108 // Maybe we will complain about the shadowed template parameter.
1109 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1110 // Just pretend that we didn't see the previous declaration.
1111 PrevDecl = nullptr;
1112 }
1113
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001114 // If there is a previous declaration with the same name, check
1115 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +00001116 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001117 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001118
1119 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001121 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001123 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1124 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001125 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001126 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1127 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1128 PrevClassTemplate
1129 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1130 ->getSpecializedTemplate();
1131 }
1132 }
1133
John McCalld43784f2009-12-18 11:25:59 +00001134 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001135 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136 // [...] When looking for a prior declaration of a class or a function
1137 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001138 // function is neither a qualified name nor a template-id, scopes outside
1139 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001140 if (!SS.isSet()) {
1141 DeclContext *OutermostContext = CurContext;
1142 while (!OutermostContext->isFileContext())
1143 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001144
Richard Smith61e582f2012-04-20 07:12:26 +00001145 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001146 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1147 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1148 SemanticContext = PrevDecl->getDeclContext();
1149 } else {
1150 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001152 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001153 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001154 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001155
1156 // Check that the chosen semantic context doesn't already contain a
1157 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001158 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001159 DeclContext *LookupContext = SemanticContext;
1160 while (LookupContext->isTransparentContext())
1161 LookupContext = LookupContext->getLookupParent();
1162 LookupQualifiedName(Previous, LookupContext);
1163
1164 if (Previous.isAmbiguous())
1165 return true;
1166
1167 if (Previous.begin() != Previous.end())
1168 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001169 }
John McCall90d3bb92009-12-17 23:21:11 +00001170 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001171 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001172 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1173 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001174 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001175
Richard Smithfc805ca2015-07-06 04:43:58 +00001176 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1177 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1178 if (SS.isEmpty() &&
1179 !(PrevClassTemplate &&
1180 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1181 SemanticContext->getRedeclContext()))) {
1182 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1183 Diag(Shadow->getTargetDecl()->getLocation(),
1184 diag::note_using_decl_target);
1185 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1186 // Recover by ignoring the old declaration.
1187 PrevDecl = PrevClassTemplate = nullptr;
1188 }
1189 }
1190
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001191 // TODO Memory management; associated constraints are not always stored.
1192 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1193
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001194 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001195 // Ensure that the template parameter lists are compatible. Skip this check
1196 // for a friend in a dependent context: the template parameter list itself
1197 // could be dependent.
1198 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1199 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001200 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001201 /*Complain=*/true,
1202 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001203 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001204
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001205 // Check for matching associated constraints on redeclarations.
1206 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1207 const bool RedeclACMismatch = [&] {
1208 if (!(CurAC || PrevAC))
1209 return false; // Nothing to check; no mismatch.
1210 if (CurAC && PrevAC) {
1211 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1212 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1213 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1214 if (CurACInfo == PrevACInfo)
1215 return false; // All good; no mismatch.
1216 }
1217 return true;
1218 }();
1219
1220 if (RedeclACMismatch) {
1221 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1222 diag::err_template_different_associated_constraints);
1223 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1224 diag::note_template_prev_declaration) << /*declaration*/0;
1225 return true;
1226 }
1227
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001228 // C++ [temp.class]p4:
1229 // In a redeclaration, partial specialization, explicit
1230 // specialization or explicit instantiation of a class template,
1231 // the class-key shall agree in kind with the original class
1232 // template declaration (7.1.5.3).
1233 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001234 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001235 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001236 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001237 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001238 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001239 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001240 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001241 }
1242
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001243 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001244 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001245 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001246 // If we have a prior definition that is not visible, treat this as
1247 // simply making that previous definition visible.
1248 NamedDecl *Hidden = nullptr;
1249 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001250 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001251 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1252 assert(Tmpl && "original definition of a class template is not a "
1253 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001254 makeMergedDefinitionVisible(Hidden, KWLoc);
1255 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001256 return Def;
1257 }
1258
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001259 Diag(NameLoc, diag::err_redefinition) << Name;
1260 Diag(Def->getLocation(), diag::note_previous_definition);
1261 // FIXME: Would it make sense to try to "forget" the previous
1262 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001263 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001264 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001265 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001266 } else if (PrevDecl) {
1267 // C++ [temp]p5:
1268 // A class template shall not have the same name as any other
1269 // template, class, function, object, enumeration, enumerator,
1270 // namespace, or type in the same scope (3.3), except as specified
1271 // in (14.5.4).
1272 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1273 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001274 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001275 }
1276
Douglas Gregordba32632009-02-10 19:49:53 +00001277 // Check the template parameter list of this declaration, possibly
1278 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001279 // template declaration. Skip this check for a friend in a dependent
1280 // context, because the template parameter list might be dependent.
1281 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001282 CheckTemplateParameterList(
1283 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001284 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1285 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001286 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1287 SemanticContext->isDependentContext())
1288 ? TPC_ClassTemplateMember
1289 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1290 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001291 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001292
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001293 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001294 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001295 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001296 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1297 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001298 : diag::err_member_decl_does_not_match)
1299 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001300 Invalid = true;
1301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001302 }
1303
Vassil Vassilev352e4412017-01-12 09:16:26 +00001304 // If this is a templated friend in a dependent context we should not put it
1305 // on the redecl chain. In some cases, the templated friend can be the most
1306 // recent declaration tricking the template instantiator to make substitutions
1307 // there.
1308 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1309 bool ShouldAddRedecl
1310 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1311
Mike Stump11289f42009-09-09 15:08:12 +00001312 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001313 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001314 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001315 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001316 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001317 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001318 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001319 NewClass->setTemplateParameterListsInfo(
1320 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1321 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001322
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001323 // Add alignment attributes if necessary; these attributes are checked when
1324 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001325 if (TUK == TUK_Definition) {
1326 AddAlignmentAttributesForRecord(NewClass);
1327 AddMsStructLayoutForRecord(NewClass);
1328 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001329
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001330 // Attach the associated constraints when the declaration will not be part of
1331 // a decl chain.
1332 Expr *const ACtoAttach =
1333 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1334
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001335 ClassTemplateDecl *NewTemplate
1336 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1337 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001338 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001339
1340 if (ShouldAddRedecl)
1341 NewTemplate->setPreviousDecl(PrevClassTemplate);
1342
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001343 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001344
Douglas Gregor21823bf2011-12-20 18:11:52 +00001345 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001346 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001347
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001348 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001349 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001350 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001351 assert(T->isDependentType() && "Class template type is not dependent?");
1352 (void)T;
1353
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001354 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001355 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001356 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001357 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1358 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359
Anders Carlsson137108d2009-03-26 01:24:28 +00001360 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001361 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001362 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001363
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001364 // Set the lexical context of these templates
1365 NewClass->setLexicalDeclContext(CurContext);
1366 NewTemplate->setLexicalDeclContext(CurContext);
1367
John McCall9bb74a52009-07-31 02:45:11 +00001368 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001369 NewClass->startDefinition();
1370
1371 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001372 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001373
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001374 if (PrevClassTemplate)
1375 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1376
Rafael Espindola385c0422012-07-13 18:04:45 +00001377 AddPushedVisibilityAttribute(NewClass);
1378
Richard Smith234ff472014-08-23 00:49:01 +00001379 if (TUK != TUK_Friend) {
1380 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1381 Scope *Outer = S;
1382 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1383 Outer = Outer->getParent();
1384 PushOnScopeChains(NewTemplate, Outer);
1385 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001386 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001387 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001388 NewClass->setAccess(PrevClassTemplate->getAccess());
1389 }
John McCall27b5c252009-09-14 21:59:20 +00001390
Richard Smith64017682013-07-17 23:53:16 +00001391 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001392
John McCall27b5c252009-09-14 21:59:20 +00001393 // Friend templates are visible in fairly strange ways.
1394 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001395 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001396 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001397 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1398 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001401
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001402 FriendDecl *Friend = FriendDecl::Create(
1403 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001404 Friend->setAccess(AS_public);
1405 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001406 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001407
Douglas Gregordba32632009-02-10 19:49:53 +00001408 if (Invalid) {
1409 NewTemplate->setInvalidDecl();
1410 NewClass->setInvalidDecl();
1411 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001412
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001413 ActOnDocumentableDecl(NewTemplate);
1414
John McCall48871652010-08-21 09:40:31 +00001415 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001416}
1417
Richard Smith32918772017-02-14 00:25:28 +00001418namespace {
1419/// Transform to convert portions of a constructor declaration into the
1420/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1421struct ConvertConstructorToDeductionGuideTransform {
1422 ConvertConstructorToDeductionGuideTransform(Sema &S,
1423 ClassTemplateDecl *Template)
1424 : SemaRef(S), Template(Template) {}
1425
1426 Sema &SemaRef;
1427 ClassTemplateDecl *Template;
1428
1429 DeclContext *DC = Template->getDeclContext();
1430 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1431 DeclarationName DeductionGuideName =
1432 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1433
1434 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1435
1436 // Index adjustment to apply to convert depth-1 template parameters into
1437 // depth-0 template parameters.
1438 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1439
1440 /// Transform a constructor declaration into a deduction guide.
1441 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD, FunctionDecl *FD) {
1442 SmallVector<TemplateArgument, 16> SubstArgs;
1443
1444 // C++ [over.match.class.deduct]p1:
1445 // -- For each constructor of the class template designated by the
1446 // template-name, a function template with the following properties:
1447
1448 // -- The template parameters are the template parameters of the class
1449 // template followed by the template parameters (including default
1450 // template arguments) of the constructor, if any.
1451 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1452 if (FTD) {
1453 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1454 SmallVector<NamedDecl *, 16> AllParams;
1455 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1456 AllParams.insert(AllParams.begin(),
1457 TemplateParams->begin(), TemplateParams->end());
1458 SubstArgs.reserve(InnerParams->size());
1459
1460 // Later template parameters could refer to earlier ones, so build up
1461 // a list of substituted template arguments as we go.
1462 for (NamedDecl *Param : *InnerParams) {
1463 MultiLevelTemplateArgumentList Args;
1464 Args.addOuterTemplateArguments(SubstArgs);
1465 Args.addOuterTemplateArguments(None);
1466 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1467 if (!NewParam)
1468 return nullptr;
1469 AllParams.push_back(NewParam);
1470 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1471 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1472 }
1473 TemplateParams = TemplateParameterList::Create(
1474 SemaRef.Context, InnerParams->getTemplateLoc(),
1475 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1476 /*FIXME: RequiresClause*/ nullptr);
1477 }
1478
1479 // If we built a new template-parameter-list, track that we need to
1480 // substitute references to the old parameters into references to the
1481 // new ones.
1482 MultiLevelTemplateArgumentList Args;
1483 if (FTD) {
1484 Args.addOuterTemplateArguments(SubstArgs);
1485 Args.addOuterTemplateArguments(None);
1486 }
1487
1488 FunctionProtoTypeLoc FPTL = FD->getTypeSourceInfo()->getTypeLoc()
1489 .getAsAdjusted<FunctionProtoTypeLoc>();
1490 assert(FPTL && "no prototype for constructor declaration");
1491
1492 // Transform the type of the function, adjusting the return type and
1493 // replacing references to the old parameters with references to the
1494 // new ones.
1495 TypeLocBuilder TLB;
1496 SmallVector<ParmVarDecl*, 8> Params;
1497 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1498 if (NewType.isNull())
1499 return nullptr;
1500 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1501
1502 return buildDeductionGuide(TemplateParams, FD->isExplicit(), NewTInfo,
1503 FD->getLocStart(), FD->getLocation(),
1504 FD->getLocEnd());
1505 }
1506
1507 /// Build a deduction guide with the specified parameter types.
1508 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1509 SourceLocation Loc = Template->getLocation();
1510
1511 // Build the requested type.
1512 FunctionProtoType::ExtProtoInfo EPI;
1513 EPI.HasTrailingReturn = true;
1514 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1515 DeductionGuideName, EPI);
1516 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1517
1518 FunctionProtoTypeLoc FPTL =
1519 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1520
1521 // Build the parameters, needed during deduction / substitution.
1522 SmallVector<ParmVarDecl*, 4> Params;
1523 for (auto T : ParamTypes) {
1524 ParmVarDecl *NewParam = ParmVarDecl::Create(
1525 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1526 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1527 NewParam->setScopeInfo(0, Params.size());
1528 FPTL.setParam(Params.size(), NewParam);
1529 Params.push_back(NewParam);
1530 }
1531
1532 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1533 Loc, Loc, Loc);
1534 }
1535
1536private:
1537 /// Transform a constructor template parameter into a deduction guide template
1538 /// parameter, rebuilding any internal references to earlier parameters and
1539 /// renumbering as we go.
1540 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1541 MultiLevelTemplateArgumentList &Args) {
1542 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1543 // TemplateTypeParmDecl's index cannot be changed after creation, so
1544 // substitute it directly.
1545 auto *NewTTP = TemplateTypeParmDecl::Create(
1546 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1547 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1548 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1549 TTP->isParameterPack());
1550 if (TTP->hasDefaultArgument()) {
1551 TypeSourceInfo *InstantiatedDefaultArg =
1552 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1553 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1554 if (InstantiatedDefaultArg)
1555 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1556 }
1557 return NewTTP;
1558 }
1559
1560 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1561 return transformTemplateParameterImpl(TTP, Args);
1562
1563 return transformTemplateParameterImpl(
1564 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1565 }
1566 template<typename TemplateParmDecl>
1567 TemplateParmDecl *
1568 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1569 MultiLevelTemplateArgumentList &Args) {
1570 // Ask the template instantiator to do the heavy lifting for us, then adjust
1571 // the index of the parameter once it's done.
1572 auto *NewParam =
1573 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1574 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1575 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1576 return NewParam;
1577 }
1578
1579 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1580 FunctionProtoTypeLoc TL,
1581 SmallVectorImpl<ParmVarDecl*> &Params,
1582 MultiLevelTemplateArgumentList &Args) {
1583 SmallVector<QualType, 4> ParamTypes;
1584 const FunctionProtoType *T = TL.getTypePtr();
1585
1586 // -- The types of the function parameters are those of the constructor.
1587 for (auto *OldParam : TL.getParams()) {
1588 // If we're transforming a non-template constructor, just reuse its
1589 // parameters as the parameters of the deduction guide. Otherwise, we
1590 // need to transform their references to constructor template parameters.
1591 ParmVarDecl *NewParam = Args.getNumLevels()
1592 ? transformFunctionTypeParam(OldParam, Args)
1593 : OldParam;
1594 if (!NewParam)
1595 return QualType();
1596 ParamTypes.push_back(NewParam->getType());
1597 Params.push_back(NewParam);
1598 }
1599
1600 // -- The return type is the class template specialization designated by
1601 // the template-name and template arguments corresponding to the
1602 // template parameters obtained from the class template.
1603 //
1604 // We use the injected-class-name type of the primary template instead.
1605 // This has the convenient property that it is different from any type that
1606 // the user can write in a deduction-guide (because they cannot enter the
1607 // context of the template), so implicit deduction guides can never collide
1608 // with explicit ones.
1609 QualType ReturnType = DeducedType;
1610 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1611
1612 // Resolving a wording defect, we also inherit the variadicness of the
1613 // constructor.
1614 FunctionProtoType::ExtProtoInfo EPI;
1615 EPI.Variadic = T->isVariadic();
1616 EPI.HasTrailingReturn = true;
1617
1618 QualType Result = SemaRef.BuildFunctionType(
1619 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1620 if (Result.isNull())
1621 return QualType();
1622
1623 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1624 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1625 NewTL.setLParenLoc(TL.getLParenLoc());
1626 NewTL.setRParenLoc(TL.getRParenLoc());
1627 NewTL.setExceptionSpecRange(SourceRange());
1628 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1629 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1630 NewTL.setParam(I, Params[I]);
1631
1632 return Result;
1633 }
1634
1635 ParmVarDecl *
1636 transformFunctionTypeParam(ParmVarDecl *OldParam,
1637 MultiLevelTemplateArgumentList &Args) {
1638 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1639 TypeSourceInfo *NewDI = SemaRef.SubstType(
1640 OldDI, Args, OldParam->getLocation(), OldParam->getDeclName());
1641 if (!NewDI)
1642 return nullptr;
1643
1644 // Resolving a wording defect, we also inherit default arguments from the
1645 // constructor.
1646 ExprResult NewDefArg;
1647 if (OldParam->hasDefaultArg()) {
1648 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
1649 if (NewDefArg.isInvalid())
1650 return nullptr;
1651 }
1652
1653 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1654 OldParam->getInnerLocStart(),
1655 OldParam->getLocation(),
1656 OldParam->getIdentifier(),
1657 NewDI->getType(),
1658 NewDI,
1659 OldParam->getStorageClass(),
1660 NewDefArg.get());
1661 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1662 OldParam->getFunctionScopeIndex());
1663 return NewParam;
1664 }
1665
1666 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1667 bool Explicit, TypeSourceInfo *TInfo,
1668 SourceLocation LocStart, SourceLocation Loc,
1669 SourceLocation LocEnd) {
1670 // Build the implicit deduction guide template.
1671 auto *Guide = FunctionDecl::Create(SemaRef.Context, DC, LocStart, Loc,
1672 DeductionGuideName, TInfo->getType(),
1673 TInfo, SC_None);
1674 Guide->setImplicit();
1675 if (Explicit)
1676 Guide->setExplicitSpecified();
1677 Guide->setRangeEnd(LocEnd);
1678 Guide->setParams(
1679 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams());
1680
1681 auto *GuideTemplate = FunctionTemplateDecl::Create(
1682 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1683 GuideTemplate->setImplicit();
1684 Guide->setDescribedFunctionTemplate(GuideTemplate);
1685
1686 if (isa<CXXRecordDecl>(DC)) {
1687 Guide->setAccess(AS_public);
1688 GuideTemplate->setAccess(AS_public);
1689 }
1690
1691 DC->addDecl(GuideTemplate);
1692 return GuideTemplate;
1693 }
1694};
1695}
1696
1697void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1698 SourceLocation Loc) {
1699 DeclContext *DC = Template->getDeclContext();
1700 if (DC->isDependentContext())
1701 return;
1702
1703 ConvertConstructorToDeductionGuideTransform Transform(
1704 *this, cast<ClassTemplateDecl>(Template));
1705 if (!isCompleteType(Loc, Transform.DeducedType))
1706 return;
1707
1708 // Check whether we've already declared deduction guides for this template.
1709 // FIXME: Consider storing a flag on the template to indicate this.
1710 auto Existing = DC->lookup(Transform.DeductionGuideName);
1711 for (auto *D : Existing)
1712 if (D->isImplicit())
1713 return;
1714
1715 // In case we were expanding a pack when we attempted to declare deduction
1716 // guides, turn off pack expansion for everything we're about to do.
1717 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1718 // Create a template instantiation record to track the "instantiation" of
1719 // constructors into deduction guides.
1720 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1721 // this substitution process actually fail?
1722 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1723
1724 // Convert declared constructors into deduction guide templates.
1725 // FIXME: Skip constructors for which deduction must necessarily fail (those
1726 // for which some class template parameter without a default argument never
1727 // appears in a deduced context).
1728 bool AddedAny = false;
1729 bool AddedCopyOrMove = false;
1730 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1731 D = D->getUnderlyingDecl();
1732 if (D->isInvalidDecl() || D->isImplicit())
1733 continue;
1734 D = cast<NamedDecl>(D->getCanonicalDecl());
1735
1736 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1737 auto *FD = FTD ? FTD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D);
1738 // Class-scope explicit specializations (MS extension) do not result in
1739 // deduction guides.
1740 if (!FD || (!FTD && FD->isFunctionTemplateSpecialization()))
1741 continue;
1742
1743 Transform.transformConstructor(FTD, FD);
1744 AddedAny = true;
1745
1746 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(FD);
1747 AddedCopyOrMove |= CD->isCopyOrMoveConstructor();
1748 }
1749
1750 // Synthesize an X() -> X<...> guide if there were no declared constructors.
1751 // FIXME: The standard doesn't say (how) to do this.
1752 if (!AddedAny)
1753 Transform.buildSimpleDeductionGuide(None);
1754
1755 // Synthesize an X(X<...>) -> X<...> guide if there was no declared constructor
1756 // resembling a copy or move constructor.
1757 // FIXME: The standard doesn't say (how) to do this.
1758 if (!AddedCopyOrMove)
1759 Transform.buildSimpleDeductionGuide(Transform.DeducedType);
1760}
1761
Douglas Gregored5731f2009-11-25 17:50:39 +00001762/// \brief Diagnose the presence of a default template argument on a
1763/// template parameter, which is ill-formed in certain contexts.
1764///
1765/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001766static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001767 Sema::TemplateParamListContext TPC,
1768 SourceLocation ParamLoc,
1769 SourceRange DefArgRange) {
1770 switch (TPC) {
1771 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001772 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001773 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001774 return false;
1775
1776 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001777 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001778 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001779 // A default template-argument shall not be specified in a
1780 // function template declaration or a function template
1781 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00001782 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001783 // template-argument, that declaration shall be a definition and shall be
1784 // the only declaration of the function template in the translation unit.
1785 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001786 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001787 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1788 : diag::ext_template_parameter_default_in_function_template)
1789 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001790 return false;
1791
1792 case Sema::TPC_ClassTemplateMember:
1793 // C++0x [temp.param]p9:
1794 // A default template-argument shall not be specified in the
1795 // template-parameter-lists of the definition of a member of a
1796 // class template that appears outside of the member's class.
1797 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1798 << DefArgRange;
1799 return true;
1800
David Majnemerba8f17a2013-06-25 22:08:55 +00001801 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001802 case Sema::TPC_FriendFunctionTemplate:
1803 // C++ [temp.param]p9:
1804 // A default template-argument shall not be specified in a
1805 // friend template declaration.
1806 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1807 << DefArgRange;
1808 return true;
1809
1810 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1811 // for friend function templates if there is only a single
1812 // declaration (and it is a definition). Strange!
1813 }
1814
David Blaikie8a40f702012-01-17 06:56:22 +00001815 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001816}
1817
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001818/// \brief Check for unexpanded parameter packs within the template parameters
1819/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001820static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1821 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001822 // A template template parameter which is a parameter pack is also a pack
1823 // expansion.
1824 if (TTP->isParameterPack())
1825 return false;
1826
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001827 TemplateParameterList *Params = TTP->getTemplateParameters();
1828 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1829 NamedDecl *P = Params->getParam(I);
1830 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001831 if (!NTTP->isParameterPack() &&
1832 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001833 NTTP->getTypeSourceInfo(),
1834 Sema::UPPC_NonTypeTemplateParameterType))
1835 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001836
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001837 continue;
1838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001839
1840 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001841 = dyn_cast<TemplateTemplateParmDecl>(P))
1842 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1843 return true;
1844 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001845
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001846 return false;
1847}
1848
Douglas Gregordba32632009-02-10 19:49:53 +00001849/// \brief Checks the validity of a template parameter list, possibly
1850/// considering the template parameter list from a previous
1851/// declaration.
1852///
1853/// If an "old" template parameter list is provided, it must be
1854/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1855/// template parameter list.
1856///
1857/// \param NewParams Template parameter list for a new template
1858/// declaration. This template parameter list will be updated with any
1859/// default arguments that are carried through from the previous
1860/// template parameter list.
1861///
1862/// \param OldParams If provided, template parameter list from a
1863/// previous declaration of the same template. Default template
1864/// arguments will be merged from the old template parameter list to
1865/// the new template parameter list.
1866///
Douglas Gregored5731f2009-11-25 17:50:39 +00001867/// \param TPC Describes the context in which we are checking the given
1868/// template parameter list.
1869///
Douglas Gregordba32632009-02-10 19:49:53 +00001870/// \returns true if an error occurred, false otherwise.
1871bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001872 TemplateParameterList *OldParams,
1873 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001874 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001875
Douglas Gregordba32632009-02-10 19:49:53 +00001876 // C++ [temp.param]p10:
1877 // The set of default template-arguments available for use with a
1878 // template declaration or definition is obtained by merging the
1879 // default arguments from the definition (if in scope) and all
1880 // declarations in scope in the same way default function
1881 // arguments are (8.3.6).
1882 bool SawDefaultArgument = false;
1883 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001884
Mike Stumpc89c8e32009-02-11 23:03:27 +00001885 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001886 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001887 if (OldParams)
1888 OldParam = OldParams->begin();
1889
Douglas Gregor0693def2011-01-27 01:40:17 +00001890 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001891 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1892 NewParamEnd = NewParams->end();
1893 NewParam != NewParamEnd; ++NewParam) {
1894 // Variables used to diagnose redundant default arguments
1895 bool RedundantDefaultArg = false;
1896 SourceLocation OldDefaultLoc;
1897 SourceLocation NewDefaultLoc;
1898
David Blaikie651c73c2011-10-19 05:19:50 +00001899 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001900 bool MissingDefaultArg = false;
1901
David Blaikie651c73c2011-10-19 05:19:50 +00001902 // Variable used to diagnose non-final parameter packs
1903 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001904
Douglas Gregordba32632009-02-10 19:49:53 +00001905 if (TemplateTypeParmDecl *NewTypeParm
1906 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001907 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001908 if (NewTypeParm->hasDefaultArgument() &&
1909 DiagnoseDefaultTemplateArgument(*this, TPC,
1910 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001911 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001912 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001913 NewTypeParm->removeDefaultArgument();
1914
1915 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001916 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001917 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001918 if (NewTypeParm->isParameterPack()) {
1919 assert(!NewTypeParm->hasDefaultArgument() &&
1920 "Parameter packs can't have a default argument!");
1921 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001922 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001923 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001924 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1925 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1926 SawDefaultArgument = true;
1927 RedundantDefaultArg = true;
1928 PreviousDefaultArgLoc = NewDefaultLoc;
1929 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1930 // Merge the default argument from the old declaration to the
1931 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001932 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001933 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1934 } else if (NewTypeParm->hasDefaultArgument()) {
1935 SawDefaultArgument = true;
1936 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1937 } else if (SawDefaultArgument)
1938 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001939 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001940 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001941 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001942 if (!NewNonTypeParm->isParameterPack() &&
1943 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001944 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001945 UPPC_NonTypeTemplateParameterType)) {
1946 Invalid = true;
1947 continue;
1948 }
1949
Douglas Gregored5731f2009-11-25 17:50:39 +00001950 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001951 if (NewNonTypeParm->hasDefaultArgument() &&
1952 DiagnoseDefaultTemplateArgument(*this, TPC,
1953 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001954 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001955 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001956 }
1957
Mike Stump12b8ce12009-08-04 21:02:39 +00001958 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001959 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001960 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001961 if (NewNonTypeParm->isParameterPack()) {
1962 assert(!NewNonTypeParm->hasDefaultArgument() &&
1963 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001964 if (!NewNonTypeParm->isPackExpansion())
1965 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001966 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001967 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001968 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1969 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1970 SawDefaultArgument = true;
1971 RedundantDefaultArg = true;
1972 PreviousDefaultArgLoc = NewDefaultLoc;
1973 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1974 // Merge the default argument from the old declaration to the
1975 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001976 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001977 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1978 } else if (NewNonTypeParm->hasDefaultArgument()) {
1979 SawDefaultArgument = true;
1980 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1981 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001982 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001983 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001984 TemplateTemplateParmDecl *NewTemplateParm
1985 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001987 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001988 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001989 Invalid = true;
1990 continue;
1991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
David Blaikie651c73c2011-10-19 05:19:50 +00001993 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001994 if (NewTemplateParm->hasDefaultArgument() &&
1995 DiagnoseDefaultTemplateArgument(*this, TPC,
1996 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001997 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001998 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001999
2000 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002001 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002002 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002003 if (NewTemplateParm->isParameterPack()) {
2004 assert(!NewTemplateParm->hasDefaultArgument() &&
2005 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002006 if (!NewTemplateParm->isPackExpansion())
2007 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002008 } else if (OldTemplateParm &&
2009 hasVisibleDefaultArgument(OldTemplateParm) &&
2010 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002011 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2012 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002013 SawDefaultArgument = true;
2014 RedundantDefaultArg = true;
2015 PreviousDefaultArgLoc = NewDefaultLoc;
2016 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2017 // Merge the default argument from the old declaration to the
2018 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002019 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002020 PreviousDefaultArgLoc
2021 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002022 } else if (NewTemplateParm->hasDefaultArgument()) {
2023 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002024 PreviousDefaultArgLoc
2025 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002026 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002027 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002028 }
2029
Richard Smith1fde8ec2012-09-07 02:06:42 +00002030 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002031 // If a template parameter of a primary class template or alias template
2032 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002033 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002034 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2035 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002036 Diag((*NewParam)->getLocation(),
2037 diag::err_template_param_pack_must_be_last_template_parameter);
2038 Invalid = true;
2039 }
2040
Douglas Gregordba32632009-02-10 19:49:53 +00002041 if (RedundantDefaultArg) {
2042 // C++ [temp.param]p12:
2043 // A template-parameter shall not be given default arguments
2044 // by two different declarations in the same scope.
2045 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2046 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2047 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002048 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002049 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002050 // If a template-parameter of a class template has a default
2051 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002052 // have a default template-argument supplied or be a template parameter
2053 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002054 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002055 diag::err_template_param_default_arg_missing);
2056 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2057 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002058 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002059 }
2060
2061 // If we have an old template parameter list that we're merging
2062 // in, move on to the next parameter.
2063 if (OldParams)
2064 ++OldParam;
2065 }
2066
Douglas Gregor0693def2011-01-27 01:40:17 +00002067 // We were missing some default arguments at the end of the list, so remove
2068 // all of the default arguments.
2069 if (RemoveDefaultArguments) {
2070 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2071 NewParamEnd = NewParams->end();
2072 NewParam != NewParamEnd; ++NewParam) {
2073 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2074 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002075 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002076 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2077 NTTP->removeDefaultArgument();
2078 else
2079 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2080 }
2081 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002082
Douglas Gregordba32632009-02-10 19:49:53 +00002083 return Invalid;
2084}
Douglas Gregord32e0282009-02-09 23:23:08 +00002085
John McCalla020a012010-10-20 05:44:58 +00002086namespace {
2087
2088/// A class which looks for a use of a certain level of template
2089/// parameter.
2090struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2091 typedef RecursiveASTVisitor<DependencyChecker> super;
2092
2093 unsigned Depth;
Richard Smith43a833b2017-01-09 23:54:33 +00002094 bool FindLessThanDepth;
Richard Smith57aae072016-12-28 02:37:25 +00002095
2096 // Whether we're looking for a use of a template parameter that makes the
2097 // overall construct type-dependent / a dependent type. This is strictly
2098 // best-effort for now; we may fail to match at all for a dependent type
2099 // in some cases if this is set.
2100 bool IgnoreNonTypeDependent;
2101
John McCalla020a012010-10-20 05:44:58 +00002102 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002103 SourceLocation MatchLoc;
2104
Richard Smith43a833b2017-01-09 23:54:33 +00002105 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent,
2106 bool FindLessThanDepth = false)
2107 : Depth(Depth), FindLessThanDepth(FindLessThanDepth),
2108 IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002109
Richard Smith57aae072016-12-28 02:37:25 +00002110 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith43a833b2017-01-09 23:54:33 +00002111 : DependencyChecker(Params->getDepth(), IgnoreNonTypeDependent) {}
John McCalla020a012010-10-20 05:44:58 +00002112
Richard Smith6056d5e2014-02-09 00:54:43 +00002113 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith43a833b2017-01-09 23:54:33 +00002114 if (FindLessThanDepth ^ (ParmDepth >= Depth)) {
John McCalla020a012010-10-20 05:44:58 +00002115 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002116 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002117 return true;
2118 }
2119 return false;
2120 }
2121
Richard Smith57aae072016-12-28 02:37:25 +00002122 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2123 // Prune out non-type-dependent expressions if requested. This can
2124 // sometimes result in us failing to find a template parameter reference
2125 // (if a value-dependent expression creates a dependent type), but this
2126 // mode is best-effort only.
2127 if (auto *E = dyn_cast_or_null<Expr>(S))
2128 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2129 return true;
2130 return super::TraverseStmt(S, Q);
2131 }
2132
2133 bool TraverseTypeLoc(TypeLoc TL) {
2134 if (IgnoreNonTypeDependent && !TL.isNull() &&
2135 !TL.getType()->isDependentType())
2136 return true;
2137 return super::TraverseTypeLoc(TL);
2138 }
2139
Richard Smith6056d5e2014-02-09 00:54:43 +00002140 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2141 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2142 }
2143
John McCalla020a012010-10-20 05:44:58 +00002144 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002145 // For a best-effort search, keep looking until we find a location.
2146 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002147 }
2148
2149 bool TraverseTemplateName(TemplateName N) {
2150 if (TemplateTemplateParmDecl *PD =
2151 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002152 if (Matches(PD->getDepth()))
2153 return false;
John McCalla020a012010-10-20 05:44:58 +00002154 return super::TraverseTemplateName(N);
2155 }
2156
2157 bool VisitDeclRefExpr(DeclRefExpr *E) {
2158 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002159 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2160 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002161 return false;
John McCalla020a012010-10-20 05:44:58 +00002162 return super::VisitDeclRefExpr(E);
2163 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002164
2165 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2166 return TraverseType(T->getReplacementType());
2167 }
2168
2169 bool
2170 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2171 return TraverseTemplateArgument(T->getArgumentPack());
2172 }
2173
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002174 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2175 return TraverseType(T->getInjectedSpecializationType());
2176 }
John McCalla020a012010-10-20 05:44:58 +00002177};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002178} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002179
Douglas Gregor972fe532011-05-10 18:27:06 +00002180/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002181/// list.
2182static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002183DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002184 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002185 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002186 return Checker.Match;
2187}
2188
Douglas Gregor972fe532011-05-10 18:27:06 +00002189// Find the source range corresponding to the named type in the given
2190// nested-name-specifier, if any.
2191static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2192 QualType T,
2193 const CXXScopeSpec &SS) {
2194 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2195 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2196 if (const Type *CurType = NNS->getAsType()) {
2197 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2198 return NNSLoc.getTypeLoc().getSourceRange();
2199 } else
2200 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002201
Douglas Gregor972fe532011-05-10 18:27:06 +00002202 NNSLoc = NNSLoc.getPrefix();
2203 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002204
Douglas Gregor972fe532011-05-10 18:27:06 +00002205 return SourceRange();
2206}
2207
Mike Stump11289f42009-09-09 15:08:12 +00002208/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002209/// specifier, returning the template parameter list that applies to the
2210/// name.
2211///
2212/// \param DeclStartLoc the start of the declaration that has a scope
2213/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002214///
Douglas Gregor972fe532011-05-10 18:27:06 +00002215/// \param DeclLoc The location of the declaration itself.
2216///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002217/// \param SS the scope specifier that will be matched to the given template
2218/// parameter lists. This scope specifier precedes a qualified name that is
2219/// being declared.
2220///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002221/// \param TemplateId The template-id following the scope specifier, if there
2222/// is one. Used to check for a missing 'template<>'.
2223///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002224/// \param ParamLists the template parameter lists, from the outermost to the
2225/// innermost template parameter lists.
2226///
John McCalle820e5e2010-04-13 20:37:33 +00002227/// \param IsFriend Whether to apply the slightly different rules for
2228/// matching template parameters to scope specifiers in friend
2229/// declarations.
2230///
Richard Smithf445f192017-02-09 21:04:43 +00002231/// \param IsMemberSpecialization will be set true if the scope specifier
2232/// denotes a fully-specialized type, and therefore this is a declaration of
2233/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002234///
Mike Stump11289f42009-09-09 15:08:12 +00002235/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002236/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002237/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002238/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002239/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002240/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002241TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2242 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002243 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002244 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002245 bool &IsMemberSpecialization, bool &Invalid) {
2246 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002247 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002248
Douglas Gregor972fe532011-05-10 18:27:06 +00002249 // The sequence of nested types to which we will match up the template
2250 // parameter lists. We first build this list by starting with the type named
2251 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002252 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002253 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002254 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002255 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002256 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2257 T = Context.getTypeDeclType(Record);
2258 else
2259 T = QualType(SS.getScopeRep()->getAsType(), 0);
2260 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002261
Douglas Gregor972fe532011-05-10 18:27:06 +00002262 // If we found an explicit specialization that prevents us from needing
2263 // 'template<>' headers, this will be set to the location of that
2264 // explicit specialization.
2265 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002266
Douglas Gregor972fe532011-05-10 18:27:06 +00002267 while (!T.isNull()) {
2268 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002269
Douglas Gregor972fe532011-05-10 18:27:06 +00002270 // Retrieve the parent of a record type.
2271 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2272 // If this type is an explicit specialization, we're done.
2273 if (ClassTemplateSpecializationDecl *Spec
2274 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002275 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002276 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2277 ExplicitSpecLoc = Spec->getLocation();
2278 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002279 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002280 } else if (Record->getTemplateSpecializationKind()
2281 == TSK_ExplicitSpecialization) {
2282 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002283 break;
2284 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002285
Douglas Gregor972fe532011-05-10 18:27:06 +00002286 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2287 T = Context.getTypeDeclType(Parent);
2288 else
2289 T = QualType();
2290 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002291 }
2292
Douglas Gregor972fe532011-05-10 18:27:06 +00002293 if (const TemplateSpecializationType *TST
2294 = T->getAs<TemplateSpecializationType>()) {
2295 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2296 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2297 T = Context.getTypeDeclType(Parent);
2298 else
2299 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002300 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002301 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002302 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002303
Douglas Gregor972fe532011-05-10 18:27:06 +00002304 // Look one step prior in a dependent template specialization type.
2305 if (const DependentTemplateSpecializationType *DependentTST
2306 = T->getAs<DependentTemplateSpecializationType>()) {
2307 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2308 T = QualType(NNS->getAsType(), 0);
2309 else
2310 T = QualType();
2311 continue;
2312 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002313
Douglas Gregor972fe532011-05-10 18:27:06 +00002314 // Look one step prior in a dependent name type.
2315 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2316 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2317 T = QualType(NNS->getAsType(), 0);
2318 else
2319 T = QualType();
2320 continue;
2321 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002322
Douglas Gregor972fe532011-05-10 18:27:06 +00002323 // Retrieve the parent of an enumeration type.
2324 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2325 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2326 // check here.
2327 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002328
Douglas Gregor972fe532011-05-10 18:27:06 +00002329 // Get to the parent type.
2330 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2331 T = Context.getTypeDeclType(Parent);
2332 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002333 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002334 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002335 }
Mike Stump11289f42009-09-09 15:08:12 +00002336
Douglas Gregor972fe532011-05-10 18:27:06 +00002337 T = QualType();
2338 }
2339 // Reverse the nested types list, since we want to traverse from the outermost
2340 // to the innermost while checking template-parameter-lists.
2341 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002342
Douglas Gregor972fe532011-05-10 18:27:06 +00002343 // C++0x [temp.expl.spec]p17:
2344 // A member or a member template may be nested within many
2345 // enclosing class templates. In an explicit specialization for
2346 // such a member, the member declaration shall be preceded by a
2347 // template<> for each enclosing class template that is
2348 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002349 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002350
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002351 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002352 if (SawNonEmptyTemplateParameterList) {
2353 Diag(DeclLoc, diag::err_specialize_member_of_template)
2354 << !Recovery << Range;
2355 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002356 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002357 return true;
2358 }
2359
2360 return false;
2361 };
2362
2363 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2364 // Check that we can have an explicit specialization here.
2365 if (CheckExplicitSpecialization(Range, true))
2366 return true;
2367
2368 // We don't have a template header, but we should.
2369 SourceLocation ExpectedTemplateLoc;
2370 if (!ParamLists.empty())
2371 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2372 else
2373 ExpectedTemplateLoc = DeclStartLoc;
2374
2375 Diag(DeclLoc, diag::err_template_spec_needs_header)
2376 << Range
2377 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2378 return false;
2379 };
2380
Douglas Gregor972fe532011-05-10 18:27:06 +00002381 unsigned ParamIdx = 0;
2382 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2383 ++TypeIdx) {
2384 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002385
Douglas Gregor972fe532011-05-10 18:27:06 +00002386 // Whether we expect a 'template<>' header.
2387 bool NeedEmptyTemplateHeader = false;
2388
2389 // Whether we expect a template header with parameters.
2390 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002391
Douglas Gregor972fe532011-05-10 18:27:06 +00002392 // For a dependent type, the set of template parameters that we
2393 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002394 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002395
Douglas Gregor373af9b2011-05-11 23:26:17 +00002396 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002397 // A member or a member template may be nested within many enclosing
2398 // class templates. In an explicit specialization for such a member, the
2399 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002400 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002401 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2402 if (ClassTemplatePartialSpecializationDecl *Partial
2403 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2404 ExpectedTemplateParams = Partial->getTemplateParameters();
2405 NeedNonemptyTemplateHeader = true;
2406 } else if (Record->isDependentType()) {
2407 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002408 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002409 ->getTemplateParameters();
2410 NeedNonemptyTemplateHeader = true;
2411 }
2412 } else if (ClassTemplateSpecializationDecl *Spec
2413 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2414 // C++0x [temp.expl.spec]p4:
2415 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002416 // in the same manner as members of normal classes, and not using
2417 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002418 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2419 NeedEmptyTemplateHeader = true;
2420 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002421 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002422 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002423 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002424 != TSK_ExplicitSpecialization &&
2425 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002426 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002427
Douglas Gregor373af9b2011-05-11 23:26:17 +00002428 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002429 }
2430 } else if (const TemplateSpecializationType *TST
2431 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002432 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002433 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002434 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002435 }
2436 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2437 // FIXME: We actually could/should check the template arguments here
2438 // against the corresponding template parameter list.
2439 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002440 }
2441
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002442 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002443 // In an explicit specialization declaration for a member of a class
2444 // template or a member template that ap- pears in namespace scope, the
2445 // member template and some of its enclosing class templates may remain
2446 // unspecialized, except that the declaration shall not explicitly
2447 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002448 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002449 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002450 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002451 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2452 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002453 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002454 } else
2455 SawNonEmptyTemplateParameterList = true;
2456 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002457
Douglas Gregor972fe532011-05-10 18:27:06 +00002458 if (NeedEmptyTemplateHeader) {
2459 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002460 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002461 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002462 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002463
2464 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002465 if (ParamLists[ParamIdx]->size() > 0) {
2466 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002467 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002468 diag::err_template_param_list_matches_nontemplate)
2469 << T
2470 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2471 ParamLists[ParamIdx]->getRAngleLoc())
2472 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2473 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002474 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002475 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002476
Douglas Gregor972fe532011-05-10 18:27:06 +00002477 // Consume this template header.
2478 ++ParamIdx;
2479 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002480 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002481
2482 if (!IsFriend)
2483 if (DiagnoseMissingExplicitSpecialization(
2484 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002485 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002486
Douglas Gregor972fe532011-05-10 18:27:06 +00002487 continue;
2488 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002489
Douglas Gregor972fe532011-05-10 18:27:06 +00002490 if (NeedNonemptyTemplateHeader) {
2491 // In friend declarations we can have template-ids which don't
2492 // depend on the corresponding template parameter lists. But
2493 // assume that empty parameter lists are supposed to match this
2494 // template-id.
2495 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002496 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002497 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002498 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002499 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002500 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002501 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002502
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002503 if (ParamIdx < ParamLists.size()) {
2504 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002505 if (ExpectedTemplateParams &&
2506 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2507 ExpectedTemplateParams,
2508 true, TPL_TemplateMatch))
2509 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002510
Douglas Gregor972fe532011-05-10 18:27:06 +00002511 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002512 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002513 TPC_ClassTemplateMember))
2514 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002515
Douglas Gregor972fe532011-05-10 18:27:06 +00002516 ++ParamIdx;
2517 continue;
2518 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002519
Douglas Gregor972fe532011-05-10 18:27:06 +00002520 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2521 << T
2522 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2523 Invalid = true;
2524 continue;
2525 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002526 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002527
Douglas Gregord8d297c2009-07-21 23:53:31 +00002528 // If there were at least as many template-ids as there were template
2529 // parameter lists, then there are no template parameter lists remaining for
2530 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002531 if (ParamIdx >= ParamLists.size()) {
2532 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002533 // We don't have a template header for the declaration itself, but we
2534 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002535 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2536 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002537
2538 // Fabricate an empty template parameter list for the invented header.
2539 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002540 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002541 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002542 }
2543
Craig Topperc3ec1492014-05-26 06:22:03 +00002544 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002545 }
Mike Stump11289f42009-09-09 15:08:12 +00002546
Douglas Gregord8d297c2009-07-21 23:53:31 +00002547 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002548 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002549 bool HasAnyExplicitSpecHeader = false;
2550 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002551 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002552 if (ParamLists[I]->size() == 0)
2553 HasAnyExplicitSpecHeader = true;
2554 else
2555 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002556 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002557
Douglas Gregor972fe532011-05-10 18:27:06 +00002558 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002559 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2560 : diag::err_template_spec_extra_headers)
2561 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2562 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002563
2564 // If there was a specialization somewhere, such that 'template<>' is
2565 // not required, and there were any 'template<>' headers, note where the
2566 // specialization occurred.
2567 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002568 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002569 diag::note_explicit_template_spec_does_not_need_header)
2570 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002571
Douglas Gregor972fe532011-05-10 18:27:06 +00002572 // We have a template parameter list with no corresponding scope, which
2573 // means that the resulting template declaration can't be instantiated
2574 // properly (we'll end up with dependent nodes when we shouldn't).
2575 if (!AllExplicitSpecHeaders)
2576 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002577 }
Mike Stump11289f42009-09-09 15:08:12 +00002578
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002579 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002580 // In an explicit specialization declaration for a member of a class
2581 // template or a member template that ap- pears in namespace scope, the
2582 // member template and some of its enclosing class templates may remain
2583 // unspecialized, except that the declaration shall not explicitly
2584 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002585 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002586 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002587 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2588 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002589 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002590
Douglas Gregord8d297c2009-07-21 23:53:31 +00002591 // Return the last template parameter list, which corresponds to the
2592 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002593 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002594}
2595
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002596void Sema::NoteAllFoundTemplates(TemplateName Name) {
2597 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2598 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002599 << (isa<FunctionTemplateDecl>(Template)
2600 ? 0
2601 : isa<ClassTemplateDecl>(Template)
2602 ? 1
2603 : isa<VarTemplateDecl>(Template)
2604 ? 2
2605 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2606 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002607 return;
2608 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002609
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002610 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002611 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002612 IEnd = OST->end();
2613 I != IEnd; ++I)
2614 Diag((*I)->getLocation(), diag::note_template_declared_here)
2615 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002616
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002617 return;
2618 }
2619}
2620
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002621static QualType
2622checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2623 const SmallVectorImpl<TemplateArgument> &Converted,
2624 SourceLocation TemplateLoc,
2625 TemplateArgumentListInfo &TemplateArgs) {
2626 ASTContext &Context = SemaRef.getASTContext();
2627 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002628 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002629 // Specializations of __make_integer_seq<S, T, N> are treated like
2630 // S<T, 0, ..., N-1>.
2631
2632 // C++14 [inteseq.intseq]p1:
2633 // T shall be an integer type.
2634 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2635 SemaRef.Diag(TemplateArgs[1].getLocation(),
2636 diag::err_integer_sequence_integral_element_type);
2637 return QualType();
2638 }
2639
2640 // C++14 [inteseq.make]p1:
2641 // If N is negative the program is ill-formed.
2642 TemplateArgument NumArgsArg = Converted[2];
2643 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2644 if (NumArgs < 0) {
2645 SemaRef.Diag(TemplateArgs[2].getLocation(),
2646 diag::err_integer_sequence_negative_length);
2647 return QualType();
2648 }
2649
2650 QualType ArgTy = NumArgsArg.getIntegralType();
2651 TemplateArgumentListInfo SyntheticTemplateArgs;
2652 // The type argument gets reused as the first template argument in the
2653 // synthetic template argument list.
2654 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2655 // Expand N into 0 ... N-1.
2656 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2657 I < NumArgs; ++I) {
2658 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002659 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2660 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002661 }
2662 // The first template argument will be reused as the template decl that
2663 // our synthetic template arguments will be applied to.
2664 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2665 TemplateLoc, SyntheticTemplateArgs);
2666 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002667
2668 case BTK__type_pack_element:
2669 // Specializations of
2670 // __type_pack_element<Index, T_1, ..., T_N>
2671 // are treated like T_Index.
2672 assert(Converted.size() == 2 &&
2673 "__type_pack_element should be given an index and a parameter pack");
2674
2675 // If the Index is out of bounds, the program is ill-formed.
2676 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2677 llvm::APSInt Index = IndexArg.getAsIntegral();
2678 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2679 "type std::size_t, and hence be non-negative");
2680 if (Index >= Ts.pack_size()) {
2681 SemaRef.Diag(TemplateArgs[0].getLocation(),
2682 diag::err_type_pack_element_out_of_bounds);
2683 return QualType();
2684 }
2685
2686 // We simply return the type at index `Index`.
2687 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2688 return Nth->getAsType();
2689 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002690 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2691}
2692
Douglas Gregordc572a32009-03-30 22:58:21 +00002693QualType Sema::CheckTemplateIdType(TemplateName Name,
2694 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002695 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002696 DependentTemplateName *DTN
2697 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002698 if (DTN && DTN->isIdentifier())
2699 // When building a template-id where the template-name is dependent,
2700 // assume the template is a type template. Either our assumption is
2701 // correct, or the code is ill-formed and will be diagnosed when the
2702 // dependent name is substituted.
2703 return Context.getDependentTemplateSpecializationType(ETK_None,
2704 DTN->getQualifier(),
2705 DTN->getIdentifier(),
2706 TemplateArgs);
2707
Douglas Gregordc572a32009-03-30 22:58:21 +00002708 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002709 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2710 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002711 // We might have a substituted template template parameter pack. If so,
2712 // build a template specialization type for it.
2713 if (Name.getAsSubstTemplateTemplateParmPack())
2714 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002715
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002716 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2717 << Name;
2718 NoteAllFoundTemplates(Name);
2719 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002720 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002721
Douglas Gregorc40290e2009-03-09 23:48:35 +00002722 // Check that the template argument list is well-formed for this
2723 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002724 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002725 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002726 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002727 return QualType();
2728
Douglas Gregorc40290e2009-03-09 23:48:35 +00002729 QualType CanonType;
2730
Douglas Gregor678d76c2011-07-01 01:22:09 +00002731 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002732 if (TypeAliasTemplateDecl *AliasTemplate =
2733 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002734 // Find the canonical type for this type alias template specialization.
2735 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2736 if (Pattern->isInvalidDecl())
2737 return QualType();
2738
2739 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002740 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002741
2742 // Only substitute for the innermost template argument list.
2743 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002744 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002745 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2746 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002747 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002748
Richard Smith802c4b72012-08-23 06:16:52 +00002749 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002750 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002751 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002752 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002753
Richard Smith3f1b5d02011-05-05 21:57:07 +00002754 CanonType = SubstType(Pattern->getUnderlyingType(),
2755 TemplateArgLists, AliasTemplate->getLocation(),
2756 AliasTemplate->getDeclName());
2757 if (CanonType.isNull())
2758 return QualType();
2759 } else if (Name.isDependent() ||
2760 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002761 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002762 // This class template specialization is a dependent
2763 // type. Therefore, its canonical type is another class template
2764 // specialization type that contains all of the converted
2765 // arguments in canonical form. This ensures that, e.g., A<T> and
2766 // A<T, T> have identical types when A is declared as:
2767 //
2768 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00002769 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00002770
2771 // This might work out to be a current instantiation, in which
2772 // case the canonical type needs to be the InjectedClassNameType.
2773 //
2774 // TODO: in theory this could be a simple hashtable lookup; most
2775 // changes to CurContext don't change the set of current
2776 // instantiations.
2777 if (isa<ClassTemplateDecl>(Template)) {
2778 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2779 // If we get out to a namespace, we're done.
2780 if (Ctx->isFileContext()) break;
2781
2782 // If this isn't a record, keep looking.
2783 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2784 if (!Record) continue;
2785
2786 // Look for one of the two cases with InjectedClassNameTypes
2787 // and check whether it's the same template.
2788 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2789 !Record->getDescribedClassTemplate())
2790 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002791
John McCall2408e322010-04-27 00:57:59 +00002792 // Fetch the injected class name type and check whether its
2793 // injected type is equal to the type we just built.
2794 QualType ICNT = Context.getTypeDeclType(Record);
2795 QualType Injected = cast<InjectedClassNameType>(ICNT)
2796 ->getInjectedSpecializationType();
2797
2798 if (CanonType != Injected->getCanonicalTypeInternal())
2799 continue;
2800
2801 // If so, the canonical type of this TST is the injected
2802 // class name type of the record we just found.
2803 assert(ICNT.isCanonical());
2804 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002805 break;
2806 }
2807 }
Mike Stump11289f42009-09-09 15:08:12 +00002808 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002809 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002810 // Find the class template specialization declaration that
2811 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002812 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002813 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002814 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002815 if (!Decl) {
2816 // This is the first time we have referenced this class template
2817 // specialization. Create the canonical declaration and add it to
2818 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002819 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002820 ClassTemplate->getTemplatedDecl()->getTagKind(),
2821 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002822 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002823 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002824 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00002825 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002826 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002827 if (ClassTemplate->isOutOfLine())
2828 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002829 }
2830
Chandler Carruth2acfb222013-09-27 22:14:40 +00002831 // Diagnose uses of this specialization.
2832 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2833
Douglas Gregorc40290e2009-03-09 23:48:35 +00002834 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002835 assert(isa<RecordType>(CanonType) &&
2836 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002837 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2838 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2839 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002840 }
Mike Stump11289f42009-09-09 15:08:12 +00002841
Douglas Gregorc40290e2009-03-09 23:48:35 +00002842 // Build the fully-sugared type for this class template
2843 // specialization, which refers back to the class template
2844 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002845 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002846}
2847
John McCallfaf5fb42010-08-26 23:41:50 +00002848TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002849Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00002850 TemplateTy TemplateD, IdentifierInfo *TemplateII,
2851 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00002852 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002853 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002854 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00002855 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002856 if (SS.isInvalid())
2857 return true;
2858
Richard Smith62559bd2017-02-01 21:36:38 +00002859 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
2860 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
2861
2862 // C++ [temp.res]p3:
2863 // A qualified-id that refers to a type and in which the
2864 // nested-name-specifier depends on a template-parameter (14.6.2)
2865 // shall be prefixed by the keyword typename to indicate that the
2866 // qualified-id denotes a type, forming an
2867 // elaborated-type-specifier (7.1.5.3).
2868 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00002869 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00002870 << SS.getScopeRep() << TemplateII->getName();
2871 // Recover as if 'typename' were specified.
2872 // FIXME: This is not quite correct recovery as we don't transform SS
2873 // into the corresponding dependent form (and we don't diagnose missing
2874 // 'template' keywords within SS as a result).
2875 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
2876 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
2877 TemplateArgsIn, RAngleLoc);
2878 }
2879
2880 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
2881 // it's not actually allowed to be used as a type in most cases. Because
2882 // we annotate it before we know whether it's valid, we have to check for
2883 // this case here.
2884 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00002885 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
2886 Diag(TemplateIILoc,
2887 TemplateKWLoc.isInvalid()
2888 ? diag::err_out_of_line_qualified_id_type_names_constructor
2889 : diag::ext_out_of_line_qualified_id_type_names_constructor)
2890 << TemplateII << 0 /*injected-class-name used as template name*/
2891 << 1 /*if any keyword was present, it was 'template'*/;
2892 }
2893 }
2894
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002895 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002896
Douglas Gregorc40290e2009-03-09 23:48:35 +00002897 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002898 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002899 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002900
Douglas Gregor5a064722011-02-28 17:23:35 +00002901 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002902 QualType T
2903 = Context.getDependentTemplateSpecializationType(ETK_None,
2904 DTN->getQualifier(),
2905 DTN->getIdentifier(),
2906 TemplateArgs);
2907 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002908 TypeLocBuilder TLB;
2909 DependentTemplateSpecializationTypeLoc SpecTL
2910 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002911 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2912 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002913 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00002914 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002915 SpecTL.setLAngleLoc(LAngleLoc);
2916 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002917 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2918 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2919 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2920 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002921
Richard Smith74f02342017-01-19 21:00:13 +00002922 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002923 if (Result.isNull())
2924 return true;
2925
Douglas Gregore7c20652011-03-02 00:47:37 +00002926 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002927 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002928 TemplateSpecializationTypeLoc SpecTL
2929 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002930 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00002931 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002932 SpecTL.setLAngleLoc(LAngleLoc);
2933 SpecTL.setRAngleLoc(RAngleLoc);
2934 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2935 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002936
Abramo Bagnara4244b432012-01-27 08:46:19 +00002937 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2938 // constructor or destructor name (in such a case, the scope specifier
2939 // will be attached to the enclosing Decl or Expr node).
2940 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002941 // Create an elaborated-type-specifier containing the nested-name-specifier.
2942 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2943 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002944 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002945 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2946 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002947
Douglas Gregore7c20652011-03-02 00:47:37 +00002948 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002949}
John McCall06f6fe8d2009-09-04 01:14:41 +00002950
Douglas Gregore7c20652011-03-02 00:47:37 +00002951TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002952 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002953 SourceLocation TagLoc,
2954 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002955 SourceLocation TemplateKWLoc,
2956 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002957 SourceLocation TemplateLoc,
2958 SourceLocation LAngleLoc,
2959 ASTTemplateArgsPtr TemplateArgsIn,
2960 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002961 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002962
Douglas Gregore7c20652011-03-02 00:47:37 +00002963 // Translate the parser's template argument list in our AST format.
2964 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2965 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002966
Douglas Gregore7c20652011-03-02 00:47:37 +00002967 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002968 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002969 ElaboratedTypeKeyword Keyword
2970 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002971
Douglas Gregore7c20652011-03-02 00:47:37 +00002972 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2973 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00002974 DTN->getQualifier(),
2975 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00002976 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002977
2978 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00002979 TypeLocBuilder TLB;
2980 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002981 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2982 SpecTL.setElaboratedKeywordLoc(TagLoc);
2983 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002984 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002985 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002986 SpecTL.setLAngleLoc(LAngleLoc);
2987 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002988 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2989 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2990 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2991 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002992
2993 if (TypeAliasTemplateDecl *TAT =
2994 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2995 // C++0x [dcl.type.elab]p2:
2996 // If the identifier resolves to a typedef-name or the simple-template-id
2997 // resolves to an alias template specialization, the
2998 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00002999 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3000 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003001 Diag(TAT->getLocation(), diag::note_declared_at);
3002 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003003
Douglas Gregore7c20652011-03-02 00:47:37 +00003004 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3005 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003006 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003007
Douglas Gregore7c20652011-03-02 00:47:37 +00003008 // Check the tag kind
3009 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003010 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003011
John McCalld8fe9af2009-09-08 17:47:29 +00003012 IdentifierInfo *Id = D->getIdentifier();
3013 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003014
Richard Trieucaa33d32011-06-10 03:11:26 +00003015 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003016 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003017 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003018 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003019 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003020 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003021 }
3022 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003023
Douglas Gregore7c20652011-03-02 00:47:37 +00003024 // Provide source-location information for the template specialization.
3025 TypeLocBuilder TLB;
3026 TemplateSpecializationTypeLoc SpecTL
3027 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003028 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003029 SpecTL.setTemplateNameLoc(TemplateLoc);
3030 SpecTL.setLAngleLoc(LAngleLoc);
3031 SpecTL.setRAngleLoc(RAngleLoc);
3032 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3033 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003034
Douglas Gregore7c20652011-03-02 00:47:37 +00003035 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003036 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003037 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3038 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003039 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003040 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3041 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003042}
3043
Larisse Voufo39a1e502013-08-06 01:03:05 +00003044static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3045 NamedDecl *PrevDecl,
3046 SourceLocation Loc,
3047 bool IsPartialSpecialization);
3048
3049static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003050
Richard Smith300e0c32013-09-24 04:49:23 +00003051static bool isTemplateArgumentTemplateParameter(
3052 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3053 switch (Arg.getKind()) {
3054 case TemplateArgument::Null:
3055 case TemplateArgument::NullPtr:
3056 case TemplateArgument::Integral:
3057 case TemplateArgument::Declaration:
3058 case TemplateArgument::Pack:
3059 case TemplateArgument::TemplateExpansion:
3060 return false;
3061
3062 case TemplateArgument::Type: {
3063 QualType Type = Arg.getAsType();
3064 const TemplateTypeParmType *TPT =
3065 Arg.getAsType()->getAs<TemplateTypeParmType>();
3066 return TPT && !Type.hasQualifiers() &&
3067 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3068 }
3069
3070 case TemplateArgument::Expression: {
3071 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3072 if (!DRE || !DRE->getDecl())
3073 return false;
3074 const NonTypeTemplateParmDecl *NTTP =
3075 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3076 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3077 }
3078
3079 case TemplateArgument::Template:
3080 const TemplateTemplateParmDecl *TTP =
3081 dyn_cast_or_null<TemplateTemplateParmDecl>(
3082 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3083 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3084 }
3085 llvm_unreachable("unexpected kind of template argument");
3086}
3087
3088static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3089 ArrayRef<TemplateArgument> Args) {
3090 if (Params->size() != Args.size())
3091 return false;
3092
3093 unsigned Depth = Params->getDepth();
3094
3095 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3096 TemplateArgument Arg = Args[I];
3097
3098 // If the parameter is a pack expansion, the argument must be a pack
3099 // whose only element is a pack expansion.
3100 if (Params->getParam(I)->isParameterPack()) {
3101 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3102 !Arg.pack_begin()->isPackExpansion())
3103 return false;
3104 Arg = Arg.pack_begin()->getPackExpansionPattern();
3105 }
3106
3107 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3108 return false;
3109 }
3110
3111 return true;
3112}
3113
Richard Smith4b55a9c2014-04-17 03:29:33 +00003114/// Convert the parser's template argument list representation into our form.
3115static TemplateArgumentListInfo
3116makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3117 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3118 TemplateId.RAngleLoc);
3119 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3120 TemplateId.NumArgs);
3121 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3122 return TemplateArgs;
3123}
3124
Richard Smith0e617ec2016-12-27 07:56:27 +00003125template<typename PartialSpecDecl>
3126static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3127 if (Partial->getDeclContext()->isDependentContext())
3128 return;
3129
3130 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3131 // for non-substitution-failure issues?
3132 TemplateDeductionInfo Info(Partial->getLocation());
3133 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3134 return;
3135
3136 auto *Template = Partial->getSpecializedTemplate();
3137 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003138 diag::ext_partial_spec_not_more_specialized_than_primary)
3139 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003140
3141 if (Info.hasSFINAEDiagnostic()) {
3142 PartialDiagnosticAt Diag = {SourceLocation(),
3143 PartialDiagnostic::NullDiagnostic()};
3144 Info.takeSFINAEDiagnostic(Diag);
3145 SmallString<128> SFINAEArgString;
3146 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3147 S.Diag(Diag.first,
3148 diag::note_partial_spec_not_more_specialized_than_primary)
3149 << SFINAEArgString;
3150 }
3151
3152 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3153}
3154
Richard Smith57aae072016-12-28 02:37:25 +00003155template<typename PartialSpecDecl>
3156static void checkTemplatePartialSpecialization(Sema &S,
3157 PartialSpecDecl *Partial) {
3158 // C++1z [temp.class.spec]p8: (DR1495)
3159 // - The specialization shall be more specialized than the primary
3160 // template (14.5.5.2).
3161 checkMoreSpecializedThanPrimary(S, Partial);
3162
3163 // C++ [temp.class.spec]p8: (DR1315)
3164 // - Each template-parameter shall appear at least once in the
3165 // template-id outside a non-deduced context.
3166 // C++1z [temp.class.spec.match]p3 (P0127R2)
3167 // If the template arguments of a partial specialization cannot be
3168 // deduced because of the structure of its template-parameter-list
3169 // and the template-id, the program is ill-formed.
3170 auto *TemplateParams = Partial->getTemplateParameters();
3171 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3172 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3173 TemplateParams->getDepth(), DeducibleParams);
3174
3175 if (!DeducibleParams.all()) {
3176 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3177 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3178 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3179 << (NumNonDeducible > 1)
3180 << SourceRange(Partial->getLocation(),
3181 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3182 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3183 if (!DeducibleParams[I]) {
3184 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3185 if (Param->getDeclName())
3186 S.Diag(Param->getLocation(),
3187 diag::note_partial_spec_unused_parameter)
3188 << Param->getDeclName();
3189 else
3190 S.Diag(Param->getLocation(),
3191 diag::note_partial_spec_unused_parameter)
3192 << "(anonymous)";
3193 }
3194 }
3195 }
3196}
3197
3198void Sema::CheckTemplatePartialSpecialization(
3199 ClassTemplatePartialSpecializationDecl *Partial) {
3200 checkTemplatePartialSpecialization(*this, Partial);
3201}
3202
3203void Sema::CheckTemplatePartialSpecialization(
3204 VarTemplatePartialSpecializationDecl *Partial) {
3205 checkTemplatePartialSpecialization(*this, Partial);
3206}
3207
Larisse Voufo39a1e502013-08-06 01:03:05 +00003208DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003209 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003210 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003211 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003212 // D must be variable template id.
3213 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
3214 "Variable template specialization is declared with a template it.");
3215
3216 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003217 TemplateArgumentListInfo TemplateArgs =
3218 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003219 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3220 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3221 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003222
Richard Smithbeef3452014-01-16 23:39:20 +00003223 TemplateName Name = TemplateId->Template.get();
3224
3225 // The template-id must name a variable template.
3226 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003227 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3228 if (!VarTemplate) {
3229 NamedDecl *FnTemplate;
3230 if (auto *OTS = Name.getAsOverloadedTemplate())
3231 FnTemplate = *OTS->begin();
3232 else
3233 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3234 if (FnTemplate)
3235 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3236 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003237 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3238 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003239 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003240
3241 // Check for unexpanded parameter packs in any of the template arguments.
3242 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3243 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3244 UPPC_PartialSpecialization))
3245 return true;
3246
3247 // Check that the template argument list is well-formed for this
3248 // template.
3249 SmallVector<TemplateArgument, 4> Converted;
3250 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3251 false, Converted))
3252 return true;
3253
Larisse Voufo39a1e502013-08-06 01:03:05 +00003254 // Find the variable template (partial) specialization declaration that
3255 // corresponds to these arguments.
3256 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003257 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3258 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003259 return true;
3260
Richard Smith57aae072016-12-28 02:37:25 +00003261 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3262 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003263 bool InstantiationDependent;
3264 if (!Name.isDependent() &&
3265 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003266 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003267 InstantiationDependent)) {
3268 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3269 << VarTemplate->getDeclName();
3270 IsPartialSpecialization = false;
3271 }
Richard Smith300e0c32013-09-24 04:49:23 +00003272
3273 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3274 Converted)) {
3275 // C++ [temp.class.spec]p9b3:
3276 //
3277 // -- The argument list of the specialization shall not be identical
3278 // to the implicit argument list of the primary template.
3279 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3280 << /*variable template*/ 1
3281 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3282 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3283 // FIXME: Recover from this by treating the declaration as a redeclaration
3284 // of the primary template.
3285 return true;
3286 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003287 }
3288
Craig Topperc3ec1492014-05-26 06:22:03 +00003289 void *InsertPos = nullptr;
3290 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003291
3292 if (IsPartialSpecialization)
3293 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003294 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003295 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003296 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003297
Craig Topperc3ec1492014-05-26 06:22:03 +00003298 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003299
3300 // Check whether we can declare a variable template specialization in
3301 // the current scope.
3302 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3303 TemplateNameLoc,
3304 IsPartialSpecialization))
3305 return true;
3306
3307 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3308 // Since the only prior variable template specialization with these
3309 // arguments was referenced but not declared, reuse that
3310 // declaration node as our own, updating its source location and
3311 // the list of outer template parameters to reflect our new declaration.
3312 Specialization = PrevDecl;
3313 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003314 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003315 } else if (IsPartialSpecialization) {
3316 // Create a new class template partial specialization declaration node.
3317 VarTemplatePartialSpecializationDecl *PrevPartial =
3318 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003319 VarTemplatePartialSpecializationDecl *Partial =
3320 VarTemplatePartialSpecializationDecl::Create(
3321 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3322 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003323 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003324
3325 if (!PrevPartial)
3326 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3327 Specialization = Partial;
3328
3329 // If we are providing an explicit specialization of a member variable
3330 // template specialization, make a note of that.
3331 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003332 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003333
Richard Smith57aae072016-12-28 02:37:25 +00003334 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003335 } else {
3336 // Create a new class template specialization declaration node for
3337 // this explicit specialization or friend declaration.
3338 Specialization = VarTemplateSpecializationDecl::Create(
3339 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003340 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003341 Specialization->setTemplateArgsInfo(TemplateArgs);
3342
3343 if (!PrevDecl)
3344 VarTemplate->AddSpecialization(Specialization, InsertPos);
3345 }
3346
3347 // C++ [temp.expl.spec]p6:
3348 // If a template, a member template or the member of a class template is
3349 // explicitly specialized then that specialization shall be declared
3350 // before the first use of that specialization that would cause an implicit
3351 // instantiation to take place, in every translation unit in which such a
3352 // use occurs; no diagnostic is required.
3353 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3354 bool Okay = false;
3355 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3356 // Is there any previous explicit specialization declaration?
3357 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3358 Okay = true;
3359 break;
3360 }
3361 }
3362
3363 if (!Okay) {
3364 SourceRange Range(TemplateNameLoc, RAngleLoc);
3365 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3366 << Name << Range;
3367
3368 Diag(PrevDecl->getPointOfInstantiation(),
3369 diag::note_instantiation_required_here)
3370 << (PrevDecl->getTemplateSpecializationKind() !=
3371 TSK_ImplicitInstantiation);
3372 return true;
3373 }
3374 }
3375
3376 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3377 Specialization->setLexicalDeclContext(CurContext);
3378
3379 // Add the specialization into its lexical context, so that it can
3380 // be seen when iterating through the list of declarations in that
3381 // context. However, specializations are not found by name lookup.
3382 CurContext->addDecl(Specialization);
3383
3384 // Note that this is an explicit specialization.
3385 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3386
3387 if (PrevDecl) {
3388 // Check that this isn't a redefinition of this specialization,
3389 // merging with previous declarations.
3390 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3391 ForRedeclaration);
3392 PrevSpec.addDecl(PrevDecl);
3393 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003394 } else if (Specialization->isStaticDataMember() &&
3395 Specialization->isOutOfLine()) {
3396 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003397 }
3398
3399 // Link instantiations of static data members back to the template from
3400 // which they were instantiated.
3401 if (Specialization->isStaticDataMember())
3402 Specialization->setInstantiationOfStaticDataMember(
3403 VarTemplate->getTemplatedDecl(),
3404 Specialization->getSpecializationKind());
3405
3406 return Specialization;
3407}
3408
3409namespace {
3410/// \brief A partial specialization whose template arguments have matched
3411/// a given template-id.
3412struct PartialSpecMatchResult {
3413 VarTemplatePartialSpecializationDecl *Partial;
3414 TemplateArgumentList *Args;
3415};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003416} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003417
3418DeclResult
3419Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3420 SourceLocation TemplateNameLoc,
3421 const TemplateArgumentListInfo &TemplateArgs) {
3422 assert(Template && "A variable template id without template?");
3423
3424 // Check that the template argument list is well-formed for this template.
3425 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003426 if (CheckTemplateArgumentList(
3427 Template, TemplateNameLoc,
3428 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003429 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003430 return true;
3431
3432 // Find the variable template specialization declaration that
3433 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003434 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003435 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003436 Converted, InsertPos)) {
3437 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003438 // If we already have a variable template specialization, return it.
3439 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003440 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003441
3442 // This is the first time we have referenced this variable template
3443 // specialization. Create the canonical declaration and add it to
3444 // the set of specializations, based on the closest partial specialization
3445 // that it represents. That is,
3446 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3447 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003448 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003449 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3450 bool AmbiguousPartialSpec = false;
3451 typedef PartialSpecMatchResult MatchResult;
3452 SmallVector<MatchResult, 4> Matched;
3453 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003454 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3455 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003456
3457 // 1. Attempt to find the closest partial specialization that this
3458 // specializes, if any.
3459 // If any of the template arguments is dependent, then this is probably
3460 // a placeholder for an incomplete declarative context; which must be
3461 // complete by instantiation time. Thus, do not search through the partial
3462 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003463 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3464 // Perhaps better after unification of DeduceTemplateArguments() and
3465 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003466 bool InstantiationDependent = false;
3467 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3468 TemplateArgs, InstantiationDependent)) {
3469
3470 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3471 Template->getPartialSpecializations(PartialSpecs);
3472
3473 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3474 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3475 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3476
3477 if (TemplateDeductionResult Result =
3478 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3479 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003480 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003481 FailedCandidates.addCandidate().set(
3482 DeclAccessPair::make(Template, AS_public), Partial,
3483 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003484 (void)Result;
3485 } else {
3486 Matched.push_back(PartialSpecMatchResult());
3487 Matched.back().Partial = Partial;
3488 Matched.back().Args = Info.take();
3489 }
3490 }
3491
Larisse Voufo39a1e502013-08-06 01:03:05 +00003492 if (Matched.size() >= 1) {
3493 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3494 if (Matched.size() == 1) {
3495 // -- If exactly one matching specialization is found, the
3496 // instantiation is generated from that specialization.
3497 // We don't need to do anything for this.
3498 } else {
3499 // -- If more than one matching specialization is found, the
3500 // partial order rules (14.5.4.2) are used to determine
3501 // whether one of the specializations is more specialized
3502 // than the others. If none of the specializations is more
3503 // specialized than all of the other matching
3504 // specializations, then the use of the variable template is
3505 // ambiguous and the program is ill-formed.
3506 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3507 PEnd = Matched.end();
3508 P != PEnd; ++P) {
3509 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3510 PointOfInstantiation) ==
3511 P->Partial)
3512 Best = P;
3513 }
3514
3515 // Determine if the best partial specialization is more specialized than
3516 // the others.
3517 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3518 PEnd = Matched.end();
3519 P != PEnd; ++P) {
3520 if (P != Best && getMoreSpecializedPartialSpecialization(
3521 P->Partial, Best->Partial,
3522 PointOfInstantiation) != Best->Partial) {
3523 AmbiguousPartialSpec = true;
3524 break;
3525 }
3526 }
3527 }
3528
3529 // Instantiate using the best variable template partial specialization.
3530 InstantiationPattern = Best->Partial;
3531 InstantiationArgs = Best->Args;
3532 } else {
3533 // -- If no match is found, the instantiation is generated
3534 // from the primary template.
3535 // InstantiationPattern = Template->getTemplatedDecl();
3536 }
3537 }
3538
Larisse Voufo39a1e502013-08-06 01:03:05 +00003539 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00003540 // Note that we do not instantiate a definition until we see an odr-use
3541 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003542 // FIXME: LateAttrs et al.?
3543 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3544 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3545 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3546 if (!Decl)
3547 return true;
3548
3549 if (AmbiguousPartialSpec) {
3550 // Partial ordering did not produce a clear winner. Complain.
3551 Decl->setInvalidDecl();
3552 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3553 << Decl;
3554
3555 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00003556 for (MatchResult P : Matched)
3557 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3558 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3559 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003560 return true;
3561 }
3562
3563 if (VarTemplatePartialSpecializationDecl *D =
3564 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3565 Decl->setInstantiationOf(D, InstantiationArgs);
3566
Richard Smith6739a102016-05-05 00:56:12 +00003567 checkSpecializationVisibility(TemplateNameLoc, Decl);
3568
Larisse Voufo39a1e502013-08-06 01:03:05 +00003569 assert(Decl && "No variable template specialization?");
3570 return Decl;
3571}
3572
3573ExprResult
3574Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3575 const DeclarationNameInfo &NameInfo,
3576 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3577 const TemplateArgumentListInfo *TemplateArgs) {
3578
3579 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3580 *TemplateArgs);
3581 if (Decl.isInvalid())
3582 return ExprError();
3583
3584 VarDecl *Var = cast<VarDecl>(Decl.get());
3585 if (!Var->getTemplateSpecializationKind())
3586 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3587 NameInfo.getLoc());
3588
3589 // Build an ordinary singleton decl ref.
3590 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003591 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003592}
3593
John McCalldadc5752010-08-24 06:29:42 +00003594ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003595 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003596 LookupResult &R,
3597 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003598 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003599 // FIXME: Can we do any checking at this point? I guess we could check the
3600 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003601 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003602 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003603 // foo<int> could identify a single function unambiguously
3604 // This approach does NOT work, since f<int>(1);
3605 // gets resolved prior to resorting to overload resolution
3606 // i.e., template<class T> void f(double);
3607 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003608
3609 // These should be filtered out by our callers.
3610 assert(!R.empty() && "empty lookup results when building templateid");
3611 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3612
Larisse Voufo39a1e502013-08-06 01:03:05 +00003613 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003614 bool InstantiationDependent;
3615 if (R.getAsSingle<VarTemplateDecl>() &&
3616 !TemplateSpecializationType::anyDependentTemplateArguments(
3617 *TemplateArgs, InstantiationDependent)) {
3618 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3619 R.getAsSingle<VarTemplateDecl>(),
3620 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003621 }
3622
John McCall58cc69d2010-01-27 01:50:18 +00003623 // We don't want lookup warnings at this point.
3624 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003625
John McCalle66edc12009-11-24 19:00:30 +00003626 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003627 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003628 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003629 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003630 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003631 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003632 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003633
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003634 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003635}
3636
John McCalle66edc12009-11-24 19:00:30 +00003637// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003638ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003639Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003640 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003641 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003642 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003643
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003644 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003645 DeclContext *DC;
3646 if (!(DC = computeDeclContext(SS, false)) ||
3647 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003648 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003649 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003650
Douglas Gregor786123d2010-05-21 23:18:07 +00003651 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003652 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003653 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003654 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003655
John McCalle66edc12009-11-24 19:00:30 +00003656 if (R.isAmbiguous())
3657 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003658
John McCalle66edc12009-11-24 19:00:30 +00003659 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003660 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3661 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003662 return ExprError();
3663 }
3664
3665 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003666 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003667 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003668 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003669 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3670 return ExprError();
3671 }
3672
Abramo Bagnara7945c982012-01-27 09:46:47 +00003673 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003674}
3675
Douglas Gregorb67535d2009-03-31 00:43:58 +00003676/// \brief Form a dependent template name.
3677///
3678/// This action forms a dependent template name given the template
3679/// name and its (presumably dependent) scope specifier. For
3680/// example, given "MetaFun::template apply", the scope specifier \p
3681/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3682/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003683TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003684 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003685 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003686 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003687 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003688 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00003689 TemplateTy &Result,
3690 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003691 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3692 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003693 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003694 diag::warn_cxx98_compat_template_outside_of_template :
3695 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003696 << FixItHint::CreateRemoval(TemplateKWLoc);
3697
Craig Topperc3ec1492014-05-26 06:22:03 +00003698 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003699 if (SS.isSet())
3700 LookupCtx = computeDeclContext(SS, EnteringContext);
3701 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003702 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003703 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003704 // C++0x [temp.names]p5:
3705 // If a name prefixed by the keyword template is not the name of
3706 // a template, the program is ill-formed. [Note: the keyword
3707 // template may not be applied to non-template members of class
3708 // templates. -end note ] [ Note: as is the case with the
3709 // typename prefix, the template prefix is allowed in cases
3710 // where it is not strictly necessary; i.e., when the
3711 // nested-name-specifier or the expression on the left of the ->
3712 // or . is not dependent on a template-parameter, or the use
3713 // does not appear in the scope of a template. -end note]
3714 //
3715 // Note: C++03 was more strict here, because it banned the use of
3716 // the "template" keyword prior to a template-name that was not a
3717 // dependent name. C++ DR468 relaxed this requirement (the
3718 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003719 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003720 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003721 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003722 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003723 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003724 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3725 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003726 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3727 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003728 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003729 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003730 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003731 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003732 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003733 << Name.getSourceRange()
3734 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003735 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003736 } else {
3737 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00003738 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
3739 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
3740 Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
3741 LookupRD->getIdentifier() == Name.Identifier) {
3742 // C++14 [class.qual]p2:
3743 // In a lookup in which function names are not ignored and the
3744 // nested-name-specifier nominates a class C, if the name specified
3745 // [...] is the injected-class-name of C, [...] the name is instead
3746 // considered to name the constructor
3747 //
3748 // We don't get here if naming the constructor would be valid, so we
3749 // just reject immediately and recover by treating the
3750 // injected-class-name as naming the template.
3751 Diag(Name.getLocStart(),
3752 diag::ext_out_of_line_qualified_id_type_names_constructor)
3753 << Name.Identifier << 0 /*injected-class-name used as template name*/
3754 << 1 /*'template' keyword was used*/;
3755 }
Douglas Gregorbb119652010-06-16 23:00:59 +00003756 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003757 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003758 }
3759
Aaron Ballman4a979672014-01-03 13:56:08 +00003760 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761
Douglas Gregor3cf81312009-11-03 23:16:33 +00003762 switch (Name.getKind()) {
3763 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003765 Name.Identifier));
3766 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767
Douglas Gregor71395fa2009-11-04 00:56:37 +00003768 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003769 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003770 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003771 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003772
3773 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003774 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003775
Douglas Gregor3cf81312009-11-03 23:16:33 +00003776 default:
3777 break;
3778 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003779
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003780 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003781 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003782 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003783 << Name.getSourceRange()
3784 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003785 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003786}
3787
Mike Stump11289f42009-09-09 15:08:12 +00003788bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003789 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003790 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003791 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003792 QualType ArgType;
3793 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003794
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003795 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003796 switch(Arg.getKind()) {
3797 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003798 // C++ [temp.arg.type]p1:
3799 // A template-argument for a template-parameter which is a
3800 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003801 ArgType = Arg.getAsType();
3802 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003803 break;
3804 case TemplateArgument::Template: {
3805 // We have a template type parameter but the template argument
3806 // is a template without any arguments.
3807 SourceRange SR = AL.getSourceRange();
3808 TemplateName Name = Arg.getAsTemplate();
3809 Diag(SR.getBegin(), diag::err_template_missing_args)
Richard Smith0c062b42017-01-14 02:19:59 +00003810 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003811 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3812 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003813
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003814 return true;
3815 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003816 case TemplateArgument::Expression: {
3817 // We have a template type parameter but the template argument is an
3818 // expression; see if maybe it is missing the "typename" keyword.
3819 CXXScopeSpec SS;
3820 DeclarationNameInfo NameInfo;
3821
3822 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3823 SS.Adopt(ArgExpr->getQualifierLoc());
3824 NameInfo = ArgExpr->getNameInfo();
3825 } else if (DependentScopeDeclRefExpr *ArgExpr =
3826 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3827 SS.Adopt(ArgExpr->getQualifierLoc());
3828 NameInfo = ArgExpr->getNameInfo();
3829 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3830 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003831 if (ArgExpr->isImplicitAccess()) {
3832 SS.Adopt(ArgExpr->getQualifierLoc());
3833 NameInfo = ArgExpr->getMemberNameInfo();
3834 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003835 }
3836
Reid Kleckner377c1592014-06-10 23:29:48 +00003837 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003838 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3839 LookupParsedName(Result, CurScope, &SS);
3840
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003841 if (Result.getAsSingle<TypeDecl>() ||
3842 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003843 LookupResult::NotFoundInCurrentInstantiation) {
3844 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003845 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003846 Diag(Loc, getLangOpts().MSVCCompat
3847 ? diag::ext_ms_template_type_arg_missing_typename
3848 : diag::err_template_arg_must_be_type_suggest)
3849 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003850 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003851
3852 // Recover by synthesizing a type using the location information that we
3853 // already have.
3854 ArgType =
3855 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3856 TypeLocBuilder TLB;
3857 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3858 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3859 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3860 TL.setNameLoc(NameInfo.getLoc());
3861 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3862
3863 // Overwrite our input TemplateArgumentLoc so that we can recover
3864 // properly.
3865 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3866 TemplateArgumentLocInfo(TSI));
3867
3868 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003869 }
3870 }
3871 // fallthrough
3872 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003873 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003874 // We have a template type parameter but the template argument
3875 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003876 SourceRange SR = AL.getSourceRange();
3877 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003878 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003879
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003880 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003881 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003882 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003883
Reid Kleckner377c1592014-06-10 23:29:48 +00003884 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003885 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003886
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003887 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003888 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003889
Douglas Gregore46db902011-06-17 22:11:49 +00003890 // Objective-C ARC:
3891 // If an explicitly-specified template argument type is a lifetime type
3892 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003893 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003894 ArgType->isObjCLifetimeType() &&
3895 !ArgType.getObjCLifetime()) {
3896 Qualifiers Qs;
3897 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3898 ArgType = Context.getQualifiedType(ArgType, Qs);
3899 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003900
Douglas Gregore46db902011-06-17 22:11:49 +00003901 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003902 return false;
3903}
3904
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003905/// \brief Substitute template arguments into the default template argument for
3906/// the given template type parameter.
3907///
3908/// \param SemaRef the semantic analysis object for which we are performing
3909/// the substitution.
3910///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003911/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003912/// for.
3913///
3914/// \param TemplateLoc the location of the template name that started the
3915/// template-id we are checking.
3916///
3917/// \param RAngleLoc the location of the right angle bracket ('>') that
3918/// terminates the template-id.
3919///
3920/// \param Param the template template parameter whose default we are
3921/// substituting into.
3922///
3923/// \param Converted the list of template arguments provided for template
3924/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003925/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003926static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003927SubstDefaultTemplateArgument(Sema &SemaRef,
3928 TemplateDecl *Template,
3929 SourceLocation TemplateLoc,
3930 SourceLocation RAngleLoc,
3931 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003932 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003933 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003934
3935 // If the argument type is dependent, instantiate it now based
3936 // on the previously-computed template arguments.
3937 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003938 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003939 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003940 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003941 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003942 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943
David Majnemer8b622692016-07-03 21:17:51 +00003944 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003945
3946 // Only substitute for the innermost template argument list.
3947 MultiLevelTemplateArgumentList TemplateArgLists;
3948 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3949 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3950 TemplateArgLists.addOuterTemplateArguments(None);
3951
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003952 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003953 ArgType =
3954 SemaRef.SubstType(ArgType, TemplateArgLists,
3955 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003956 }
3957
3958 return ArgType;
3959}
3960
3961/// \brief Substitute template arguments into the default template argument for
3962/// the given non-type template parameter.
3963///
3964/// \param SemaRef the semantic analysis object for which we are performing
3965/// the substitution.
3966///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003967/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003968/// for.
3969///
3970/// \param TemplateLoc the location of the template name that started the
3971/// template-id we are checking.
3972///
3973/// \param RAngleLoc the location of the right angle bracket ('>') that
3974/// terminates the template-id.
3975///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003976/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003977/// substituting into.
3978///
3979/// \param Converted the list of template arguments provided for template
3980/// parameters that precede \p Param in the template parameter list.
3981///
3982/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003983static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003984SubstDefaultTemplateArgument(Sema &SemaRef,
3985 TemplateDecl *Template,
3986 SourceLocation TemplateLoc,
3987 SourceLocation RAngleLoc,
3988 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003989 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003990 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003991 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003992 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003993 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003994 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003995
David Majnemer8b622692016-07-03 21:17:51 +00003996 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003997
3998 // Only substitute for the innermost template argument list.
3999 MultiLevelTemplateArgumentList TemplateArgLists;
4000 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4001 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4002 TemplateArgLists.addOuterTemplateArguments(None);
4003
Faisal Vali48401eb2015-11-19 19:20:17 +00004004 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
4005 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004006 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004007}
4008
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004009/// \brief Substitute template arguments into the default template argument for
4010/// the given template template parameter.
4011///
4012/// \param SemaRef the semantic analysis object for which we are performing
4013/// the substitution.
4014///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004015/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004016/// for.
4017///
4018/// \param TemplateLoc the location of the template name that started the
4019/// template-id we are checking.
4020///
4021/// \param RAngleLoc the location of the right angle bracket ('>') that
4022/// terminates the template-id.
4023///
4024/// \param Param the template template parameter whose default we are
4025/// substituting into.
4026///
4027/// \param Converted the list of template arguments provided for template
4028/// parameters that precede \p Param in the template parameter list.
4029///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004030/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004031/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004032///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004033/// \returns the substituted template argument, or NULL if an error occurred.
4034static TemplateName
4035SubstDefaultTemplateArgument(Sema &SemaRef,
4036 TemplateDecl *Template,
4037 SourceLocation TemplateLoc,
4038 SourceLocation RAngleLoc,
4039 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004040 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004041 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004042 Sema::InstantiatingTemplate Inst(
4043 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4044 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004045 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004046 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004047
David Majnemer8b622692016-07-03 21:17:51 +00004048 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004049
4050 // Only substitute for the innermost template argument list.
4051 MultiLevelTemplateArgumentList TemplateArgLists;
4052 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4053 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4054 TemplateArgLists.addOuterTemplateArguments(None);
4055
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004056 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004057 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004058 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004059 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004060 QualifierLoc =
4061 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004062 if (!QualifierLoc)
4063 return TemplateName();
4064 }
David Majnemer89189202013-08-28 23:48:32 +00004065
4066 return SemaRef.SubstTemplateName(
4067 QualifierLoc,
4068 Param->getDefaultArgument().getArgument().getAsTemplate(),
4069 Param->getDefaultArgument().getTemplateNameLoc(),
4070 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004071}
4072
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004073/// \brief If the given template parameter has a default template
4074/// argument, substitute into that default template argument and
4075/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004076TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004077Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4078 SourceLocation TemplateLoc,
4079 SourceLocation RAngleLoc,
4080 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004081 SmallVectorImpl<TemplateArgument>
4082 &Converted,
4083 bool &HasDefaultArg) {
4084 HasDefaultArg = false;
4085
4086 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004087 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004088 return TemplateArgumentLoc();
4089
Richard Smithc87b9382013-07-04 01:01:24 +00004090 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004091 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004092 TemplateLoc,
4093 RAngleLoc,
4094 TypeParm,
4095 Converted);
4096 if (DI)
4097 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4098
4099 return TemplateArgumentLoc();
4100 }
4101
4102 if (NonTypeTemplateParmDecl *NonTypeParm
4103 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004104 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004105 return TemplateArgumentLoc();
4106
Richard Smithc87b9382013-07-04 01:01:24 +00004107 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004108 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004109 TemplateLoc,
4110 RAngleLoc,
4111 NonTypeParm,
4112 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004113 if (Arg.isInvalid())
4114 return TemplateArgumentLoc();
4115
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004116 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004117 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4118 }
4119
4120 TemplateTemplateParmDecl *TempTempParm
4121 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004122 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004123 return TemplateArgumentLoc();
4124
Richard Smithc87b9382013-07-04 01:01:24 +00004125 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004126 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004127 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004128 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004129 RAngleLoc,
4130 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004131 Converted,
4132 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004133 if (TName.isNull())
4134 return TemplateArgumentLoc();
4135
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004136 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004137 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004138 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4139}
4140
Richard Smith11255ec2017-01-18 19:19:22 +00004141/// Convert a template-argument that we parsed as a type into a template, if
4142/// possible. C++ permits injected-class-names to perform dual service as
4143/// template template arguments and as template type arguments.
4144static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4145 // Extract and step over any surrounding nested-name-specifier.
4146 NestedNameSpecifierLoc QualLoc;
4147 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4148 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4149 return TemplateArgumentLoc();
4150
4151 QualLoc = ETLoc.getQualifierLoc();
4152 TLoc = ETLoc.getNamedTypeLoc();
4153 }
4154
4155 // If this type was written as an injected-class-name, it can be used as a
4156 // template template argument.
4157 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4158 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4159 QualLoc, InjLoc.getNameLoc());
4160
4161 // If this type was written as an injected-class-name, it may have been
4162 // converted to a RecordType during instantiation. If the RecordType is
4163 // *not* wrapped in a TemplateSpecializationType and denotes a class
4164 // template specialization, it must have come from an injected-class-name.
4165 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4166 if (auto *CTSD =
4167 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4168 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4169 QualLoc, RecLoc.getNameLoc());
4170
4171 return TemplateArgumentLoc();
4172}
4173
Douglas Gregorda0fb532009-11-11 19:31:23 +00004174/// \brief Check that the given template argument corresponds to the given
4175/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004176///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004177/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004178/// checked.
4179///
Richard Trieu15b66532015-01-24 02:48:32 +00004180/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004181///
4182/// \param Template The template in which the template argument resides.
4183///
4184/// \param TemplateLoc The location of the template name for the template
4185/// whose argument list we're matching.
4186///
4187/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4188/// the template argument list.
4189///
4190/// \param ArgumentPackIndex The index into the argument pack where this
4191/// argument will be placed. Only valid if the parameter is a parameter pack.
4192///
4193/// \param Converted The checked, converted argument will be added to the
4194/// end of this small vector.
4195///
4196/// \param CTAK Describes how we arrived at this particular template argument:
4197/// explicitly written, deduced, etc.
4198///
4199/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004200bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004201 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004202 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004203 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004204 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004205 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004206 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004207 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004208 // Check template type parameters.
4209 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004210 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211
Douglas Gregoreebed722009-11-11 19:41:09 +00004212 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004213 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004214 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004215 // with the template arguments we've seen thus far. But if the
4216 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004217 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004218 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4219 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004220
Peter Collingbourne01687632010-12-10 17:08:53 +00004221 if (NTTPType->isDependentType() &&
4222 !isa<TemplateTemplateParmDecl>(Template) &&
4223 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004224 // Do substitution on the type of the non-type template parameter.
4225 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004226 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004227 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004228 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004229 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004230
4231 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004232 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004233 NTTPType = SubstType(NTTPType,
4234 MultiLevelTemplateArgumentList(TemplateArgs),
4235 NTTP->getLocation(),
4236 NTTP->getDeclName());
4237 // If that worked, check the non-type template parameter type
4238 // for validity.
4239 if (!NTTPType.isNull())
4240 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4241 NTTP->getLocation());
4242 if (NTTPType.isNull())
4243 return true;
4244 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004245
Douglas Gregorda0fb532009-11-11 19:31:23 +00004246 switch (Arg.getArgument().getKind()) {
4247 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004248 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004249
Douglas Gregorda0fb532009-11-11 19:31:23 +00004250 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004251 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00004252 ExprResult Res =
4253 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4254 Result, CTAK);
4255 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004256 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257
Richard Trieu15b66532015-01-24 02:48:32 +00004258 // If the resulting expression is new, then use it in place of the
4259 // old expression in the template argument.
4260 if (Res.get() != Arg.getArgument().getAsExpr()) {
4261 TemplateArgument TA(Res.get());
4262 Arg = TemplateArgumentLoc(TA, Res.get());
4263 }
4264
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004265 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004266 break;
4267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
Douglas Gregorda0fb532009-11-11 19:31:23 +00004269 case TemplateArgument::Declaration:
4270 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004271 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004272 // We've already checked this template argument, so just copy
4273 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004274 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004275 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004276
Douglas Gregorda0fb532009-11-11 19:31:23 +00004277 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004278 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004279 // We were given a template template argument. It may not be ill-formed;
4280 // see below.
4281 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004282 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4283 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004284 // We have a template argument such as \c T::template X, which we
4285 // parsed as a template template argument. However, since we now
4286 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004287 // template name into an expression.
4288
4289 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4290 Arg.getTemplateNameLoc());
4291
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004292 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004293 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004294 // FIXME: the template-template arg was a DependentTemplateName,
4295 // so it was provided with a template keyword. However, its source
4296 // location is not stored in the template argument structure.
4297 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004298 ExprResult E = DependentScopeDeclRefExpr::Create(
4299 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4300 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004302 // If we parsed the template argument as a pack expansion, create a
4303 // pack expansion expression.
4304 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004305 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004306 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004307 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004309
Douglas Gregorda0fb532009-11-11 19:31:23 +00004310 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004311 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004312 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004313 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004315 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004316 break;
4317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318
Douglas Gregorda0fb532009-11-11 19:31:23 +00004319 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004320 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004321 // therefore cannot be a non-type template argument.
4322 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4323 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004324
Douglas Gregorda0fb532009-11-11 19:31:23 +00004325 Diag(Param->getLocation(), diag::note_template_param_here);
4326 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327
Douglas Gregorda0fb532009-11-11 19:31:23 +00004328 case TemplateArgument::Type: {
4329 // We have a non-type template parameter but the template
4330 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004331
Douglas Gregorda0fb532009-11-11 19:31:23 +00004332 // C++ [temp.arg]p2:
4333 // In a template-argument, an ambiguity between a type-id and
4334 // an expression is resolved to a type-id, regardless of the
4335 // form of the corresponding template-parameter.
4336 //
4337 // We warn specifically about this case, since it can be rather
4338 // confusing for users.
4339 QualType T = Arg.getArgument().getAsType();
4340 SourceRange SR = Arg.getSourceRange();
4341 if (T->isFunctionType())
4342 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4343 else
4344 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4345 Diag(Param->getLocation(), diag::note_template_param_here);
4346 return true;
4347 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348
Douglas Gregorda0fb532009-11-11 19:31:23 +00004349 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004350 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004351 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004352
Douglas Gregorda0fb532009-11-11 19:31:23 +00004353 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004354 }
4355
4356
Douglas Gregorda0fb532009-11-11 19:31:23 +00004357 // Check template template parameters.
4358 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004359
Douglas Gregorda0fb532009-11-11 19:31:23 +00004360 // Substitute into the template parameter list of the template
4361 // template parameter, since previously-supplied template arguments
4362 // may appear within the template template parameter.
4363 {
4364 // Set up a template instantiation context.
4365 LocalInstantiationScope Scope(*this);
4366 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004367 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004368 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004369 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004370 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371
David Majnemer8b622692016-07-03 21:17:51 +00004372 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004373 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004374 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004375 MultiLevelTemplateArgumentList(TemplateArgs)));
4376 if (!TempParm)
4377 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004379
Richard Smith11255ec2017-01-18 19:19:22 +00004380 // C++1z [temp.local]p1: (DR1004)
4381 // When [the injected-class-name] is used [...] as a template-argument for
4382 // a template template-parameter [...] it refers to the class template
4383 // itself.
4384 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4385 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4386 Arg.getTypeSourceInfo()->getTypeLoc());
4387 if (!ConvertedArg.getArgument().isNull())
4388 Arg = ConvertedArg;
4389 }
4390
Douglas Gregorda0fb532009-11-11 19:31:23 +00004391 switch (Arg.getArgument().getKind()) {
4392 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004393 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394
Douglas Gregorda0fb532009-11-11 19:31:23 +00004395 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004396 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00004397 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004398 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004400 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004401 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402
Douglas Gregorda0fb532009-11-11 19:31:23 +00004403 case TemplateArgument::Expression:
4404 case TemplateArgument::Type:
4405 // We have a template template parameter but the template
4406 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004407 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004408 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004409 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410
Douglas Gregorda0fb532009-11-11 19:31:23 +00004411 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004412 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004413 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004414 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004415 case TemplateArgument::NullPtr:
4416 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417
Douglas Gregorda0fb532009-11-11 19:31:23 +00004418 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004419 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004420 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004421
Douglas Gregorda0fb532009-11-11 19:31:23 +00004422 return false;
4423}
4424
Simon Pilgrim6905d222016-12-30 22:55:33 +00004425/// \brief Diagnose an arity mismatch in the
Douglas Gregor8e072612012-02-03 07:34:46 +00004426static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4427 SourceLocation TemplateLoc,
4428 TemplateArgumentListInfo &TemplateArgs) {
4429 TemplateParameterList *Params = Template->getTemplateParameters();
4430 unsigned NumParams = Params->size();
4431 unsigned NumArgs = TemplateArgs.size();
4432
4433 SourceRange Range;
4434 if (NumArgs > NumParams)
Simon Pilgrim6905d222016-12-30 22:55:33 +00004435 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
Douglas Gregor8e072612012-02-03 07:34:46 +00004436 TemplateArgs.getRAngleLoc());
4437 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4438 << (NumArgs > NumParams)
Richard Smith0c062b42017-01-14 02:19:59 +00004439 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
Douglas Gregor8e072612012-02-03 07:34:46 +00004440 << Template << Range;
4441 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4442 << Params->getSourceRange();
4443 return true;
4444}
4445
Richard Smith1fde8ec2012-09-07 02:06:42 +00004446/// \brief Check whether the template parameter is a pack expansion, and if so,
4447/// determine the number of parameters produced by that expansion. For instance:
4448///
4449/// \code
4450/// template<typename ...Ts> struct A {
4451/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4452/// };
4453/// \endcode
4454///
4455/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4456/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004457static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004458 if (NonTypeTemplateParmDecl *NTTP
4459 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4460 if (NTTP->isExpandedParameterPack())
4461 return NTTP->getNumExpansionTypes();
4462 }
4463
4464 if (TemplateTemplateParmDecl *TTP
4465 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4466 if (TTP->isExpandedParameterPack())
4467 return TTP->getNumExpansionTemplateParameters();
4468 }
4469
David Blaikie7a30dc52013-02-21 01:47:18 +00004470 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00004471}
4472
Richard Smith35c1df52015-06-17 20:16:32 +00004473/// Diagnose a missing template argument.
4474template<typename TemplateParmDecl>
4475static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4476 TemplateDecl *TD,
4477 const TemplateParmDecl *D,
4478 TemplateArgumentListInfo &Args) {
4479 // Dig out the most recent declaration of the template parameter; there may be
4480 // declarations of the template that are more recent than TD.
4481 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4482 ->getTemplateParameters()
4483 ->getParam(D->getIndex()));
4484
4485 // If there's a default argument that's not visible, diagnose that we're
4486 // missing a module import.
4487 llvm::SmallVector<Module*, 8> Modules;
4488 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4489 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4490 D->getDefaultArgumentLoc(), Modules,
4491 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00004492 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00004493 return true;
4494 }
4495
4496 // FIXME: If there's a more recent default argument that *is* visible,
4497 // diagnose that it was declared too late.
4498
4499 return diagnoseArityMismatch(S, TD, Loc, Args);
4500}
4501
Douglas Gregord32e0282009-02-09 23:23:08 +00004502/// \brief Check that the given template argument list is well-formed
4503/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00004504bool Sema::CheckTemplateArgumentList(
4505 TemplateDecl *Template, SourceLocation TemplateLoc,
4506 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4507 SmallVectorImpl<TemplateArgument> &Converted,
4508 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00004509 // Make a copy of the template arguments for processing. Only make the
4510 // changes at the end when successful in matching the arguments to the
4511 // template.
4512 TemplateArgumentListInfo NewArgs = TemplateArgs;
4513
Douglas Gregord32e0282009-02-09 23:23:08 +00004514 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00004515
Richard Trieu15b66532015-01-24 02:48:32 +00004516 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00004517
Mike Stump11289f42009-09-09 15:08:12 +00004518 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00004519 // [...] The type and form of each template-argument specified in
4520 // a template-id shall match the type and form specified for the
4521 // corresponding parameter declared by the template in its
4522 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00004523 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004524 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00004525 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00004526 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00004527 for (TemplateParameterList::iterator Param = Params->begin(),
4528 ParamEnd = Params->end();
4529 Param != ParamEnd; /* increment in loop */) {
4530 // If we have an expanded parameter pack, make sure we don't have too
4531 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00004532 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004533 if (*Expansions == ArgumentPack.size()) {
4534 // We're done with this parameter pack. Pack up its arguments and add
4535 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00004536 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00004537 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004538 ArgumentPack.clear();
4539
Richard Smith1fde8ec2012-09-07 02:06:42 +00004540 // This argument is assigned to the next parameter.
4541 ++Param;
4542 continue;
4543 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4544 // Not enough arguments for this parameter pack.
4545 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4546 << false
Richard Smith0c062b42017-01-14 02:19:59 +00004547 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00004548 << Template;
4549 Diag(Template->getLocation(), diag::note_template_decl_here)
4550 << Params->getSourceRange();
4551 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004552 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004553 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554
Richard Smith1fde8ec2012-09-07 02:06:42 +00004555 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00004556 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00004557 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004558 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004559 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00004560 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561
Richard Smith96d71c32014-11-12 23:38:38 +00004562 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00004563 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00004564 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4565 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00004566 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00004567 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00004568 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00004569 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00004570 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00004571 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00004572 Diag((*Param)->getLocation(), diag::note_template_param_here);
4573 return true;
4574 }
4575
Richard Smith1fde8ec2012-09-07 02:06:42 +00004576 // We're now done with this argument.
4577 ++ArgIdx;
4578
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004579 if ((*Param)->isTemplateParameterPack()) {
4580 // The template parameter was a template parameter pack, so take the
4581 // deduced argument and place it on the argument pack. Note that we
4582 // stay on the same template parameter so that we can deduce more
4583 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004584 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004585 } else {
4586 // Move to the next template parameter.
4587 ++Param;
4588 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004589
Richard Smith96d71c32014-11-12 23:38:38 +00004590 // If we just saw a pack expansion into a non-pack, then directly convert
4591 // the remaining arguments, because we don't know what parameters they'll
4592 // match up with.
4593 if (PackExpansionIntoNonPack) {
4594 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004595 // If we were part way through filling in an expanded parameter pack,
4596 // fall back to just producing individual arguments.
4597 Converted.insert(Converted.end(),
4598 ArgumentPack.begin(), ArgumentPack.end());
4599 ArgumentPack.clear();
4600 }
4601
4602 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00004603 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00004604 ++ArgIdx;
4605 }
4606
Richard Smith1fde8ec2012-09-07 02:06:42 +00004607 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00004608 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004609
Douglas Gregor84d49a22009-11-11 21:54:23 +00004610 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004612
Douglas Gregor2f157c92011-06-03 02:59:40 +00004613 // If we're checking a partial template argument list, we're done.
4614 if (PartialTemplateArgs) {
4615 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00004616 Converted.push_back(
4617 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4618
Richard Smith1fde8ec2012-09-07 02:06:42 +00004619 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00004620 }
4621
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004622 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004623 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00004624 if ((*Param)->isTemplateParameterPack()) {
4625 assert(!getExpandedPackSize(*Param) &&
4626 "Should have dealt with this already");
4627
4628 // A non-expanded parameter pack before the end of the parameter list
4629 // only occurs for an ill-formed template parameter list, unless we've
4630 // got a partial argument list for a function template, so just bail out.
4631 if (Param + 1 != ParamEnd)
4632 return true;
4633
Benjamin Kramercce63472015-08-05 09:40:22 +00004634 Converted.push_back(
4635 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004636 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00004637
4638 ++Param;
4639 continue;
4640 }
4641
Douglas Gregor8e072612012-02-03 07:34:46 +00004642 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00004643 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004644
Douglas Gregor84d49a22009-11-11 21:54:23 +00004645 // Retrieve the default template argument from the template
4646 // parameter. For each kind of template parameter, we substitute the
4647 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004648 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004649 // the default argument.
4650 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004651 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004652 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4653 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004654
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004655 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004656 Template,
4657 TemplateLoc,
4658 RAngleLoc,
4659 TTP,
4660 Converted);
4661 if (!ArgType)
4662 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004663
Douglas Gregor84d49a22009-11-11 21:54:23 +00004664 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4665 ArgType);
4666 } else if (NonTypeTemplateParmDecl *NTTP
4667 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004668 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004669 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4670 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004671
John McCalldadc5752010-08-24 06:29:42 +00004672 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673 TemplateLoc,
4674 RAngleLoc,
4675 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004676 Converted);
4677 if (E.isInvalid())
4678 return true;
4679
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004680 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004681 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4682 } else {
4683 TemplateTemplateParmDecl *TempParm
4684 = cast<TemplateTemplateParmDecl>(*Param);
4685
Richard Smith95d83952015-06-10 20:36:34 +00004686 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004687 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4688 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004689
Douglas Gregordf846d12011-03-02 18:46:51 +00004690 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004691 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004692 TemplateLoc,
4693 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004694 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004695 Converted,
4696 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004697 if (Name.isNull())
4698 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004699
Douglas Gregor9d802122011-03-02 17:09:35 +00004700 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4701 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004702 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004703
Douglas Gregor84d49a22009-11-11 21:54:23 +00004704 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00004705 // the default template argument. We're not actually instantiating a
4706 // template here, we just create this object to put a note into the
4707 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004708 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4709 SourceRange(TemplateLoc, RAngleLoc));
4710 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004711 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004712
Douglas Gregor84d49a22009-11-11 21:54:23 +00004713 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004714 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004715 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004716 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004717
Richard Trieu15b66532015-01-24 02:48:32 +00004718 // Core issue 150 (assumed resolution): if this is a template template
4719 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004720 // template definition.
4721 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004722 NewArgs.addArgument(Arg);
4723
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004724 // Move to the next template parameter and argument.
4725 ++Param;
4726 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004728
Richard Smith07f79912014-06-06 16:00:50 +00004729 // If we're performing a partial argument substitution, allow any trailing
4730 // pack expansions; they might be empty. This can happen even if
4731 // PartialTemplateArgs is false (the list of arguments is complete but
4732 // still dependent).
4733 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4734 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004735 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4736 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004737 }
4738
Douglas Gregor8e072612012-02-03 07:34:46 +00004739 // If we have any leftover arguments, then there were too many arguments.
4740 // Complain and fail.
4741 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004742 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4743
4744 // No problems found with the new argument list, propagate changes back
4745 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00004746 if (UpdateArgsWithConversions)
4747 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004748
Richard Smith1fde8ec2012-09-07 02:06:42 +00004749 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004750}
4751
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004752namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004753 class UnnamedLocalNoLinkageFinder
4754 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004755 {
4756 Sema &S;
4757 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004758
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004759 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004761 public:
4762 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4763
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004764 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00004765 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004767
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004768#define TYPE(Class, Parent) \
4769 bool Visit##Class##Type(const Class##Type *);
4770#define ABSTRACT_TYPE(Class, Parent) \
4771 bool Visit##Class##Type(const Class##Type *) { return false; }
4772#define NON_CANONICAL_TYPE(Class, Parent) \
4773 bool Visit##Class##Type(const Class##Type *) { return false; }
4774#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004775
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004776 bool VisitTagDecl(const TagDecl *Tag);
4777 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4778 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004779} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004780
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004781bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004782 return false;
4783}
4784
4785bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4786 return Visit(T->getElementType());
4787}
4788
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004789bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004790 return Visit(T->getPointeeType());
4791}
4792
4793bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004794 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004795 return Visit(T->getPointeeType());
4796}
4797
4798bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004799 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004800 return Visit(T->getPointeeType());
4801}
4802
4803bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004804 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004805 return Visit(T->getPointeeType());
4806}
4807
4808bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004809 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004810 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4811}
4812
4813bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004814 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004815 return Visit(T->getElementType());
4816}
4817
4818bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004819 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004820 return Visit(T->getElementType());
4821}
4822
4823bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004824 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004825 return Visit(T->getElementType());
4826}
4827
4828bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004829 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004830 return Visit(T->getElementType());
4831}
4832
4833bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004834 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004835 return Visit(T->getElementType());
4836}
4837
4838bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4839 return Visit(T->getElementType());
4840}
4841
4842bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4843 return Visit(T->getElementType());
4844}
4845
4846bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4847 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004848 for (const auto &A : T->param_types()) {
4849 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004850 return true;
4851 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004852
Alp Toker314cc812014-01-25 16:55:45 +00004853 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004854}
4855
4856bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4857 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004858 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004859}
4860
4861bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4862 const UnresolvedUsingType*) {
4863 return false;
4864}
4865
4866bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4867 return false;
4868}
4869
4870bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4871 return Visit(T->getUnderlyingType());
4872}
4873
4874bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4875 return false;
4876}
4877
Alexis Hunte852b102011-05-24 22:41:36 +00004878bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4879 const UnaryTransformType*) {
4880 return false;
4881}
4882
Richard Smith30482bc2011-02-20 03:19:35 +00004883bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4884 return Visit(T->getDeducedType());
4885}
4886
Richard Smith600b5262017-01-26 20:40:47 +00004887bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
4888 const DeducedTemplateSpecializationType *T) {
4889 return Visit(T->getDeducedType());
4890}
4891
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004892bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4893 return VisitTagDecl(T->getDecl());
4894}
4895
4896bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4897 return VisitTagDecl(T->getDecl());
4898}
4899
4900bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4901 const TemplateTypeParmType*) {
4902 return false;
4903}
4904
Douglas Gregorada4b792011-01-14 02:55:32 +00004905bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4906 const SubstTemplateTypeParmPackType *) {
4907 return false;
4908}
4909
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004910bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4911 const TemplateSpecializationType*) {
4912 return false;
4913}
4914
4915bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4916 const InjectedClassNameType* T) {
4917 return VisitTagDecl(T->getDecl());
4918}
4919
4920bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4921 const DependentNameType* T) {
4922 return VisitNestedNameSpecifier(T->getQualifier());
4923}
4924
4925bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4926 const DependentTemplateSpecializationType* T) {
4927 return VisitNestedNameSpecifier(T->getQualifier());
4928}
4929
Douglas Gregord2fa7662010-12-20 02:24:11 +00004930bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4931 const PackExpansionType* T) {
4932 return Visit(T->getPattern());
4933}
4934
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004935bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4936 return false;
4937}
4938
4939bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4940 const ObjCInterfaceType *) {
4941 return false;
4942}
4943
4944bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4945 const ObjCObjectPointerType *) {
4946 return false;
4947}
4948
Eli Friedman0dfb8892011-10-06 23:00:33 +00004949bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4950 return Visit(T->getValueType());
4951}
4952
Xiuli Pan9c14e282016-01-09 12:53:17 +00004953bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4954 return false;
4955}
4956
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004957bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4958 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004959 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004960 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004961 diag::warn_cxx98_compat_template_arg_local_type :
4962 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004963 << S.Context.getTypeDeclType(Tag) << SR;
4964 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004965 }
4966
John McCall5ea95772013-03-09 00:54:27 +00004967 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004968 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004969 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004970 diag::warn_cxx98_compat_template_arg_unnamed_type :
4971 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004972 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4973 return true;
4974 }
4975
4976 return false;
4977}
4978
4979bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4980 NestedNameSpecifier *NNS) {
4981 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4982 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004983
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004984 switch (NNS->getKind()) {
4985 case NestedNameSpecifier::Identifier:
4986 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004987 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004988 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004989 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004990 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004991
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004992 case NestedNameSpecifier::TypeSpec:
4993 case NestedNameSpecifier::TypeSpecWithTemplate:
4994 return Visit(QualType(NNS->getAsType(), 0));
4995 }
David Blaikie8a40f702012-01-17 06:56:22 +00004996 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004997}
4998
Douglas Gregord32e0282009-02-09 23:23:08 +00004999/// \brief Check a template argument against its corresponding
5000/// template type parameter.
5001///
5002/// This routine implements the semantics of C++ [temp.arg.type]. It
5003/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005004bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005005 TypeSourceInfo *ArgInfo) {
5006 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005007 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005008 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005009
5010 if (Arg->isVariablyModifiedType()) {
5011 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005012 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005013 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005014 }
5015
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005016 // C++03 [temp.arg.type]p2:
5017 // A local type, a type with no linkage, an unnamed type or a type
5018 // compounded from any of these types shall not be used as a
5019 // template-argument for a template type-parameter.
5020 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005021 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005022 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005023 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005024 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5025 (void)Finder.Visit(Context.getCanonicalType(Arg));
5026 }
5027
Douglas Gregord32e0282009-02-09 23:23:08 +00005028 return false;
5029}
5030
Douglas Gregor20fdef32012-04-10 17:08:25 +00005031enum NullPointerValueKind {
5032 NPV_NotNullPointer,
5033 NPV_NullPointer,
5034 NPV_Error
5035};
5036
5037/// \brief Determine whether the given template argument is a null pointer
5038/// value of the appropriate type.
5039static NullPointerValueKind
5040isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5041 QualType ParamType, Expr *Arg) {
5042 if (Arg->isValueDependent() || Arg->isTypeDependent())
5043 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005044
Richard Smithdb0ac552015-12-18 22:40:25 +00005045 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005046 llvm_unreachable(
5047 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005048
David Majnemer5c734ad2014-08-14 00:49:23 +00005049 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005050 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005051
Douglas Gregor20fdef32012-04-10 17:08:25 +00005052 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005053 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5054 if (ArgRV.isInvalid())
5055 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005056 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005057
Douglas Gregor20fdef32012-04-10 17:08:25 +00005058 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005059 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005060 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005061 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005062 EvalResult.HasSideEffects) {
5063 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005064
Douglas Gregor350880c2012-04-10 19:03:30 +00005065 // If our only note is the usual "invalid subexpression" note, just point
5066 // the caret at its location rather than producing an essentially
5067 // redundant note.
5068 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5069 diag::note_invalid_subexpr_in_const_expr) {
5070 DiagLoc = Notes[0].first;
5071 Notes.clear();
5072 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005073
Douglas Gregor350880c2012-04-10 19:03:30 +00005074 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5075 << Arg->getType() << Arg->getSourceRange();
5076 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5077 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005078
Douglas Gregor350880c2012-04-10 19:03:30 +00005079 S.Diag(Param->getLocation(), diag::note_template_param_here);
5080 return NPV_Error;
5081 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005082
Douglas Gregor20fdef32012-04-10 17:08:25 +00005083 // C++11 [temp.arg.nontype]p1:
5084 // - an address constant expression of type std::nullptr_t
5085 if (Arg->getType()->isNullPtrType())
5086 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005087
Douglas Gregor20fdef32012-04-10 17:08:25 +00005088 // - a constant expression that evaluates to a null pointer value (4.10); or
5089 // - a constant expression that evaluates to a null member pointer value
5090 // (4.11); or
5091 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5092 (EvalResult.Val.isMemberPointer() &&
5093 !EvalResult.Val.getMemberPointerDecl())) {
5094 // If our expression has an appropriate type, we've succeeded.
5095 bool ObjCLifetimeConversion;
5096 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5097 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5098 ObjCLifetimeConversion))
5099 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005100
Douglas Gregor20fdef32012-04-10 17:08:25 +00005101 // The types didn't match, but we know we got a null pointer; complain,
5102 // then recover as if the types were correct.
5103 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5104 << Arg->getType() << ParamType << Arg->getSourceRange();
5105 S.Diag(Param->getLocation(), diag::note_template_param_here);
5106 return NPV_NullPointer;
5107 }
5108
5109 // If we don't have a null pointer value, but we do have a NULL pointer
5110 // constant, suggest a cast to the appropriate type.
5111 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5112 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5113 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005114 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5115 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5116 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005117 S.Diag(Param->getLocation(), diag::note_template_param_here);
5118 return NPV_NullPointer;
5119 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005120
Douglas Gregor20fdef32012-04-10 17:08:25 +00005121 // FIXME: If we ever want to support general, address-constant expressions
5122 // as non-type template arguments, we should return the ExprResult here to
5123 // be interpreted by the caller.
5124 return NPV_NotNullPointer;
5125}
5126
David Majnemer61c39a12013-08-23 05:39:39 +00005127/// \brief Checks whether the given template argument is compatible with its
5128/// template parameter.
5129static bool CheckTemplateArgumentIsCompatibleWithParameter(
5130 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5131 Expr *Arg, QualType ArgType) {
5132 bool ObjCLifetimeConversion;
5133 if (ParamType->isPointerType() &&
5134 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5135 S.IsQualificationConversion(ArgType, ParamType, false,
5136 ObjCLifetimeConversion)) {
5137 // For pointer-to-object types, qualification conversions are
5138 // permitted.
5139 } else {
5140 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5141 if (!ParamRef->getPointeeType()->isFunctionType()) {
5142 // C++ [temp.arg.nontype]p5b3:
5143 // For a non-type template-parameter of type reference to
5144 // object, no conversions apply. The type referred to by the
5145 // reference may be more cv-qualified than the (otherwise
5146 // identical) type of the template- argument. The
5147 // template-parameter is bound directly to the
5148 // template-argument, which shall be an lvalue.
5149
5150 // FIXME: Other qualifiers?
5151 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5152 unsigned ArgQuals = ArgType.getCVRQualifiers();
5153
5154 if ((ParamQuals | ArgQuals) != ParamQuals) {
5155 S.Diag(Arg->getLocStart(),
5156 diag::err_template_arg_ref_bind_ignores_quals)
5157 << ParamType << Arg->getType() << Arg->getSourceRange();
5158 S.Diag(Param->getLocation(), diag::note_template_param_here);
5159 return true;
5160 }
5161 }
5162 }
5163
5164 // At this point, the template argument refers to an object or
5165 // function with external linkage. We now need to check whether the
5166 // argument and parameter types are compatible.
5167 if (!S.Context.hasSameUnqualifiedType(ArgType,
5168 ParamType.getNonReferenceType())) {
5169 // We can't perform this conversion or binding.
5170 if (ParamType->isReferenceType())
5171 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5172 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5173 else
5174 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5175 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5176 S.Diag(Param->getLocation(), diag::note_template_param_here);
5177 return true;
5178 }
5179 }
5180
5181 return false;
5182}
5183
Douglas Gregorccb07762009-02-11 19:52:55 +00005184/// \brief Checks whether the given template argument is the address
5185/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005186static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005187CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5188 NonTypeTemplateParmDecl *Param,
5189 QualType ParamType,
5190 Expr *ArgIn,
5191 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005192 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005193 Expr *Arg = ArgIn;
5194 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005195
Douglas Gregorb242683d2010-04-01 18:32:35 +00005196 bool AddressTaken = false;
5197 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005198 if (S.getLangOpts().MicrosoftExt) {
5199 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5200 // dereference and address-of operators.
5201 Arg = Arg->IgnoreParenCasts();
5202
5203 bool ExtWarnMSTemplateArg = false;
5204 UnaryOperatorKind FirstOpKind;
5205 SourceLocation FirstOpLoc;
5206 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5207 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5208 if (UnOpKind == UO_Deref)
5209 ExtWarnMSTemplateArg = true;
5210 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5211 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5212 if (!AddrOpLoc.isValid()) {
5213 FirstOpKind = UnOpKind;
5214 FirstOpLoc = UnOp->getOperatorLoc();
5215 }
5216 } else
5217 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005218 }
David Majnemer61c39a12013-08-23 05:39:39 +00005219 if (FirstOpLoc.isValid()) {
5220 if (ExtWarnMSTemplateArg)
5221 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5222 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005223
David Majnemer61c39a12013-08-23 05:39:39 +00005224 if (FirstOpKind == UO_AddrOf)
5225 AddressTaken = true;
5226 else if (Arg->getType()->isPointerType()) {
5227 // We cannot let pointers get dereferenced here, that is obviously not a
5228 // constant expression.
5229 assert(FirstOpKind == UO_Deref);
5230 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5231 << Arg->getSourceRange();
5232 }
5233 }
5234 } else {
5235 // See through any implicit casts we added to fix the type.
5236 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005237
David Majnemer61c39a12013-08-23 05:39:39 +00005238 // C++ [temp.arg.nontype]p1:
5239 //
5240 // A template-argument for a non-type, non-template
5241 // template-parameter shall be one of: [...]
5242 //
5243 // -- the address of an object or function with external
5244 // linkage, including function templates and function
5245 // template-ids but excluding non-static class members,
5246 // expressed as & id-expression where the & is optional if
5247 // the name refers to a function or array, or if the
5248 // corresponding template-parameter is a reference; or
5249
5250 // In C++98/03 mode, give an extension warning on any extra parentheses.
5251 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5252 bool ExtraParens = false;
5253 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5254 if (!Invalid && !ExtraParens) {
5255 S.Diag(Arg->getLocStart(),
5256 S.getLangOpts().CPlusPlus11
5257 ? diag::warn_cxx98_compat_template_arg_extra_parens
5258 : diag::ext_template_arg_extra_parens)
5259 << Arg->getSourceRange();
5260 ExtraParens = true;
5261 }
5262
5263 Arg = Parens->getSubExpr();
5264 }
5265
5266 while (SubstNonTypeTemplateParmExpr *subst =
5267 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5268 Arg = subst->getReplacement()->IgnoreImpCasts();
5269
5270 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5271 if (UnOp->getOpcode() == UO_AddrOf) {
5272 Arg = UnOp->getSubExpr();
5273 AddressTaken = true;
5274 AddrOpLoc = UnOp->getOperatorLoc();
5275 }
5276 }
5277
5278 while (SubstNonTypeTemplateParmExpr *subst =
5279 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5280 Arg = subst->getReplacement()->IgnoreImpCasts();
5281 }
John McCall7c454bb2011-07-15 05:09:51 +00005282
David Majnemer07910d62014-06-26 07:48:46 +00005283 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5284 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5285
5286 // If our parameter has pointer type, check for a null template value.
5287 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5288 NullPointerValueKind NPV;
5289 // dllimport'd entities aren't constant but are available inside of template
5290 // arguments.
5291 if (Entity && Entity->hasAttr<DLLImportAttr>())
5292 NPV = NPV_NotNullPointer;
5293 else
5294 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
5295 switch (NPV) {
5296 case NPV_NullPointer:
5297 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005298 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5299 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005300 return false;
5301
5302 case NPV_Error:
5303 return true;
5304
5305 case NPV_NotNullPointer:
5306 break;
5307 }
5308 }
5309
Chandler Carruth724a8a12010-01-31 10:01:20 +00005310 // Stop checking the precise nature of the argument if it is value dependent,
5311 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005312 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005313 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005314 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005315 }
David Majnemer61c39a12013-08-23 05:39:39 +00005316
5317 if (isa<CXXUuidofExpr>(Arg)) {
5318 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5319 ArgIn, Arg, ArgType))
5320 return true;
5321
5322 Converted = TemplateArgument(ArgIn);
5323 return false;
5324 }
5325
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005326 if (!DRE) {
5327 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5328 << Arg->getSourceRange();
5329 S.Diag(Param->getLocation(), diag::note_template_param_here);
5330 return true;
5331 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00005332
Douglas Gregorccb07762009-02-11 19:52:55 +00005333 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00005334 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005335 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00005336 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005337 S.Diag(Param->getLocation(), diag::note_template_param_here);
5338 return true;
5339 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005340
5341 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00005342 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005343 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005344 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00005345 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005346 S.Diag(Param->getLocation(), diag::note_template_param_here);
5347 return true;
5348 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005349 }
Mike Stump11289f42009-09-09 15:08:12 +00005350
Richard Smith9380e0e2012-04-04 21:11:30 +00005351 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5352 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00005353
Richard Smith9380e0e2012-04-04 21:11:30 +00005354 // A non-type template argument must refer to an object or function.
5355 if (!Func && !Var) {
5356 // We found something, but we don't know specifically what it is.
5357 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5358 << Arg->getSourceRange();
5359 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5360 return true;
5361 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005362
Richard Smith9380e0e2012-04-04 21:11:30 +00005363 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00005364 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005365 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00005366 diag::warn_cxx98_compat_template_arg_object_internal :
5367 diag::ext_template_arg_object_internal)
5368 << !Func << Entity << Arg->getSourceRange();
5369 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5370 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00005371 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005372 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5373 << !Func << Entity << Arg->getSourceRange();
5374 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5375 << !Func;
5376 return true;
5377 }
5378
5379 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005380 // If the template parameter has pointer type, the function decays.
5381 if (ParamType->isPointerType() && !AddressTaken)
5382 ArgType = S.Context.getPointerType(Func->getType());
5383 else if (AddressTaken && ParamType->isReferenceType()) {
5384 // If we originally had an address-of operator, but the
5385 // parameter has reference type, complain and (if things look
5386 // like they will work) drop the address-of operator.
5387 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5388 ParamType.getNonReferenceType())) {
5389 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5390 << ParamType;
5391 S.Diag(Param->getLocation(), diag::note_template_param_here);
5392 return true;
5393 }
5394
5395 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5396 << ParamType
5397 << FixItHint::CreateRemoval(AddrOpLoc);
5398 S.Diag(Param->getLocation(), diag::note_template_param_here);
5399
5400 ArgType = Func->getType();
5401 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005402 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005403 // A value of reference type is not an object.
5404 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005405 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00005406 diag::err_template_arg_reference_var)
5407 << Var->getType() << Arg->getSourceRange();
5408 S.Diag(Param->getLocation(), diag::note_template_param_here);
5409 return true;
5410 }
5411
Richard Smith9380e0e2012-04-04 21:11:30 +00005412 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005413 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005414 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5415 << Arg->getSourceRange();
5416 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5417 return true;
5418 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005419
5420 // If the template parameter has pointer type, we must have taken
5421 // the address of this object.
5422 if (ParamType->isReferenceType()) {
5423 if (AddressTaken) {
5424 // If we originally had an address-of operator, but the
5425 // parameter has reference type, complain and (if things look
5426 // like they will work) drop the address-of operator.
5427 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5428 ParamType.getNonReferenceType())) {
5429 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5430 << ParamType;
5431 S.Diag(Param->getLocation(), diag::note_template_param_here);
5432 return true;
5433 }
5434
5435 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5436 << ParamType
5437 << FixItHint::CreateRemoval(AddrOpLoc);
5438 S.Diag(Param->getLocation(), diag::note_template_param_here);
5439
5440 ArgType = Var->getType();
5441 }
5442 } else if (!AddressTaken && ParamType->isPointerType()) {
5443 if (Var->getType()->isArrayType()) {
5444 // Array-to-pointer decay.
5445 ArgType = S.Context.getArrayDecayedType(Var->getType());
5446 } else {
5447 // If the template parameter has pointer type but the address of
5448 // this object was not taken, complain and (possibly) recover by
5449 // taking the address of the entity.
5450 ArgType = S.Context.getPointerType(Var->getType());
5451 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5452 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5453 << ParamType;
5454 S.Diag(Param->getLocation(), diag::note_template_param_here);
5455 return true;
5456 }
5457
5458 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5459 << ParamType
5460 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5461
5462 S.Diag(Param->getLocation(), diag::note_template_param_here);
5463 }
5464 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005465 }
Mike Stump11289f42009-09-09 15:08:12 +00005466
David Majnemer61c39a12013-08-23 05:39:39 +00005467 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5468 Arg, ArgType))
5469 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005470
5471 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00005472 Converted =
5473 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00005474 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00005475 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005476}
5477
5478/// \brief Checks whether the given template argument is a pointer to
5479/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005480static bool CheckTemplateArgumentPointerToMember(Sema &S,
5481 NonTypeTemplateParmDecl *Param,
5482 QualType ParamType,
5483 Expr *&ResultArg,
5484 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005485 bool Invalid = false;
5486
Douglas Gregor20fdef32012-04-10 17:08:25 +00005487 // Check for a null pointer value.
5488 Expr *Arg = ResultArg;
5489 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
5490 case NPV_Error:
5491 return true;
5492 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005493 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005494 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5495 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00005496 return false;
5497 case NPV_NotNullPointer:
5498 break;
5499 }
5500
5501 bool ObjCLifetimeConversion;
5502 if (S.IsQualificationConversion(Arg->getType(),
5503 ParamType.getNonReferenceType(),
5504 false, ObjCLifetimeConversion)) {
5505 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005506 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00005507 ResultArg = Arg;
5508 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
5509 ParamType.getNonReferenceType())) {
5510 // We can't perform this conversion.
5511 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5512 << Arg->getType() << ParamType << Arg->getSourceRange();
5513 S.Diag(Param->getLocation(), diag::note_template_param_here);
5514 return true;
5515 }
5516
Douglas Gregorccb07762009-02-11 19:52:55 +00005517 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00005518 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00005519 Arg = Cast->getSubExpr();
5520
5521 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005522 //
Douglas Gregorccb07762009-02-11 19:52:55 +00005523 // A template-argument for a non-type, non-template
5524 // template-parameter shall be one of: [...]
5525 //
5526 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00005527 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00005528
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005529 // In C++98/03 mode, give an extension warning on any extra parentheses.
5530 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5531 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005532 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005533 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005534 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005535 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00005536 diag::warn_cxx98_compat_template_arg_extra_parens :
5537 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00005538 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005539 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00005540 }
5541
5542 Arg = Parens->getSubExpr();
5543 }
5544
John McCall7c454bb2011-07-15 05:09:51 +00005545 while (SubstNonTypeTemplateParmExpr *subst =
5546 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5547 Arg = subst->getReplacement()->IgnoreImpCasts();
5548
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005549 // A pointer-to-member constant written &Class::member.
5550 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00005551 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005552 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5553 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005554 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005556 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005557 // A constant of pointer-to-member type.
5558 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5559 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5560 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00005561 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005562 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005563 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005564 } else {
5565 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005566 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005567 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005568 return Invalid;
5569 }
5570 }
5571 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005572
Craig Topperc3ec1492014-05-26 06:22:03 +00005573 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005575
Douglas Gregorccb07762009-02-11 19:52:55 +00005576 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005577 return S.Diag(Arg->getLocStart(),
5578 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00005579 << Arg->getSourceRange();
5580
David Majnemer3ac84e62013-10-22 21:56:38 +00005581 if (isa<FieldDecl>(DRE->getDecl()) ||
5582 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5583 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005584 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00005585 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00005586 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5587 "Only non-static member pointers can make it here");
5588
5589 // Okay: this is the address of a non-static member, and therefore
5590 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00005591 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005592 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005593 } else {
5594 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005595 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005596 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005597 return Invalid;
5598 }
5599
5600 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005601 S.Diag(Arg->getLocStart(),
5602 diag::err_template_arg_not_pointer_to_member_form)
5603 << Arg->getSourceRange();
5604 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00005605 return true;
5606}
5607
Douglas Gregord32e0282009-02-09 23:23:08 +00005608/// \brief Check a template argument against its corresponding
5609/// non-type template parameter.
5610///
Douglas Gregor463421d2009-03-03 04:44:36 +00005611/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00005612/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00005613/// returns the converted template argument. \p ParamType is the
5614/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00005615ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00005616 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00005617 TemplateArgument &Converted,
5618 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005619 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00005620
Richard Smith5f274382016-09-28 23:55:27 +00005621 // If the parameter type somehow involves auto, deduce the type now.
5622 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
Richard Smith87d263e2016-12-25 08:05:23 +00005623 // When checking a deduced template argument, deduce from its type even if
5624 // the type is dependent, in order to check the types of non-type template
5625 // arguments line up properly in partial ordering.
5626 Optional<unsigned> Depth;
5627 if (CTAK != CTAK_Specified)
5628 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00005629 if (DeduceAutoType(
5630 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00005631 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00005632 Diag(Arg->getExprLoc(),
5633 diag::err_non_type_template_parm_type_deduction_failure)
5634 << Param->getDeclName() << Param->getType() << Arg->getType()
5635 << Arg->getSourceRange();
5636 Diag(Param->getLocation(), diag::note_template_param_here);
5637 return ExprError();
5638 }
5639 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5640 // an error. The error message normally references the parameter
5641 // declaration, but here we'll pass the argument location because that's
5642 // where the parameter type is deduced.
5643 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5644 if (ParamType.isNull()) {
5645 Diag(Param->getLocation(), diag::note_template_param_here);
5646 return ExprError();
5647 }
5648 }
5649
Richard Smithd663fdd2014-12-17 20:42:37 +00005650 // We should have already dropped all cv-qualifiers by now.
5651 assert(!ParamType.hasQualifiers() &&
5652 "non-type template parameter type cannot be qualified");
5653
5654 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00005655 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00005656 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00005657 // FIXME: If either type is dependent, we skip the check. This isn't
5658 // correct, since during deduction we're supposed to have replaced each
5659 // template parameter with some unique (non-dependent) placeholder.
5660 // FIXME: If the argument type contains 'auto', we carry on and fail the
5661 // type check in order to force specific types to be more specialized than
5662 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5663 // work.
5664 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5665 !Arg->getType()->getContainedAutoType()) {
5666 Converted = TemplateArgument(Arg);
5667 return Arg;
5668 }
5669 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5670 // we should actually be checking the type of the template argument in P,
5671 // not the type of the template argument deduced from A, against the
5672 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00005673 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00005674 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00005675 << ParamType.getUnqualifiedType();
5676 Diag(Param->getLocation(), diag::note_template_param_here);
5677 return ExprError();
5678 }
5679
Richard Smith87d263e2016-12-25 08:05:23 +00005680 // If either the parameter has a dependent type or the argument is
5681 // type-dependent, there's nothing we can check now.
5682 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5683 // FIXME: Produce a cloned, canonical expression?
5684 Converted = TemplateArgument(Arg);
5685 return Arg;
5686 }
5687
Richard Smithe5945872017-01-06 22:52:53 +00005688 // The initialization of the parameter from the argument is
5689 // a constant-evaluated context.
5690 EnterExpressionEvaluationContext ConstantEvaluated(*this,
5691 Sema::ConstantEvaluated);
5692
Richard Smith410cc892014-11-26 03:26:53 +00005693 if (getLangOpts().CPlusPlus1z) {
Richard Smith410cc892014-11-26 03:26:53 +00005694 // C++1z [temp.arg.nontype]p1:
5695 // A template-argument for a non-type template parameter shall be
5696 // a converted constant expression of the type of the template-parameter.
5697 APValue Value;
5698 ExprResult ArgResult = CheckConvertedConstantExpression(
5699 Arg, ParamType, Value, CCEK_TemplateArg);
5700 if (ArgResult.isInvalid())
5701 return ExprError();
5702
Richard Smith52e624f2016-12-21 21:42:57 +00005703 // For a value-dependent argument, CheckConvertedConstantExpression is
5704 // permitted (and expected) to be unable to determine a value.
5705 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00005706 Converted = TemplateArgument(ArgResult.get());
5707 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00005708 }
5709
Richard Smithd663fdd2014-12-17 20:42:37 +00005710 QualType CanonParamType = Context.getCanonicalType(ParamType);
5711
Richard Smith410cc892014-11-26 03:26:53 +00005712 // Convert the APValue to a TemplateArgument.
5713 switch (Value.getKind()) {
5714 case APValue::Uninitialized:
5715 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005716 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005717 break;
5718 case APValue::Int:
5719 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005720 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005721 break;
5722 case APValue::MemberPointer: {
5723 assert(ParamType->isMemberPointerType());
5724
5725 // FIXME: We need TemplateArgument representation and mangling for these.
5726 if (!Value.getMemberPointerPath().empty()) {
5727 Diag(Arg->getLocStart(),
5728 diag::err_template_arg_member_ptr_base_derived_not_supported)
5729 << Value.getMemberPointerDecl() << ParamType
5730 << Arg->getSourceRange();
5731 return ExprError();
5732 }
5733
5734 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005735 Converted = VD ? TemplateArgument(VD, CanonParamType)
5736 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005737 break;
5738 }
5739 case APValue::LValue: {
5740 // For a non-type template-parameter of pointer or reference type,
5741 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00005742 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5743 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00005744 // -- a temporary object
5745 // -- a string literal
5746 // -- the result of a typeid expression, or
5747 // -- a predefind __func__ variable
5748 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5749 if (isa<CXXUuidofExpr>(E)) {
5750 Converted = TemplateArgument(const_cast<Expr*>(E));
5751 break;
5752 }
5753 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5754 << Arg->getSourceRange();
5755 return ExprError();
5756 }
5757 auto *VD = const_cast<ValueDecl *>(
5758 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5759 // -- a subobject
5760 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5761 VD && VD->getType()->isArrayType() &&
5762 Value.getLValuePath()[0].ArrayIndex == 0 &&
5763 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5764 // Per defect report (no number yet):
5765 // ... other than a pointer to the first element of a complete array
5766 // object.
5767 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5768 Value.isLValueOnePastTheEnd()) {
5769 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5770 << Value.getAsString(Context, ParamType);
5771 return ExprError();
5772 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005773 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005774 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005775 assert((!VD || !ParamType->isNullPtrType()) &&
5776 "non-null value of type nullptr_t?");
5777 Converted = VD ? TemplateArgument(VD, CanonParamType)
5778 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005779 break;
5780 }
5781 case APValue::AddrLabelDiff:
5782 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5783 case APValue::Float:
5784 case APValue::ComplexInt:
5785 case APValue::ComplexFloat:
5786 case APValue::Vector:
5787 case APValue::Array:
5788 case APValue::Struct:
5789 case APValue::Union:
5790 llvm_unreachable("invalid kind for template argument");
5791 }
5792
5793 return ArgResult.get();
5794 }
5795
Douglas Gregor86560402009-02-10 23:36:10 +00005796 // C++ [temp.arg.nontype]p5:
5797 // The following conversions are performed on each expression used
5798 // as a non-type template-argument. If a non-type
5799 // template-argument cannot be converted to the type of the
5800 // corresponding template-parameter then the program is
5801 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005802 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005803 // C++11:
5804 // -- for a non-type template-parameter of integral or
5805 // enumeration type, conversions permitted in a converted
5806 // constant expression are applied.
5807 //
5808 // C++98:
5809 // -- for a non-type template-parameter of integral or
5810 // enumeration type, integral promotions (4.5) and integral
5811 // conversions (4.7) are applied.
5812
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005813 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005814 // C++ [temp.arg.nontype]p1:
5815 // A template-argument for a non-type, non-template template-parameter
5816 // shall be one of:
5817 //
5818 // -- for a non-type template-parameter of integral or enumeration
5819 // type, a converted constant expression of the type of the
5820 // template-parameter; or
5821 llvm::APSInt Value;
5822 ExprResult ArgResult =
5823 CheckConvertedConstantExpression(Arg, ParamType, Value,
5824 CCEK_TemplateArg);
5825 if (ArgResult.isInvalid())
5826 return ExprError();
5827
Richard Smith01bfa682016-12-27 02:02:09 +00005828 // We can't check arbitrary value-dependent arguments.
5829 if (ArgResult.get()->isValueDependent()) {
5830 Converted = TemplateArgument(ArgResult.get());
5831 return ArgResult;
5832 }
5833
Richard Smithf8379a02012-01-18 23:55:52 +00005834 // Widen the argument value to sizeof(parameter type). This is almost
5835 // always a no-op, except when the parameter type is bool. In
5836 // that case, this may extend the argument from 1 bit to 8 bits.
5837 QualType IntegerType = ParamType;
5838 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5839 IntegerType = Enum->getDecl()->getIntegerType();
5840 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5841
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005842 Converted = TemplateArgument(Context, Value,
5843 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005844 return ArgResult;
5845 }
5846
Richard Smith08b12f12011-10-27 22:11:44 +00005847 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5848 if (ArgResult.isInvalid())
5849 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005850 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005851
5852 QualType ArgType = Arg->getType();
5853
Douglas Gregor86560402009-02-10 23:36:10 +00005854 // C++ [temp.arg.nontype]p1:
5855 // A template-argument for a non-type, non-template
5856 // template-parameter shall be one of:
5857 //
5858 // -- an integral constant-expression of integral or enumeration
5859 // type; or
5860 // -- the name of a non-type template-parameter; or
5861 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005862 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005863 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005864 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005865 diag::err_template_arg_not_integral_or_enumeral)
5866 << ArgType << Arg->getSourceRange();
5867 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005868 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005869 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005870 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5871 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005872
Douglas Gregore2b37442012-05-04 22:38:52 +00005873 public:
5874 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005875
5876 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5877 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005878 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5879 }
5880 } Diagnoser(ArgType);
5881
5882 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005883 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005884 if (!Arg)
5885 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005886 }
5887
Richard Smithd663fdd2014-12-17 20:42:37 +00005888 // From here on out, all we care about is the unqualified form
5889 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005890 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005891
5892 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005893 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005894 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005895 } else if (ParamType->isBooleanType()) {
5896 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005897 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005898 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5899 !ParamType->isEnumeralType()) {
5900 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005901 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005902 } else {
5903 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005904 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005905 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005906 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005907 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005908 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005909 }
5910
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005911 // Add the value of this argument to the list of converted
5912 // arguments. We use the bitwidth and signedness of the template
5913 // parameter.
5914 if (Arg->isValueDependent()) {
5915 // The argument is value-dependent. Create a new
5916 // TemplateArgument with the converted expression.
5917 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005918 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005919 }
5920
Douglas Gregor52aba872009-03-14 00:20:21 +00005921 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005922 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005923 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005924
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005925 if (ParamType->isBooleanType()) {
5926 // Value must be zero or one.
5927 Value = Value != 0;
5928 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5929 if (Value.getBitWidth() != AllowedBits)
5930 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005931 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005932 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005933 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005934
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005935 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005936 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005937 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005938 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005939 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005940 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00005941
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005942 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005943 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005944 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005945 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005946 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5947 << Arg->getSourceRange();
5948 Diag(Param->getLocation(), diag::note_template_param_here);
5949 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005950
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005951 // Complain if we overflowed the template parameter's type.
5952 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005953 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005954 RequiredBits = OldValue.getActiveBits();
5955 else if (OldValue.isUnsigned())
5956 RequiredBits = OldValue.getActiveBits() + 1;
5957 else
5958 RequiredBits = OldValue.getMinSignedBits();
5959 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005960 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005961 diag::warn_template_arg_too_large)
5962 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5963 << Arg->getSourceRange();
5964 Diag(Param->getLocation(), diag::note_template_param_here);
5965 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005966 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005967
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005968 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00005969 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005970 ? Context.getCanonicalType(ParamType)
5971 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005972 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005973 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005974
Richard Smith08b12f12011-10-27 22:11:44 +00005975 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005976 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5977
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005978 // Handle pointer-to-function, reference-to-function, and
5979 // pointer-to-member-function all in (roughly) the same way.
5980 if (// -- For a non-type template-parameter of type pointer to
5981 // function, only the function-to-pointer conversion (4.3) is
5982 // applied. If the template-argument represents a set of
5983 // overloaded functions (or a pointer to such), the matching
5984 // function is selected from the set (13.4).
5985 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005986 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005987 // -- For a non-type template-parameter of type reference to
5988 // function, no conversions apply. If the template-argument
5989 // represents a set of overloaded functions, the matching
5990 // function is selected from the set (13.4).
5991 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005992 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005993 // -- For a non-type template-parameter of type pointer to
5994 // member function, no conversions apply. If the
5995 // template-argument represents a set of overloaded member
5996 // functions, the matching member function is selected from
5997 // the set (13.4).
5998 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005999 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006000 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006001
Douglas Gregor064fdb22010-04-14 23:11:21 +00006002 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006003 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006004 true,
6005 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006006 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006007 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006008
6009 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6010 ArgType = Arg->getType();
6011 } else
John Wiegley01296292011-04-08 18:41:53 +00006012 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006013 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006014
John Wiegley01296292011-04-08 18:41:53 +00006015 if (!ParamType->isMemberPointerType()) {
6016 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6017 ParamType,
6018 Arg, Converted))
6019 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006020 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006021 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006022
Douglas Gregor20fdef32012-04-10 17:08:25 +00006023 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6024 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006025 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006026 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006027 }
6028
Chris Lattner696197c2009-02-20 21:37:53 +00006029 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006030 // -- for a non-type template-parameter of type pointer to
6031 // object, qualification conversions (4.4) and the
6032 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006033 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006034 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006035 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006036
John Wiegley01296292011-04-08 18:41:53 +00006037 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6038 ParamType,
6039 Arg, Converted))
6040 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006041 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006042 }
Mike Stump11289f42009-09-09 15:08:12 +00006043
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006044 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006045 // -- For a non-type template-parameter of type reference to
6046 // object, no conversions apply. The type referred to by the
6047 // reference may be more cv-qualified than the (otherwise
6048 // identical) type of the template-argument. The
6049 // template-parameter is bound directly to the
6050 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006051 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006052 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006053
Douglas Gregor064fdb22010-04-14 23:11:21 +00006054 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006055 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6056 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006057 true,
6058 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006059 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006060 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006061
6062 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6063 ArgType = Arg->getType();
6064 } else
John Wiegley01296292011-04-08 18:41:53 +00006065 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006067
John Wiegley01296292011-04-08 18:41:53 +00006068 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6069 ParamType,
6070 Arg, Converted))
6071 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006072 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006073 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006074
Douglas Gregor20fdef32012-04-10 17:08:25 +00006075 // Deal with parameters of type std::nullptr_t.
6076 if (ParamType->isNullPtrType()) {
6077 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6078 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006079 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006080 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006081
Douglas Gregor20fdef32012-04-10 17:08:25 +00006082 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6083 case NPV_NotNullPointer:
6084 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6085 << Arg->getType() << ParamType;
6086 Diag(Param->getLocation(), diag::note_template_param_here);
6087 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006088
Douglas Gregor20fdef32012-04-10 17:08:25 +00006089 case NPV_Error:
6090 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006091
Douglas Gregor20fdef32012-04-10 17:08:25 +00006092 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006093 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006094 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6095 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006096 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006097 }
6098 }
6099
Douglas Gregor0e558532009-02-11 16:16:59 +00006100 // -- For a non-type template-parameter of type pointer to data
6101 // member, qualification conversions (4.4) are applied.
6102 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6103
Douglas Gregor20fdef32012-04-10 17:08:25 +00006104 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6105 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006106 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006107 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006108}
6109
Richard Smith26b86ea2016-12-31 21:41:23 +00006110static void DiagnoseTemplateParameterListArityMismatch(
6111 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6112 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6113
Douglas Gregord32e0282009-02-09 23:23:08 +00006114/// \brief Check a template argument against its corresponding
6115/// template template parameter.
6116///
6117/// This routine implements the semantics of C++ [temp.arg.template].
6118/// It returns true if an error occurred, and false otherwise.
6119bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00006120 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00006121 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006122 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006123 TemplateDecl *Template = Name.getAsTemplateDecl();
6124 if (!Template) {
6125 // Any dependent template name is fine.
6126 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6127 return false;
6128 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006129
Richard Smith26b86ea2016-12-31 21:41:23 +00006130 if (Template->isInvalidDecl())
6131 return true;
6132
Richard Smith3f1b5d02011-05-05 21:57:07 +00006133 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006134 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006135 // the name of a class template or an alias template, expressed as an
6136 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006137 // primary class templates are considered when matching the
6138 // template template argument with the corresponding parameter;
6139 // partial specializations are not considered even if their
6140 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006141 //
6142 // Note that we also allow template template parameters here, which
6143 // will happen when we are dealing with, e.g., class template
6144 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006145 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006146 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006147 !isa<TypeAliasTemplateDecl>(Template) &&
6148 !isa<BuiltinTemplateDecl>(Template)) {
6149 assert(isa<FunctionTemplateDecl>(Template) &&
6150 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006151 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006152 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6153 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006154 }
6155
Richard Smith1fde8ec2012-09-07 02:06:42 +00006156 TemplateParameterList *Params = Param->getTemplateParameters();
6157 if (Param->isExpandedParameterPack())
6158 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6159
Richard Smith26b86ea2016-12-31 21:41:23 +00006160 // C++1z [temp.arg.template]p3: (DR 150)
6161 // A template-argument matches a template template-parameter P when P
6162 // is at least as specialized as the template-argument A.
6163 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6164 // Quick check for the common case:
6165 // If P contains a parameter pack, then A [...] matches P if each of A's
6166 // template parameters matches the corresponding template parameter in
6167 // the template-parameter-list of P.
6168 if (TemplateParameterListsAreEqual(
6169 Template->getTemplateParameters(), Params, false,
6170 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6171 return false;
6172
6173 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6174 Arg.getLocation()))
6175 return false;
6176 // FIXME: Produce better diagnostics for deduction failures.
6177 }
6178
Douglas Gregor85e0f662009-02-10 00:24:35 +00006179 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006180 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006181 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006182 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006183 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006184}
6185
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006186/// \brief Given a non-type template argument that refers to a
6187/// declaration and the type of its corresponding non-type template
6188/// parameter, produce an expression that properly refers to that
6189/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006190ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006191Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6192 QualType ParamType,
6193 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006194 // C++ [temp.param]p8:
6195 //
6196 // A non-type template-parameter of type "array of T" or
6197 // "function returning T" is adjusted to be of type "pointer to
6198 // T" or "pointer to function returning T", respectively.
6199 if (ParamType->isArrayType())
6200 ParamType = Context.getArrayDecayedType(ParamType);
6201 else if (ParamType->isFunctionType())
6202 ParamType = Context.getPointerType(ParamType);
6203
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006204 // For a NULL non-type template argument, return nullptr casted to the
6205 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006206 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006207 return ImpCastExprToType(
6208 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6209 ParamType,
6210 ParamType->getAs<MemberPointerType>()
6211 ? CK_NullToMemberPointer
6212 : CK_NullToPointer);
6213 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006214 assert(Arg.getKind() == TemplateArgument::Declaration &&
6215 "Only declaration template arguments permitted here");
6216
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006217 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6218
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006219 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006220 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6221 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006222 // If the value is a class member, we might have a pointer-to-member.
6223 // Determine whether the non-type template template parameter is of
6224 // pointer-to-member type. If so, we need to build an appropriate
6225 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6226 // would refer to the member itself.
6227 if (ParamType->isMemberPointerType()) {
6228 QualType ClassType
6229 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6230 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006231 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006232 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006233 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006234 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006235
6236 // The actual value-ness of this is unimportant, but for
6237 // internal consistency's sake, references to instance methods
6238 // are r-values.
6239 ExprValueKind VK = VK_LValue;
6240 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6241 VK = VK_RValue;
6242
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006243 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006244 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006245 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006246 Loc,
6247 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006248 if (RefExpr.isInvalid())
6249 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006250
John McCalle3027922010-08-25 11:45:40 +00006251 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006252
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006253 // We might need to perform a trailing qualification conversion, since
6254 // the element type on the parameter could be more qualified than the
6255 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006256 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006257 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006258 ParamType.getUnqualifiedType(), false,
6259 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006260 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006261
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006262 assert(!RefExpr.isInvalid() &&
6263 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006264 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006265 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006266 }
6267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006268
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006269 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006270
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006271 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006272 // When the non-type template parameter is a pointer, take the
6273 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006274 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006275 if (RefExpr.isInvalid())
6276 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006277
Richard Smithfc6fca12017-01-28 00:38:35 +00006278 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6279 (T->isFunctionType() || T->isArrayType())) {
6280 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006281 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006282 if (RefExpr.isInvalid())
6283 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006284
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006285 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006287
Douglas Gregorb242683d2010-04-01 18:32:35 +00006288 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006289 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006290 }
6291
John McCall7decc9e2010-11-18 06:31:45 +00006292 ExprValueKind VK = VK_RValue;
6293
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006294 // If the non-type template parameter has reference type, qualify the
6295 // resulting declaration reference with the extra qualifiers on the
6296 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006297 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6298 VK = VK_LValue;
6299 T = Context.getQualifiedType(T,
6300 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006301 } else if (isa<FunctionDecl>(VD)) {
6302 // References to functions are always lvalues.
6303 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006304 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006305
John McCall7decc9e2010-11-18 06:31:45 +00006306 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006307}
6308
6309/// \brief Construct a new expression that refers to the given
6310/// integral template argument with the given source-location
6311/// information.
6312///
6313/// This routine takes care of the mapping from an integral template
6314/// argument (which may have any integral type) to the appropriate
6315/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006316ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006317Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6318 SourceLocation Loc) {
6319 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006320 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006321 QualType OrigT = Arg.getIntegralType();
6322
6323 // If this is an enum type that we're instantiating, we need to use an integer
6324 // type the same size as the enumerator. We don't want to build an
6325 // IntegerLiteral with enum type. The integer type of an enum type can be of
6326 // any integral type with C++11 enum classes, make sure we create the right
6327 // type of literal for it.
6328 QualType T = OrigT;
6329 if (const EnumType *ET = OrigT->getAs<EnumType>())
6330 T = ET->getDecl()->getIntegerType();
6331
6332 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006333 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00006334 // This does not need to handle u8 character literals because those are
6335 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00006336 CharacterLiteral::CharacterKind Kind;
6337 if (T->isWideCharType())
6338 Kind = CharacterLiteral::Wide;
6339 else if (T->isChar16Type())
6340 Kind = CharacterLiteral::UTF16;
6341 else if (T->isChar32Type())
6342 Kind = CharacterLiteral::UTF32;
6343 else
6344 Kind = CharacterLiteral::Ascii;
6345
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006346 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6347 Kind, T, Loc);
6348 } else if (T->isBooleanType()) {
6349 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6350 T, Loc);
6351 } else if (T->isNullPtrType()) {
6352 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6353 } else {
6354 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00006355 }
6356
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006357 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00006358 // FIXME: This is a hack. We need a better way to handle substituted
6359 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00006360 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6361 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006362 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00006363 Loc, Loc);
6364 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006365
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006366 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006367}
6368
Richard Smith43a833b2017-01-09 23:54:33 +00006369static bool isDependentOnOuter(NonTypeTemplateParmDecl *NTTP) {
6370 if (NTTP->getDepth() == 0 || !NTTP->getType()->isDependentType())
6371 return false;
6372 DependencyChecker Checker(NTTP->getDepth(), /*IgnoreNonTypeDependent*/ false,
6373 /*FindLessThanDepth*/ true);
6374 Checker.TraverseType(NTTP->getType());
6375 return Checker.Match;
6376}
6377
Douglas Gregor641040a2011-01-12 23:45:44 +00006378/// \brief Match two template parameters within template parameter lists.
6379static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6380 bool Complain,
6381 Sema::TemplateParameterListEqualKind Kind,
6382 SourceLocation TemplateArgLoc) {
6383 // Check the actual kind (type, non-type, template).
6384 if (Old->getKind() != New->getKind()) {
6385 if (Complain) {
6386 unsigned NextDiag = diag::err_template_param_different_kind;
6387 if (TemplateArgLoc.isValid()) {
6388 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6389 NextDiag = diag::note_template_param_different_kind;
6390 }
6391 S.Diag(New->getLocation(), NextDiag)
6392 << (Kind != Sema::TPL_TemplateMatch);
6393 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6394 << (Kind != Sema::TPL_TemplateMatch);
6395 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006396
Douglas Gregor641040a2011-01-12 23:45:44 +00006397 return false;
6398 }
6399
Richard Smith26b86ea2016-12-31 21:41:23 +00006400 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006401 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006402 // template template parameter, the template template parameter can have
6403 // a parameter pack where the template template argument does not.
6404 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6405 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6406 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006407 if (Complain) {
6408 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6409 if (TemplateArgLoc.isValid()) {
6410 S.Diag(TemplateArgLoc,
6411 diag::err_template_arg_template_params_mismatch);
6412 NextDiag = diag::note_template_parameter_pack_non_pack;
6413 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006414
Douglas Gregor641040a2011-01-12 23:45:44 +00006415 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6416 : isa<NonTypeTemplateParmDecl>(New)? 1
6417 : 2;
6418 S.Diag(New->getLocation(), NextDiag)
6419 << ParamKind << New->isParameterPack();
6420 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6421 << ParamKind << Old->isParameterPack();
6422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006423
Douglas Gregor641040a2011-01-12 23:45:44 +00006424 return false;
6425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006426
Douglas Gregor641040a2011-01-12 23:45:44 +00006427 // For non-type template parameters, check the type of the parameter.
6428 if (NonTypeTemplateParmDecl *OldNTTP
6429 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6430 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006431
Douglas Gregor641040a2011-01-12 23:45:44 +00006432 // If we are matching a template template argument to a template
6433 // template parameter and one of the non-type template parameter types
Richard Smith43a833b2017-01-09 23:54:33 +00006434 // is dependent on an outer template's parameter, then we must wait until
6435 // template instantiation time to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00006436 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith43a833b2017-01-09 23:54:33 +00006437 (isDependentOnOuter(OldNTTP) || isDependentOnOuter(NewNTTP)))
Douglas Gregor641040a2011-01-12 23:45:44 +00006438 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006439
Douglas Gregor641040a2011-01-12 23:45:44 +00006440 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6441 if (Complain) {
6442 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6443 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006444 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00006445 diag::err_template_arg_template_params_mismatch);
6446 NextDiag = diag::note_template_nontype_parm_different_type;
6447 }
6448 S.Diag(NewNTTP->getLocation(), NextDiag)
6449 << NewNTTP->getType()
6450 << (Kind != Sema::TPL_TemplateMatch);
6451 S.Diag(OldNTTP->getLocation(),
6452 diag::note_template_nontype_parm_prev_declaration)
6453 << OldNTTP->getType();
6454 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006455
Douglas Gregor641040a2011-01-12 23:45:44 +00006456 return false;
6457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006458
Douglas Gregor641040a2011-01-12 23:45:44 +00006459 return true;
6460 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006461
Douglas Gregor641040a2011-01-12 23:45:44 +00006462 // For template template parameters, check the template parameter types.
6463 // The template parameter lists of template template
6464 // parameters must agree.
6465 if (TemplateTemplateParmDecl *OldTTP
6466 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006467 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00006468 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6469 OldTTP->getTemplateParameters(),
6470 Complain,
6471 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006472 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00006473 : Kind),
6474 TemplateArgLoc);
6475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006476
Douglas Gregor641040a2011-01-12 23:45:44 +00006477 return true;
6478}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006479
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006480/// \brief Diagnose a known arity mismatch when comparing template argument
6481/// lists.
6482static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006483void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006484 TemplateParameterList *New,
6485 TemplateParameterList *Old,
6486 Sema::TemplateParameterListEqualKind Kind,
6487 SourceLocation TemplateArgLoc) {
6488 unsigned NextDiag = diag::err_template_param_list_different_arity;
6489 if (TemplateArgLoc.isValid()) {
6490 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6491 NextDiag = diag::note_template_param_list_different_arity;
6492 }
6493 S.Diag(New->getTemplateLoc(), NextDiag)
6494 << (New->size() > Old->size())
6495 << (Kind != Sema::TPL_TemplateMatch)
6496 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6497 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6498 << (Kind != Sema::TPL_TemplateMatch)
6499 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6500}
6501
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006502/// \brief Determine whether the given template parameter lists are
6503/// equivalent.
6504///
Mike Stump11289f42009-09-09 15:08:12 +00006505/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006506/// source code as part of a new template declaration.
6507///
6508/// \param Old The old template parameter list, typically found via
6509/// name lookup of the template declared with this template parameter
6510/// list.
6511///
6512/// \param Complain If true, this routine will produce a diagnostic if
6513/// the template parameter lists are not equivalent.
6514///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006515/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00006516///
6517/// \param TemplateArgLoc If this source location is valid, then we
6518/// are actually checking the template parameter list of a template
6519/// argument (New) against the template parameter list of its
6520/// corresponding template template parameter (Old). We produce
6521/// slightly different diagnostics in this scenario.
6522///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006523/// \returns True if the template parameter lists are equal, false
6524/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00006525bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006526Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6527 TemplateParameterList *Old,
6528 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006529 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00006530 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006531 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6532 if (Complain)
6533 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6534 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006535
6536 return false;
6537 }
6538
Douglas Gregor641040a2011-01-12 23:45:44 +00006539 // C++0x [temp.arg.template]p3:
6540 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006541 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00006542 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006543 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006544 // template-parameter-list of P. [...]
6545 TemplateParameterList::iterator NewParm = New->begin();
6546 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006547 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006548 OldParmEnd = Old->end();
6549 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00006550 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6551 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006552 if (NewParm == NewParmEnd) {
6553 if (Complain)
6554 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6555 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006556
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006557 return false;
6558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006559
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006560 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6561 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006562 return false;
6563
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006564 ++NewParm;
6565 continue;
6566 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006567
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006568 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006569 // [...] When P's template- parameter-list contains a template parameter
6570 // pack (14.5.3), the template parameter pack will match zero or more
6571 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006572 // template-parameter-list of A with the same type and form as the
6573 // template parameter pack in P (ignoring whether those template
6574 // parameters are template parameter packs).
6575 for (; NewParm != NewParmEnd; ++NewParm) {
6576 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6577 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006578 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006579 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006580 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006581
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006582 // Make sure we exhausted all of the arguments.
6583 if (NewParm != NewParmEnd) {
6584 if (Complain)
6585 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6586 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006587
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006588 return false;
6589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006590
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006591 return true;
6592}
6593
6594/// \brief Check whether a template can be declared within this scope.
6595///
6596/// If the template declaration is valid in this scope, returns
6597/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00006598bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006599Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00006600 if (!S)
6601 return false;
6602
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006603 // Find the nearest enclosing declaration scope.
6604 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6605 (S->getFlags() & Scope::TemplateParamScope) != 0)
6606 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006607
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006608 // C++ [temp]p4:
6609 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00006610 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00006611 if (Ctx && Ctx->isExternCContext()) {
6612 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6613 << TemplateParams->getSourceRange();
6614 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6615 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6616 return true;
6617 }
Richard Smith8df390f2016-09-08 23:14:54 +00006618 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006619
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006620 // C++ [temp]p2:
6621 // A template-declaration can appear only as a namespace scope or
6622 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00006623 if (Ctx) {
6624 if (Ctx->isFileContext())
6625 return false;
6626 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6627 // C++ [temp.mem]p2:
6628 // A local class shall not have member templates.
6629 if (RD->isLocalClass())
6630 return Diag(TemplateParams->getTemplateLoc(),
6631 diag::err_template_inside_local_class)
6632 << TemplateParams->getSourceRange();
6633 else
6634 return false;
6635 }
6636 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006637
Mike Stump11289f42009-09-09 15:08:12 +00006638 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006639 diag::err_template_outside_namespace_or_class_scope)
6640 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006641}
Douglas Gregor67a65642009-02-17 23:15:12 +00006642
Douglas Gregor54888652009-10-07 00:13:32 +00006643/// \brief Determine what kind of template specialization the given declaration
6644/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006645static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00006646 if (!D)
6647 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006648
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006649 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6650 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00006651 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6652 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006653 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6654 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006655
Douglas Gregor54888652009-10-07 00:13:32 +00006656 return TSK_Undeclared;
6657}
6658
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006659/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006660/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00006661///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006662/// This routine determines whether a template specialization can be declared
6663/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00006664///
6665/// \param S the semantic analysis object for which this check is being
6666/// performed.
6667///
6668/// \param Specialized the entity being specialized or instantiated, which
6669/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006670/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00006671/// member class).
6672///
6673/// \param PrevDecl the previous declaration of this entity, if any.
6674///
6675/// \param Loc the location of the explicit specialization or instantiation of
6676/// this entity.
6677///
6678/// \param IsPartialSpecialization whether this is a partial specialization of
6679/// a class template.
6680///
Douglas Gregor54888652009-10-07 00:13:32 +00006681/// \returns true if there was an error that we cannot recover from, false
6682/// otherwise.
6683static bool CheckTemplateSpecializationScope(Sema &S,
6684 NamedDecl *Specialized,
6685 NamedDecl *PrevDecl,
6686 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006687 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00006688 // Keep these "kind" numbers in sync with the %select statements in the
6689 // various diagnostics emitted by this routine.
6690 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006691 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006692 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006693 else if (isa<VarTemplateDecl>(Specialized))
6694 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006695 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006696 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006697 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006698 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006699 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00006700 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006701 else if (isa<RecordDecl>(Specialized))
6702 EntityKind = 7;
6703 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6704 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00006705 else {
Richard Smith7d137e32012-03-23 03:33:32 +00006706 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006707 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006708 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00006709 return true;
6710 }
6711
Douglas Gregorf47b9112009-02-25 22:02:03 +00006712 // C++ [temp.expl.spec]p2:
6713 // An explicit specialization shall be declared in the namespace
6714 // of which the template is a member, or, for member templates, in
6715 // the namespace of which the enclosing class or enclosing class
6716 // template is a member. An explicit specialization of a member
6717 // function, member class or static data member of a class
6718 // template shall be declared in the namespace of which the class
6719 // template is a member. Such a declaration may also be a
6720 // definition. If the declaration is not a definition, the
6721 // specialization may be defined later in the name- space in which
6722 // the explicit specialization was declared, or in a namespace
6723 // that encloses the one in which the explicit specialization was
6724 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00006725 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00006726 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006727 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006728 return true;
6729 }
Douglas Gregore4b05162009-10-07 17:21:34 +00006730
Douglas Gregor40fb7442009-10-07 17:30:37 +00006731 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006732 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006733 // Do not warn for class scope explicit specialization during
6734 // instantiation, warning was already emitted during pattern
6735 // semantic analysis.
6736 if (!S.ActiveTemplateInstantiations.size())
6737 S.Diag(Loc, diag::ext_function_specialization_in_class)
6738 << Specialized;
6739 } else {
6740 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6741 << Specialized;
6742 return true;
6743 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006745
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006746 if (S.CurContext->isRecord() &&
6747 !S.CurContext->Equals(Specialized->getDeclContext())) {
6748 // Make sure that we're specializing in the right record context.
6749 // Otherwise, things can go horribly wrong.
6750 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6751 << Specialized;
6752 return true;
6753 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006754
Douglas Gregore4b05162009-10-07 17:21:34 +00006755 // C++ [temp.class.spec]p6:
6756 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006757 // in any namespace scope in which its definition may be defined (14.5.1
6758 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00006759 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00006760 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00006761 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00006762
6763 // Make sure that this redeclaration (or definition) occurs in an enclosing
6764 // namespace.
6765 // Note that HandleDeclarator() performs this check for explicit
6766 // specializations of function templates, static data members, and member
6767 // functions, so we skip the check here for those kinds of entities.
6768 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6769 // Should we refactor that check, so that it occurs later?
6770 if (!DC->Encloses(SpecializedContext) &&
6771 !(isa<FunctionTemplateDecl>(Specialized) ||
6772 isa<FunctionDecl>(Specialized) ||
6773 isa<VarTemplateDecl>(Specialized) ||
6774 isa<VarDecl>(Specialized))) {
6775 if (isa<TranslationUnitDecl>(SpecializedContext))
6776 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6777 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00006778 else if (isa<NamespaceDecl>(SpecializedContext)) {
6779 int Diag = diag::err_template_spec_redecl_out_of_scope;
6780 if (S.getLangOpts().MicrosoftExt)
6781 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6782 S.Diag(Loc, Diag) << EntityKind << Specialized
6783 << cast<NamedDecl>(SpecializedContext);
6784 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00006785 llvm_unreachable("unexpected namespace context for specialization");
6786
6787 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6788 } else if ((!PrevDecl ||
6789 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6790 getTemplateSpecializationKind(PrevDecl) ==
6791 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006792 // C++ [temp.exp.spec]p2:
6793 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006794 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006795 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006796 // An explicit specialization of a member function, member class or
6797 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006798 // namespace of which the class template is a member.
6799 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006800 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006801 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006802 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006803 // C++11 [temp.explicit]p3:
6804 // An explicit instantiation shall appear in an enclosing namespace of its
6805 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006806 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006807 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006808 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006809 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006810 "DC encloses TU but isn't in enclosing namespace set");
6811 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006812 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006813 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6814 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006815 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006816 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006817 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006818 Diag = diag::ext_template_spec_decl_out_of_scope;
6819 else
6820 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6821 S.Diag(Loc, Diag)
6822 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006824
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006825 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006826 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006827 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006828
Douglas Gregorf47b9112009-02-25 22:02:03 +00006829 return false;
6830}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006831
Richard Smith57aae072016-12-28 02:37:25 +00006832static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
6833 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00006834 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006835 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006836 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00006837 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006838 return E->getSourceRange();
6839 return Checker.MatchLoc;
6840}
6841
6842static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6843 if (!TL.getType()->isDependentType())
6844 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006845 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006846 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00006847 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006848 return TL.getSourceRange();
6849 return Checker.MatchLoc;
6850}
6851
Larisse Voufo39a1e502013-08-06 01:03:05 +00006852/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006853/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006854static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006855 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6856 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006857 for (unsigned I = 0; I != NumArgs; ++I) {
6858 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006859 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006860 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6861 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006862 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006863
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006864 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006865 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006866
Eli Friedmanb826a002012-09-26 02:36:12 +00006867 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006868 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006869
6870 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006871
Douglas Gregor98318c22011-01-03 21:37:45 +00006872 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006873 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6874 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006875
6876 // Strip off any implicit casts we added as part of type checking.
6877 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6878 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006879
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006880 // C++ [temp.class.spec]p8:
6881 // A non-type argument is non-specialized if it is the name of a
6882 // non-type parameter. All other non-type arguments are
6883 // specialized.
6884 //
6885 // Below, we check the two conditions that only apply to
6886 // specialized non-type arguments, so skip any non-specialized
6887 // arguments.
6888 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006889 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006890 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006891
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006892 // C++ [temp.class.spec]p9:
6893 // Within the argument list of a class template partial
6894 // specialization, the following restrictions apply:
6895 // -- A partially specialized non-type argument expression
6896 // shall not involve a template parameter of the partial
6897 // specialization except when the argument expression is a
6898 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00006899 // -- The type of a template parameter corresponding to a
6900 // specialized non-type argument shall not be dependent on a
6901 // parameter of the specialization.
6902 // DR1315 removes the first bullet, leaving an incoherent set of rules.
6903 // We implement a compromise between the original rules and DR1315:
6904 // -- A specialized non-type template argument shall not be
6905 // type-dependent and the corresponding template parameter
6906 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00006907 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00006908 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00006909 if (ParamUseRange.isValid()) {
6910 if (IsDefaultArgument) {
6911 S.Diag(TemplateNameLoc,
6912 diag::err_dependent_non_type_arg_in_partial_spec);
6913 S.Diag(ParamUseRange.getBegin(),
6914 diag::note_dependent_non_type_default_arg_in_partial_spec)
6915 << ParamUseRange;
6916 } else {
6917 S.Diag(ParamUseRange.getBegin(),
6918 diag::err_dependent_non_type_arg_in_partial_spec)
6919 << ParamUseRange;
6920 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006921 return true;
6922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006923
Richard Smith6056d5e2014-02-09 00:54:43 +00006924 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00006925 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00006926 if (ParamUseRange.isValid()) {
6927 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6928 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Richard Smith57aae072016-12-28 02:37:25 +00006929 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00006930 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00006931 << (IsDefaultArgument ? ParamUseRange : SourceRange())
6932 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006933 return true;
6934 }
6935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006936
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006937 return false;
6938}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006939
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006940/// \brief Check the non-type template arguments of a class template
6941/// partial specialization according to C++ [temp.class.spec]p9.
6942///
Richard Smith6056d5e2014-02-09 00:54:43 +00006943/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00006944/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006945/// template.
6946/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006947/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006948/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006949///
Richard Smith6056d5e2014-02-09 00:54:43 +00006950/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00006951bool Sema::CheckTemplatePartialSpecializationArgs(
6952 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
6953 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
6954 // We have to be conservative when checking a template in a dependent
6955 // context.
6956 if (PrimaryTemplate->getDeclContext()->isDependentContext())
6957 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006958
Richard Smith57aae072016-12-28 02:37:25 +00006959 TemplateParameterList *TemplateParams =
6960 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006961 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6962 NonTypeTemplateParmDecl *Param
6963 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6964 if (!Param)
6965 continue;
6966
Richard Smith57aae072016-12-28 02:37:25 +00006967 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
6968 Param, &TemplateArgs[I],
6969 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006970 return true;
6971 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006972
6973 return false;
6974}
6975
John McCall48871652010-08-21 09:40:31 +00006976DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006977Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6978 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006979 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006980 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006981 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006982 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006983 MultiTemplateParamsArg
6984 TemplateParameterLists,
6985 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006986 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006987
Richard Smith4b55a9c2014-04-17 03:29:33 +00006988 CXXScopeSpec &SS = TemplateId.SS;
6989
Abramo Bagnara60804e12011-03-18 15:16:37 +00006990 // NOTE: KWLoc is the location of the tag keyword. This will instead
6991 // store the location of the outermost template keyword in the declaration.
6992 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006993 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6994 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6995 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6996 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006997
Douglas Gregor67a65642009-02-17 23:15:12 +00006998 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006999 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007000 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007001 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7002
7003 if (!ClassTemplate) {
7004 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007005 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007006 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7007 return true;
7008 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007009
Richard Smithf445f192017-02-09 21:04:43 +00007010 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007011 bool isPartialSpecialization = false;
7012
Douglas Gregorf47b9112009-02-25 22:02:03 +00007013 // Check the validity of the template headers that introduce this
7014 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007015 // FIXME: We probably shouldn't complain about these headers for
7016 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007017 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007018 TemplateParameterList *TemplateParams =
7019 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007020 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007021 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007022 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007023 if (Invalid)
7024 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007025
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007026 if (TemplateParams && TemplateParams->size() > 0) {
7027 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007028
Douglas Gregorec9518b2010-12-21 08:14:57 +00007029 if (TUK == TUK_Friend) {
7030 Diag(KWLoc, diag::err_partial_specialization_friend)
7031 << SourceRange(LAngleLoc, RAngleLoc);
7032 return true;
7033 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007034
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007035 // C++ [temp.class.spec]p10:
7036 // The template parameter list of a specialization shall not
7037 // contain default template argument values.
7038 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7039 Decl *Param = TemplateParams->getParam(I);
7040 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7041 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007042 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007043 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007044 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007045 }
7046 } else if (NonTypeTemplateParmDecl *NTTP
7047 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7048 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007049 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007050 diag::err_default_arg_in_partial_spec)
7051 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007052 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007053 }
7054 } else {
7055 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007056 if (TTP->hasDefaultArgument()) {
7057 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007058 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007059 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007060 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007061 }
7062 }
7063 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007064 } else if (TemplateParams) {
7065 if (TUK == TUK_Friend)
7066 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007067 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007068 SourceRange(TemplateParams->getTemplateLoc(),
7069 TemplateParams->getRAngleLoc()))
7070 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007071 } else {
7072 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007073 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007074
Douglas Gregor67a65642009-02-17 23:15:12 +00007075 // Check that the specialization uses the same tag kind as the
7076 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007077 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7078 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007079 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007080 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007081 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007082 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007083 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007084 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007085 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007086 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007087 diag::note_previous_use);
7088 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7089 }
7090
Douglas Gregorc40290e2009-03-09 23:48:35 +00007091 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007092 TemplateArgumentListInfo TemplateArgs =
7093 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007094
Douglas Gregor14406932011-01-03 20:35:03 +00007095 // Check for unexpanded parameter packs in any of the template arguments.
7096 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007097 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007098 UPPC_PartialSpecialization))
7099 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007100
Douglas Gregor67a65642009-02-17 23:15:12 +00007101 // Check that the template argument list is well-formed for this
7102 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007103 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007104 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7105 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007106 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007107
Douglas Gregor2373c592009-05-31 09:31:02 +00007108 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007109 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007110 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007111 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7112 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007113 return true;
7114
Richard Smith57aae072016-12-28 02:37:25 +00007115 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7116 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007117 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007118 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007119 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007120 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007121 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7122 << ClassTemplate->getDeclName();
7123 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007124 }
7125 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007126
Craig Topperc3ec1492014-05-26 06:22:03 +00007127 void *InsertPos = nullptr;
7128 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007129
7130 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007131 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007132 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007133 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007134 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007135
Craig Topperc3ec1492014-05-26 06:22:03 +00007136 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007137
Douglas Gregorf47b9112009-02-25 22:02:03 +00007138 // Check whether we can declare a class template specialization in
7139 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007140 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007141 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7142 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007143 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007144 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007145
Douglas Gregor15301382009-07-30 17:40:51 +00007146 // The canonical type
7147 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007148 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007149 // Build the canonical type that describes the converted template
7150 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007151 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7152 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007153 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007154
7155 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007156 ClassTemplate->getInjectedClassNameSpecialization())) {
7157 // C++ [temp.class.spec]p9b3:
7158 //
7159 // -- The argument list of the specialization shall not be identical
7160 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007161 //
7162 // This rule has since been removed, because it's redundant given DR1495,
7163 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007164 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007165 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007166 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007167 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7168 ClassTemplate->getIdentifier(),
7169 TemplateNameLoc,
7170 Attr,
7171 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007172 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007173 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007174 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007175 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007176 }
Douglas Gregor15301382009-07-30 17:40:51 +00007177
Douglas Gregor2373c592009-05-31 09:31:02 +00007178 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007179 ClassTemplatePartialSpecializationDecl *PrevPartial
7180 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007181 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007182 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007183 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007184 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007185 TemplateParams,
7186 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007187 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007188 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007189 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007190 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00007191 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007192 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007193 Partial->setTemplateParameterListsInfo(
7194 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007195 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007196
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007197 if (!PrevPartial)
7198 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007199 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007200
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007201 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007202 // template specialization, make a note of that.
7203 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7204 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007205
Richard Smith57aae072016-12-28 02:37:25 +00007206 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007207 } else {
7208 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007209 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007210 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007211 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007212 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007213 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007214 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007215 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007216 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007217 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007218 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007219 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007220 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007221 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007222
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007223 if (!PrevDecl)
7224 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007225
David Majnemer678f50b2015-11-18 19:49:19 +00007226 if (CurContext->isDependentContext()) {
7227 // -fms-extensions permits specialization of nested classes without
7228 // fully specializing the outer class(es).
7229 assert(getLangOpts().MicrosoftExt &&
7230 "Only possible with -fms-extensions!");
7231 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7232 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007233 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007234 } else {
7235 CanonType = Context.getTypeDeclType(Specialization);
7236 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007237 }
7238
Douglas Gregor06db9f52009-10-12 20:18:28 +00007239 // C++ [temp.expl.spec]p6:
7240 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007241 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007242 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007243 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007244 // use occurs; no diagnostic is required.
7245 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007246 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007247 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007248 // Is there any previous explicit specialization declaration?
7249 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7250 Okay = true;
7251 break;
7252 }
7253 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007254
Douglas Gregorc854c662010-02-26 06:03:23 +00007255 if (!Okay) {
7256 SourceRange Range(TemplateNameLoc, RAngleLoc);
7257 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7258 << Context.getTypeDeclType(Specialization) << Range;
7259
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007260 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007261 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007262 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007263 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007264 return true;
7265 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007266 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007267
Douglas Gregor2208a292009-09-26 20:57:03 +00007268 // If this is not a friend, note that this is an explicit specialization.
7269 if (TUK != TUK_Friend)
7270 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007271
7272 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007273 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007274 RecordDecl *Def = Specialization->getDefinition();
7275 NamedDecl *Hidden = nullptr;
7276 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7277 SkipBody->ShouldSkip = true;
7278 makeMergedDefinitionVisible(Hidden, KWLoc);
7279 // From here on out, treat this as just a redeclaration.
7280 TUK = TUK_Declaration;
7281 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007282 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007283 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007284 Diag(Def->getLocation(), diag::note_previous_definition);
7285 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007286 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007287 }
7288 }
7289
John McCall659a3372010-12-18 03:30:47 +00007290 if (Attr)
7291 ProcessDeclAttributeList(S, Specialization, Attr);
7292
Richard Smith034b94a2012-08-17 03:20:55 +00007293 // Add alignment attributes if necessary; these attributes are checked when
7294 // the ASTContext lays out the structure.
7295 if (TUK == TUK_Definition) {
7296 AddAlignmentAttributesForRecord(Specialization);
7297 AddMsStructLayoutForRecord(Specialization);
7298 }
7299
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007300 if (ModulePrivateLoc.isValid())
7301 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7302 << (isPartialSpecialization? 1 : 0)
7303 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007304
Douglas Gregord56a91e2009-02-26 22:19:44 +00007305 // Build the fully-sugared type for this class template
7306 // specialization as the user wrote in the specialization
7307 // itself. This means that we'll pretty-print the type retrieved
7308 // from the specialization's declaration the way that the user
7309 // actually wrote the specialization, rather than formatting the
7310 // name based on the "canonical" representation used to store the
7311 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007312 TypeSourceInfo *WrittenTy
7313 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7314 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007315 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007316 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007317 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007318 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007319
Douglas Gregor1e249f82009-02-25 22:18:32 +00007320 // C++ [temp.expl.spec]p9:
7321 // A template explicit specialization is in the scope of the
7322 // namespace in which the template was defined.
7323 //
7324 // We actually implement this paragraph where we set the semantic
7325 // context (in the creation of the ClassTemplateSpecializationDecl),
7326 // but we also maintain the lexical context where the actual
7327 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007328 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007329
Douglas Gregor67a65642009-02-17 23:15:12 +00007330 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007331 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00007332 Specialization->startDefinition();
7333
Douglas Gregor2208a292009-09-26 20:57:03 +00007334 if (TUK == TUK_Friend) {
7335 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7336 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007337 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007338 /*FIXME:*/KWLoc);
7339 Friend->setAccess(AS_public);
7340 CurContext->addDecl(Friend);
7341 } else {
7342 // Add the specialization into its lexical context, so that it can
7343 // be seen when iterating through the list of declarations in that
7344 // context. However, specializations are not found by name lookup.
7345 CurContext->addDecl(Specialization);
7346 }
John McCall48871652010-08-21 09:40:31 +00007347 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007348}
Douglas Gregor333489b2009-03-27 23:10:48 +00007349
John McCall48871652010-08-21 09:40:31 +00007350Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007351 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007352 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007353 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007354 ActOnDocumentableDecl(NewDecl);
7355 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007356}
7357
John McCall4f7ced62010-02-11 01:33:53 +00007358/// \brief Strips various properties off an implicit instantiation
7359/// that has just been explicitly specialized.
7360static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007361 D->dropAttr<DLLImportAttr>();
7362 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007363
Nico Webere4974382014-12-19 23:52:45 +00007364 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007365 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007366}
7367
Nico Webera8f80b32012-01-09 19:52:25 +00007368/// \brief Compute the diagnostic location for an explicit instantiation
7369// declaration or definition.
7370static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007371 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007372 // Explicit instantiations following a specialization have no effect and
7373 // hence no PointOfInstantiation. In that case, walk decl backwards
7374 // until a valid name loc is found.
7375 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007376 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7377 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007378 PrevDiagLoc = Prev->getLocation();
7379 }
7380 assert(PrevDiagLoc.isValid() &&
7381 "Explicit instantiation without point of instantiation?");
7382 return PrevDiagLoc;
7383}
7384
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007385/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007386/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007387/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007388/// new specialization/instantiation will have any effect.
7389///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007390/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007391/// instantiation.
7392///
7393/// \param NewTSK the kind of the new explicit specialization or instantiation.
7394///
7395/// \param PrevDecl the previous declaration of the entity.
7396///
7397/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7398///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007399/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007400/// declaration was instantiated (either implicitly or explicitly).
7401///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007402/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007403/// specialization or instantiation has no effect and should be ignored.
7404///
7405/// \returns true if there was an error that should prevent the introduction of
7406/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007407bool
7408Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7409 TemplateSpecializationKind NewTSK,
7410 NamedDecl *PrevDecl,
7411 TemplateSpecializationKind PrevTSK,
7412 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007413 bool &HasNoEffect) {
7414 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007415
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007416 switch (NewTSK) {
7417 case TSK_Undeclared:
7418 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007419 assert(
7420 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7421 "previous declaration must be implicit!");
7422 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007423
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007424 case TSK_ExplicitSpecialization:
7425 switch (PrevTSK) {
7426 case TSK_Undeclared:
7427 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007428 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007429 // explicitly specialized or has merely been mentioned without any
7430 // instantiation.
7431 return false;
7432
7433 case TSK_ImplicitInstantiation:
7434 if (PrevPointOfInstantiation.isInvalid()) {
7435 // The declaration itself has not actually been instantiated, so it is
7436 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007437 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007438 return false;
7439 }
7440 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007441
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007442 case TSK_ExplicitInstantiationDeclaration:
7443 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007444 assert((PrevTSK == TSK_ImplicitInstantiation ||
7445 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007446 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007447
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007448 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007449 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007450 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007451 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007452 // implicit instantiation to take place, in every translation unit in
7453 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007454 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007455 // Is there any previous explicit specialization declaration?
7456 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7457 return false;
7458 }
7459
Douglas Gregor1d957a32009-10-27 18:42:08 +00007460 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007461 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007462 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007463 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007464
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007465 return true;
7466 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007467
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007468 case TSK_ExplicitInstantiationDeclaration:
7469 switch (PrevTSK) {
7470 case TSK_ExplicitInstantiationDeclaration:
7471 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007472 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007473 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007474
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007475 case TSK_Undeclared:
7476 case TSK_ImplicitInstantiation:
7477 // We're explicitly instantiating something that may have already been
7478 // implicitly instantiated; that's fine.
7479 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007480
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007481 case TSK_ExplicitSpecialization:
7482 // C++0x [temp.explicit]p4:
7483 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007484 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007485 // specialization for that template, the explicit instantiation has no
7486 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007487 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007488 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007489
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007490 case TSK_ExplicitInstantiationDefinition:
7491 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007492 // If an entity is the subject of both an explicit instantiation
7493 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007494 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007495 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007496 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007497
7498 // Explicit instantiations following a specialization have no effect and
7499 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7500 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007501 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7502 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007503 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007504 return false;
7505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007506
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007507 case TSK_ExplicitInstantiationDefinition:
7508 switch (PrevTSK) {
7509 case TSK_Undeclared:
7510 case TSK_ImplicitInstantiation:
7511 // We're explicitly instantiating something that may have already been
7512 // implicitly instantiated; that's fine.
7513 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007514
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007515 case TSK_ExplicitSpecialization:
7516 // C++ DR 259, C++0x [temp.explicit]p4:
7517 // For a given set of template parameters, if an explicit
7518 // instantiation of a template appears after a declaration of
7519 // an explicit specialization for that template, the explicit
7520 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00007521 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007522 << PrevDecl;
7523 Diag(PrevDecl->getLocation(),
7524 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007525 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007526 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007527
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007528 case TSK_ExplicitInstantiationDeclaration:
7529 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007530 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00007531
7532 // C++0x [temp.explicit]p4:
7533 // For a given set of template parameters, if an explicit instantiation
7534 // of a template appears after a declaration of an explicit
7535 // specialization for that template, the explicit instantiation has no
7536 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007537 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00007538 // Is there any previous explicit specialization declaration?
7539 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7540 HasNoEffect = true;
7541 break;
7542 }
7543 }
7544
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007545 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007546
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007547 case TSK_ExplicitInstantiationDefinition:
7548 // C++0x [temp.spec]p5:
7549 // For a given template and a given set of template-arguments,
7550 // - an explicit instantiation definition shall appear at most once
7551 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007552
7553 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7554 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00007555 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007556 : diag::err_explicit_instantiation_duplicate)
7557 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00007558 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00007559 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007560 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007561 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007562 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007564
David Blaikie83d382b2011-09-23 05:06:16 +00007565 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007566}
7567
John McCallb9c78482010-04-08 09:05:18 +00007568/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00007569/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00007570///
James Dennettf14a6e52012-06-15 22:23:43 +00007571/// The only possible way to get a dependent function template specialization
7572/// is with a friend declaration, like so:
7573///
7574/// \code
7575/// template \<class T> void foo(T);
7576/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00007577/// friend void foo<>(T);
7578/// };
James Dennettf14a6e52012-06-15 22:23:43 +00007579/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00007580///
7581/// There really isn't any useful analysis we can do here, so we
7582/// just store the information.
7583bool
7584Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7585 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7586 LookupResult &Previous) {
7587 // Remove anything from Previous that isn't a function template in
7588 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00007589 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00007590 LookupResult::Filter F = Previous.makeFilter();
7591 while (F.hasNext()) {
7592 NamedDecl *D = F.next()->getUnderlyingDecl();
7593 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00007594 !FDLookupContext->InEnclosingNamespaceSetOf(
7595 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00007596 F.erase();
7597 }
7598 F.done();
7599
7600 // Should this be diagnosed here?
7601 if (Previous.empty()) return true;
7602
7603 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7604 ExplicitTemplateArgs);
7605 return false;
7606}
7607
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007608/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007609/// specialization.
7610///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007611/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007612/// explicit function template specialization. On successful completion,
7613/// the function declaration \p FD will become a function template
7614/// specialization.
7615///
7616/// \param FD the function declaration, which will be updated to become a
7617/// function template specialization.
7618///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007619/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7620/// if any. Note that this may be valid info even when 0 arguments are
7621/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7622/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007623///
Francois Pichet3a44e432011-07-08 06:21:47 +00007624/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007625/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007626bool Sema::CheckFunctionTemplateSpecialization(
7627 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7628 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007629 // The set of function template specializations that could match this
7630 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00007631 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007632 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7633 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007634
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007635 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7636 ConvertedTemplateArgs;
7637
Sebastian Redl50c68252010-08-31 00:36:30 +00007638 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00007639 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7640 I != E; ++I) {
7641 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7642 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007643 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007644 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007645 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7646 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007647 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007648
Richard Smith574f4f62013-01-14 05:37:29 +00007649 // When matching a constexpr member function template specialization
7650 // against the primary template, we don't yet know whether the
7651 // specialization has an implicit 'const' (because we don't know whether
7652 // it will be a static member function until we know which template it
7653 // specializes), so adjust it now assuming it specializes this template.
7654 QualType FT = FD->getType();
7655 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007656 CXXMethodDecl *OldMD =
7657 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00007658 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007659 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00007660 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7661 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007662 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007663 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00007664 }
7665 }
7666
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007667 TemplateArgumentListInfo Args;
7668 if (ExplicitTemplateArgs)
7669 Args = *ExplicitTemplateArgs;
7670
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007671 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007672 // A trailing template-argument can be left unspecified in the
7673 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007674 // provided it can be deduced from the function argument type.
7675 // Perform template argument deduction to determine whether we may be
7676 // specializing this template.
7677 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00007678 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007679 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00007680 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7681 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00007682 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7683 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007684 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007685 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00007686 FailedCandidates.addCandidate().set(
7687 I.getPair(), FunTmpl->getTemplatedDecl(),
7688 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007689 (void)TDK;
7690 continue;
7691 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007692
Artem Belevich64135c32016-12-08 19:38:13 +00007693 // Target attributes are part of the cuda function signature, so
7694 // the deduced template's cuda target must match that of the
7695 // specialization. Given that C++ template deduction does not
7696 // take target attributes into account, we reject candidates
7697 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007698 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00007699 IdentifyCUDATarget(Specialization,
7700 /* IgnoreImplicitHDAttributes = */ true) !=
7701 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007702 FailedCandidates.addCandidate().set(
7703 I.getPair(), FunTmpl->getTemplatedDecl(),
7704 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7705 continue;
7706 }
7707
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007708 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007709 if (ExplicitTemplateArgs)
7710 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00007711 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007712 }
7713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007714
Douglas Gregor5de279c2009-09-26 03:41:46 +00007715 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007716 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007717 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007718 FD->getLocation(),
7719 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7720 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00007721 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007722 PDiag(diag::note_function_template_spec_matched));
7723
John McCall58cc69d2010-01-27 01:50:18 +00007724 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007725 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007726
7727 // Ignore access information; it doesn't figure into redeclaration checking.
7728 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007729
Nathan Wilson83839122016-04-09 02:55:27 +00007730 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7731 // an explicit specialization (14.8.3) [...] of a concept definition.
7732 if (Specialization->getPrimaryTemplate()->isConcept()) {
7733 Diag(FD->getLocation(), diag::err_concept_specialized)
7734 << 0 /*function*/ << 1 /*explicitly specialized*/;
7735 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7736 return true;
7737 }
7738
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007739 FunctionTemplateSpecializationInfo *SpecInfo
7740 = Specialization->getTemplateSpecializationInfo();
7741 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007742
7743 // Note: do not overwrite location info if previous template
7744 // specialization kind was explicit.
7745 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00007746 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00007747 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00007748 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7749 // function can differ from the template declaration with respect to
7750 // the constexpr specifier.
7751 Specialization->setConstexpr(FD->isConstexpr());
7752 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007753
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007754 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00007755 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00007756
7757 // If this is a friend declaration, then we're not really declaring
7758 // an explicit specialization.
7759 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007760
Douglas Gregor54888652009-10-07 00:13:32 +00007761 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00007762 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007763 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00007764 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007765 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007766 false))
Douglas Gregor54888652009-10-07 00:13:32 +00007767 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007768
7769 // C++ [temp.expl.spec]p6:
7770 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007771 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007772 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007773 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007774 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007775 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007776 if (!isFriend &&
7777 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007778 TSK_ExplicitSpecialization,
7779 Specialization,
7780 SpecInfo->getTemplateSpecializationKind(),
7781 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007782 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007783 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00007784
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007785 // Mark the prior declaration as an explicit specialization, so that later
7786 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007787 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007788 // Since explicit specializations do not inherit '=delete' from their
7789 // primary function template - check if the 'specialization' that was
7790 // implicitly generated (during template argument deduction for partial
7791 // ordering) from the most specialized of all the function templates that
7792 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7793 // first check that it was implicitly generated during template argument
7794 // deduction by making sure it wasn't referenced, and then reset the deleted
7795 // flag to not-deleted, so that we can inherit that information from 'FD'.
7796 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7797 !Specialization->getCanonicalDecl()->isReferenced()) {
7798 assert(
7799 Specialization->getCanonicalDecl() == Specialization &&
7800 "This must be the only existing declaration of this specialization");
7801 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007802 }
John McCall816d75b2010-03-24 07:46:06 +00007803 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007804 MarkUnusedFileScopedDecl(Specialization);
7805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007806
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007807 // Turn the given function declaration into a function template
7808 // specialization, with the template arguments from the previous
7809 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007810 // Take copies of (semantic and syntactic) template argument lists.
7811 const TemplateArgumentList* TemplArgs = new (Context)
7812 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007813 FD->setFunctionTemplateSpecialization(
7814 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7815 SpecInfo->getTemplateSpecializationKind(),
7816 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007817
Artem Belevich64135c32016-12-08 19:38:13 +00007818 // A function template specialization inherits the target attributes
7819 // of its template. (We require the attributes explicitly in the
7820 // code to match, but a template may have implicit attributes by
7821 // virtue e.g. of being constexpr, and it passes these implicit
7822 // attributes on to its specializations.)
7823 if (LangOpts.CUDA)
7824 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
7825
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007826 // The "previous declaration" for this function template specialization is
7827 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007828 Previous.clear();
7829 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007830 return false;
7831}
7832
Douglas Gregor86d142a2009-10-08 07:24:58 +00007833/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007834/// specialization.
7835///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007836/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007837/// explicit member function specialization. On successful completion,
7838/// the function declaration \p FD will become a member function
7839/// specialization.
7840///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007841/// \param Member the member declaration, which will be updated to become a
7842/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007843///
John McCall1f82f242009-11-18 22:49:29 +00007844/// \param Previous the set of declarations, one of which may be specialized
7845/// by this function specialization; the set will be modified to contain the
7846/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007847bool
John McCall1f82f242009-11-18 22:49:29 +00007848Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007849 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007850
Douglas Gregor86d142a2009-10-08 07:24:58 +00007851 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007852 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007853 NamedDecl *Instantiation = nullptr;
7854 NamedDecl *InstantiatedFrom = nullptr;
7855 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007856
John McCall1f82f242009-11-18 22:49:29 +00007857 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007858 // Nowhere to look anyway.
7859 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007860 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7861 I != E; ++I) {
7862 NamedDecl *D = (*I)->getUnderlyingDecl();
7863 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007864 QualType Adjusted = Function->getType();
7865 if (!hasExplicitCallingConv(Adjusted))
7866 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7867 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007868 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007869 Instantiation = Method;
7870 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007871 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007872 break;
7873 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007874 }
7875 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007876 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007877 VarDecl *PrevVar;
7878 if (Previous.isSingleResult() &&
7879 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007880 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007881 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007882 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007883 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007884 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007885 }
7886 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007887 CXXRecordDecl *PrevRecord;
7888 if (Previous.isSingleResult() &&
7889 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007890 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007891 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007892 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007893 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007894 }
Richard Smith7d137e32012-03-23 03:33:32 +00007895 } else if (isa<EnumDecl>(Member)) {
7896 EnumDecl *PrevEnum;
7897 if (Previous.isSingleResult() &&
7898 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007899 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007900 Instantiation = PrevEnum;
7901 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7902 MSInfo = PrevEnum->getMemberSpecializationInfo();
7903 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007905
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007906 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007907 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007908 // specializations are always out-of-line, the caller will complain about
7909 // this mismatch later.
7910 return false;
7911 }
John McCalle820e5e2010-04-13 20:37:33 +00007912
7913 // If this is a friend, just bail out here before we start turning
7914 // things into explicit specializations.
7915 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7916 // Preserve instantiation information.
7917 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7918 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7919 cast<CXXMethodDecl>(InstantiatedFrom),
7920 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7921 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7922 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7923 cast<CXXRecordDecl>(InstantiatedFrom),
7924 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7925 }
7926
7927 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007928 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007929 return false;
7930 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007931
Douglas Gregor86d142a2009-10-08 07:24:58 +00007932 // Make sure that this is a specialization of a member.
7933 if (!InstantiatedFrom) {
7934 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7935 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007936 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7937 return true;
7938 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007939
Douglas Gregor06db9f52009-10-12 20:18:28 +00007940 // C++ [temp.expl.spec]p6:
7941 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007942 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007943 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007944 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007945 // use occurs; no diagnostic is required.
7946 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007947
Abramo Bagnara8075c852010-06-12 07:44:57 +00007948 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007949 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7950 TSK_ExplicitSpecialization,
7951 Instantiation,
7952 MSInfo->getTemplateSpecializationKind(),
7953 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007954 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007955 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007956
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007957 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007958 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007959 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007960 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007961 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007962 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007963
Douglas Gregor86d142a2009-10-08 07:24:58 +00007964 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007965 // the original declaration to note that it is an explicit specialization
7966 // (if it was previously an implicit instantiation). This latter step
7967 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007968 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007969 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7970 if (InstantiationFunction->getTemplateSpecializationKind() ==
7971 TSK_ImplicitInstantiation) {
7972 InstantiationFunction->setTemplateSpecializationKind(
7973 TSK_ExplicitSpecialization);
7974 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007975 // Explicit specializations of member functions of class templates do not
7976 // inherit '=delete' from the member function they are specializing.
7977 if (InstantiationFunction->isDeleted()) {
7978 assert(InstantiationFunction->getCanonicalDecl() ==
7979 InstantiationFunction);
Richard Smith5f274382016-09-28 23:55:27 +00007980 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007981 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007983
Douglas Gregor86d142a2009-10-08 07:24:58 +00007984 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7985 cast<CXXMethodDecl>(InstantiatedFrom),
7986 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007987 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007988 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007989 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7990 if (InstantiationVar->getTemplateSpecializationKind() ==
7991 TSK_ImplicitInstantiation) {
7992 InstantiationVar->setTemplateSpecializationKind(
7993 TSK_ExplicitSpecialization);
7994 InstantiationVar->setLocation(Member->getLocation());
7995 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007996
Larisse Voufo39a1e502013-08-06 01:03:05 +00007997 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7998 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007999 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00008000 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008001 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
8002 if (InstantiationClass->getTemplateSpecializationKind() ==
8003 TSK_ImplicitInstantiation) {
8004 InstantiationClass->setTemplateSpecializationKind(
8005 TSK_ExplicitSpecialization);
8006 InstantiationClass->setLocation(Member->getLocation());
8007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008008
Douglas Gregor86d142a2009-10-08 07:24:58 +00008009 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008010 cast<CXXRecordDecl>(InstantiatedFrom),
8011 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00008012 } else {
8013 assert(isa<EnumDecl>(Member) && "Only member enums remain");
8014 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
8015 if (InstantiationEnum->getTemplateSpecializationKind() ==
8016 TSK_ImplicitInstantiation) {
8017 InstantiationEnum->setTemplateSpecializationKind(
8018 TSK_ExplicitSpecialization);
8019 InstantiationEnum->setLocation(Member->getLocation());
8020 }
8021
8022 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
8023 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00008024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008025
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008026 // Save the caller the trouble of having to figure out which declaration
8027 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008028 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008029 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008030 return false;
8031}
8032
Douglas Gregore47f5a72009-10-14 23:41:34 +00008033/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008034///
8035/// \returns true if a serious error occurs, false otherwise.
8036static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008037 SourceLocation InstLoc,
8038 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008039 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8040 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008041
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008042 if (CurContext->isRecord()) {
8043 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8044 << D;
8045 return true;
8046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008047
Richard Smith050d2612011-10-18 02:28:33 +00008048 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008049 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008050 // template. If the name declared in the explicit instantiation is an
8051 // unqualified name, the explicit instantiation shall appear in the
8052 // namespace where its template is declared or, if that namespace is inline
8053 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008054 //
8055 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008056 if (WasQualifiedName) {
8057 if (CurContext->Encloses(OrigContext))
8058 return false;
8059 } else {
8060 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8061 return false;
8062 }
8063
8064 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8065 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008066 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008067 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008068 diag::err_explicit_instantiation_out_of_scope :
8069 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008070 << D << NS;
8071 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008072 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008073 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008074 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8075 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8076 << D << NS;
8077 } else
8078 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008079 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008080 diag::err_explicit_instantiation_must_be_global :
8081 diag::warn_explicit_instantiation_must_be_global_0x)
8082 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008083 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008084 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008085}
8086
8087/// \brief Determine whether the given scope specifier has a template-id in it.
8088static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8089 if (!SS.isSet())
8090 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008091
Richard Smith050d2612011-10-18 02:28:33 +00008092 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008093 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008094 // or a static data member of a class template specialization, the name of
8095 // the class template specialization in the qualified-id for the member
8096 // name shall be a simple-template-id.
8097 //
8098 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008099 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8100 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008101 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008102 if (isa<TemplateSpecializationType>(T))
8103 return true;
8104
8105 return false;
8106}
8107
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008108/// Make a dllexport or dllimport attr on a class template specialization take
8109/// effect.
8110static void dllExportImportClassTemplateSpecialization(
8111 Sema &S, ClassTemplateSpecializationDecl *Def) {
8112 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8113 assert(A && "dllExportImportClassTemplateSpecialization called "
8114 "on Def without dllexport or dllimport");
8115
8116 // We reject explicit instantiations in class scope, so there should
8117 // never be any delayed exported classes to worry about.
8118 assert(S.DelayedDllExportClasses.empty() &&
8119 "delayed exports present at explicit instantiation");
8120 S.checkClassLevelDLLAttribute(Def);
8121
8122 // Propagate attribute to base class templates.
8123 for (auto &B : Def->bases()) {
8124 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8125 B.getType()->getAsCXXRecordDecl()))
8126 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8127 }
8128
8129 S.referenceDLLExportedClassMethods();
8130}
8131
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008132// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00008133DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008134Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008135 SourceLocation ExternLoc,
8136 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008137 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00008138 SourceLocation KWLoc,
8139 const CXXScopeSpec &SS,
8140 TemplateTy TemplateD,
8141 SourceLocation TemplateNameLoc,
8142 SourceLocation LAngleLoc,
8143 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00008144 SourceLocation RAngleLoc,
8145 AttributeList *Attr) {
8146 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008147 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008148 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008149 // Check that the specialization uses the same tag kind as the
8150 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008151 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8152 assert(Kind != TTK_Enum &&
8153 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008154
Richard Trieu265c3442016-04-05 21:13:54 +00008155 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8156
8157 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008158 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8159 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008160 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008161 return true;
8162 }
8163
Douglas Gregord9034f02009-05-14 16:41:31 +00008164 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008165 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008166 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008167 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008168 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008169 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008170 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008171 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008172 diag::note_previous_use);
8173 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8174 }
8175
Douglas Gregore47f5a72009-10-14 23:41:34 +00008176 // C++0x [temp.explicit]p2:
8177 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008178 // definition and an explicit instantiation declaration. An explicit
8179 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008180 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8181 ? TSK_ExplicitInstantiationDefinition
8182 : TSK_ExplicitInstantiationDeclaration;
8183
8184 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8185 // Check for dllexport class template instantiation declarations.
8186 for (AttributeList *A = Attr; A; A = A->getNext()) {
8187 if (A->getKind() == AttributeList::AT_DLLExport) {
8188 Diag(ExternLoc,
8189 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8190 Diag(A->getLoc(), diag::note_attribute);
8191 break;
8192 }
8193 }
8194
8195 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8196 Diag(ExternLoc,
8197 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8198 Diag(A->getLocation(), diag::note_attribute);
8199 }
8200 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008201
Hans Wennborga86a83b2016-05-26 19:42:56 +00008202 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8203 // instantiation declarations for most purposes.
8204 bool DLLImportExplicitInstantiationDef = false;
8205 if (TSK == TSK_ExplicitInstantiationDefinition &&
8206 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8207 // Check for dllimport class template instantiation definitions.
8208 bool DLLImport =
8209 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8210 for (AttributeList *A = Attr; A; A = A->getNext()) {
8211 if (A->getKind() == AttributeList::AT_DLLImport)
8212 DLLImport = true;
8213 if (A->getKind() == AttributeList::AT_DLLExport) {
8214 // dllexport trumps dllimport here.
8215 DLLImport = false;
8216 break;
8217 }
8218 }
8219 if (DLLImport) {
8220 TSK = TSK_ExplicitInstantiationDeclaration;
8221 DLLImportExplicitInstantiationDef = true;
8222 }
8223 }
8224
Douglas Gregora1f49972009-05-13 00:25:59 +00008225 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008226 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008227 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008228
8229 // Check that the template argument list is well-formed for this
8230 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008231 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008232 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8233 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008234 return true;
8235
Douglas Gregora1f49972009-05-13 00:25:59 +00008236 // Find the class template specialization declaration that
8237 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008238 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008239 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008240 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008241
Abramo Bagnara8075c852010-06-12 07:44:57 +00008242 TemplateSpecializationKind PrevDecl_TSK
8243 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8244
Douglas Gregor54888652009-10-07 00:13:32 +00008245 // C++0x [temp.explicit]p2:
8246 // [...] An explicit instantiation shall appear in an enclosing
8247 // namespace of its template. [...]
8248 //
8249 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008250 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8251 SS.isSet()))
8252 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008253
Craig Topperc3ec1492014-05-26 06:22:03 +00008254 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008255
Abramo Bagnara8075c852010-06-12 07:44:57 +00008256 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008257 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008258 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008259 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008260 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008261 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008262 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008263
Abramo Bagnara8075c852010-06-12 07:44:57 +00008264 // Even though HasNoEffect == true means that this explicit instantiation
8265 // has no effect on semantics, we go on to put its syntax in the AST.
8266
8267 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8268 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008269 // Since the only prior class template specialization with these
8270 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008271 // declaration node as our own, updating the source location
8272 // for the template name to reflect our new declaration.
8273 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008274 Specialization = PrevDecl;
8275 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008276 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008277 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008278
8279 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8280 DLLImportExplicitInstantiationDef) {
8281 // The new specialization might add a dllimport attribute.
8282 HasNoEffect = false;
8283 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008284 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008285
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008286 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008287 // Create a new class template specialization declaration node for
8288 // this explicit specialization.
8289 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008290 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008291 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008292 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008293 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008294 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008295 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00008296 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008297
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008298 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008299 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008300 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008301 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008302 }
8303
8304 // Build the fully-sugared type for this explicit instantiation as
8305 // the user wrote in the explicit instantiation itself. This means
8306 // that we'll pretty-print the type retrieved from the
8307 // specialization's declaration the way that the user actually wrote
8308 // the explicit instantiation, rather than formatting the name based
8309 // on the "canonical" representation used to store the template
8310 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008311 TypeSourceInfo *WrittenTy
8312 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8313 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008314 Context.getTypeDeclType(Specialization));
8315 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008316
Abramo Bagnara8075c852010-06-12 07:44:57 +00008317 // Set source locations for keywords.
8318 Specialization->setExternLoc(ExternLoc);
8319 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008320 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008321
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008322 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Rafael Espindola0b062072012-01-03 06:04:21 +00008323 if (Attr)
8324 ProcessDeclAttributeList(S, Specialization, Attr);
8325
Abramo Bagnara8075c852010-06-12 07:44:57 +00008326 // Add the explicit instantiation into its lexical context. However,
8327 // since explicit instantiations are never found by name lookup, we
8328 // just put it into the declaration context directly.
8329 Specialization->setLexicalDeclContext(CurContext);
8330 CurContext->addDecl(Specialization);
8331
8332 // Syntax is now OK, so return if it has no other effect on semantics.
8333 if (HasNoEffect) {
8334 // Set the template specialization kind.
8335 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008336 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008337 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008338
8339 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008340 // A definition of a class template or class member template
8341 // shall be in scope at the point of the explicit instantiation of
8342 // the class template or class member template.
8343 //
8344 // This check comes when we actually try to perform the
8345 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008346 ClassTemplateSpecializationDecl *Def
8347 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008348 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008349 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00008350 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008351 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008352 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008353 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8354 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008355
Douglas Gregor1d957a32009-10-27 18:42:08 +00008356 // Instantiate the members of this class template specialization.
8357 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008358 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00008359 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008360 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008361 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8362 // TSK_ExplicitInstantiationDefinition
8363 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00008364 (TSK == TSK_ExplicitInstantiationDefinition ||
8365 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00008366 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008367 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008368
Hans Wennborgc0875502015-06-09 00:39:05 +00008369 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00008370 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8371 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00008372 // In the MS ABI, an explicit instantiation definition can add a dll
8373 // attribute to a template with a previous instantiation declaration.
8374 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008375 auto *A = cast<InheritableAttr>(
8376 getDLLAttr(Specialization)->clone(getASTContext()));
8377 A->setInherited(true);
8378 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008379 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008380 }
8381 }
8382
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008383 // Fix a TSK_ImplicitInstantiation followed by a
8384 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008385 bool NewlyDLLExported =
8386 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8387 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008388 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8389 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8390 // In the MS ABI, an explicit instantiation definition can add a dll
8391 // attribute to a template with a previous implicit instantiation.
8392 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8393 // avoid potentially strange codegen behavior. For example, if we extend
8394 // this conditional to dllimport, and we have a source file calling a
8395 // method on an implicitly instantiated template class instance and then
8396 // declaring a dllimport explicit instantiation definition for the same
8397 // template class, the codegen for the method call will not respect the
8398 // dllimport, while it will with cl. The Def will already have the DLL
8399 // attribute, since the Def and Specialization will be the same in the
8400 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8401 // attribute to the Specialization; we just need to make it take effect.
8402 assert(Def == Specialization &&
8403 "Def and Specialization should match for implicit instantiation");
8404 dllExportImportClassTemplateSpecialization(*this, Def);
8405 }
8406
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008407 // Set the template specialization kind. Make sure it is set before
8408 // instantiating the members which will trigger ASTConsumer callbacks.
8409 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008410 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008411 } else {
8412
8413 // Set the template specialization kind.
8414 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008415 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008416
John McCall48871652010-08-21 09:40:31 +00008417 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008418}
8419
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008420// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008421DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008422Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008423 SourceLocation ExternLoc,
8424 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008425 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008426 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008427 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008428 IdentifierInfo *Name,
8429 SourceLocation NameLoc,
8430 AttributeList *Attr) {
8431
Douglas Gregord6ab8742009-05-28 23:31:59 +00008432 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008433 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008434 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008435 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008436 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008437 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008438 SourceLocation(), false, TypeResult(),
8439 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00008440 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8441
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008442 if (!TagD)
8443 return true;
8444
John McCall48871652010-08-21 09:40:31 +00008445 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00008446 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008447
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008448 if (Tag->isInvalidDecl())
8449 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008450
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008451 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8452 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8453 if (!Pattern) {
8454 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8455 << Context.getTypeDeclType(Record);
8456 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8457 return true;
8458 }
8459
Douglas Gregore47f5a72009-10-14 23:41:34 +00008460 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008461 // If the explicit instantiation is for a class or member class, the
8462 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00008463 // simple-template-id.
8464 //
8465 // C++98 has the same restriction, just worded differently.
8466 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00008467 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008468 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008469
Douglas Gregore47f5a72009-10-14 23:41:34 +00008470 // C++0x [temp.explicit]p2:
8471 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008472 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00008473 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00008474 TemplateSpecializationKind TSK
8475 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8476 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008477
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008478 // C++0x [temp.explicit]p2:
8479 // [...] An explicit instantiation shall appear in an enclosing
8480 // namespace of its template. [...]
8481 //
8482 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008483 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008484
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008485 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008486 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00008487 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008488 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00008489 PrevDecl = Record;
8490 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008491 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008492 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008493 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008494 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008495 PrevDecl,
8496 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008497 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008498 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008499 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00008500 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008501 return TagD;
8502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008503
Douglas Gregor12e49d32009-10-15 22:53:21 +00008504 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008505 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008506 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00008507 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008508 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00008509 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008510 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008511 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00008512 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00008513 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8514 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00008515 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8516 << Pattern;
8517 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008518 } else {
8519 if (InstantiateClass(NameLoc, Record, Def,
8520 getTemplateInstantiationArgs(Record),
8521 TSK))
8522 return true;
8523
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008524 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00008525 if (!RecordDef)
8526 return true;
8527 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008528 }
8529
Douglas Gregor1d957a32009-10-27 18:42:08 +00008530 // Instantiate all of the members of the class.
8531 InstantiateClassMembers(NameLoc, RecordDef,
8532 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008533
Douglas Gregor88d292c2010-05-13 16:44:06 +00008534 if (TSK == TSK_ExplicitInstantiationDefinition)
8535 MarkVTableUsed(NameLoc, RecordDef, true);
8536
Mike Stump87c57ac2009-05-16 07:39:55 +00008537 // FIXME: We don't have any representation for explicit instantiations of
8538 // member classes. Such a representation is not needed for compilation, but it
8539 // should be available for clients that want to see all of the declarations in
8540 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008541 return TagD;
8542}
8543
John McCallfaf5fb42010-08-26 23:41:50 +00008544DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8545 SourceLocation ExternLoc,
8546 SourceLocation TemplateLoc,
8547 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008548 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008549 // TODO: check if/when DNInfo should replace Name.
8550 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8551 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00008552 if (!Name) {
8553 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008554 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008555 diag::err_explicit_instantiation_requires_name)
8556 << D.getDeclSpec().getSourceRange()
8557 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008558
Douglas Gregor450f00842009-09-25 18:43:00 +00008559 return true;
8560 }
8561
8562 // The scope passed in may not be a decl scope. Zip up the scope tree until
8563 // we find one that is.
8564 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8565 (S->getFlags() & Scope::TemplateParamScope) != 0)
8566 S = S->getParent();
8567
8568 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00008569 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8570 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00008571 if (R.isNull())
8572 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008573
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008574 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00008575 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008576 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00008577 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008578 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8579 << Name;
8580 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008581 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008582 != DeclSpec::SCS_unspecified) {
8583 // Complain about then remove the storage class specifier.
8584 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8585 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008586
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008587 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00008588 }
8589
Douglas Gregor3c74d412009-10-14 20:14:33 +00008590 // C++0x [temp.explicit]p1:
8591 // [...] An explicit instantiation of a function template shall not use the
8592 // inline or constexpr specifiers.
8593 // Presumably, this also applies to member functions of class templates as
8594 // well.
Richard Smith83c19292011-10-18 03:44:03 +00008595 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008596 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008597 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00008598 diag::err_explicit_instantiation_inline :
8599 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00008600 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00008601 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00008602 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8603 // not already specified.
8604 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8605 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008606
Nathan Wilsonde498452016-02-08 05:34:00 +00008607 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8608 // applied only to the definition of a function template or variable template,
8609 // declared in namespace scope.
8610 if (D.getDeclSpec().isConceptSpecified()) {
8611 Diag(D.getDeclSpec().getConceptSpecLoc(),
8612 diag::err_concept_specified_specialization) << 0;
8613 return true;
8614 }
8615
Richard Smith19a311a2017-02-09 22:47:51 +00008616 // A deduction guide is not on the list of entities that can be explicitly
8617 // instantiated.
8618 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8619 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8620 << /*explicit instantiation*/ 0;
8621 return true;
8622 }
8623
Douglas Gregore47f5a72009-10-14 23:41:34 +00008624 // C++0x [temp.explicit]p2:
8625 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008626 // definition and an explicit instantiation declaration. An explicit
8627 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00008628 TemplateSpecializationKind TSK
8629 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8630 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008631
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008632 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00008633 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00008634
8635 if (!R->isFunctionType()) {
8636 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008637 // A [...] static data member of a class template can be explicitly
8638 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008639 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008640 // C++1y [temp.explicit]p1:
8641 // A [...] variable [...] template specialization can be explicitly
8642 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00008643 if (Previous.isAmbiguous())
8644 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008645
John McCall67c00872009-12-02 08:25:40 +00008646 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00008647 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008648
Larisse Voufo39a1e502013-08-06 01:03:05 +00008649 if (!PrevTemplate) {
8650 if (!Prev || !Prev->isStaticDataMember()) {
8651 // We expect to see a data data member here.
8652 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8653 << Name;
8654 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8655 P != PEnd; ++P)
8656 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8657 return true;
8658 }
8659
8660 if (!Prev->getInstantiatedFromStaticDataMember()) {
8661 // FIXME: Check for explicit specialization?
8662 Diag(D.getIdentifierLoc(),
8663 diag::err_explicit_instantiation_data_member_not_instantiated)
8664 << Prev;
8665 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8666 // FIXME: Can we provide a note showing where this was declared?
8667 return true;
8668 }
8669 } else {
8670 // Explicitly instantiate a variable template.
8671
8672 // C++1y [dcl.spec.auto]p6:
8673 // ... A program that uses auto or decltype(auto) in a context not
8674 // explicitly allowed in this section is ill-formed.
8675 //
8676 // This includes auto-typed variable template instantiations.
8677 if (R->isUndeducedType()) {
8678 Diag(T->getTypeLoc().getLocStart(),
8679 diag::err_auto_not_allowed_var_inst);
8680 return true;
8681 }
8682
Richard Smithef985ac2013-09-18 02:10:12 +00008683 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8684 // C++1y [temp.explicit]p3:
8685 // If the explicit instantiation is for a variable, the unqualified-id
8686 // in the declaration shall be a template-id.
8687 Diag(D.getIdentifierLoc(),
8688 diag::err_explicit_instantiation_without_template_id)
8689 << PrevTemplate;
8690 Diag(PrevTemplate->getLocation(),
8691 diag::note_explicit_instantiation_here);
8692 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00008693 }
8694
Nathan Wilson83839122016-04-09 02:55:27 +00008695 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8696 // explicit instantiation (14.8.2) [...] of a concept definition.
8697 if (PrevTemplate->isConcept()) {
8698 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8699 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8700 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8701 return true;
8702 }
8703
Richard Smithef985ac2013-09-18 02:10:12 +00008704 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00008705 TemplateArgumentListInfo TemplateArgs =
8706 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00008707
Larisse Voufo39a1e502013-08-06 01:03:05 +00008708 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8709 D.getIdentifierLoc(), TemplateArgs);
8710 if (Res.isInvalid())
8711 return true;
8712
8713 // Ignore access control bits, we don't need them for redeclaration
8714 // checking.
8715 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00008716 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008717
Douglas Gregore47f5a72009-10-14 23:41:34 +00008718 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008719 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008720 // or a static data member of a class template specialization, the name of
8721 // the class template specialization in the qualified-id for the member
8722 // name shall be a simple-template-id.
8723 //
8724 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008725 //
Richard Smith5977d872013-09-18 21:55:14 +00008726 // This does not apply to variable template specializations, where the
8727 // template-id is in the unqualified-id instead.
8728 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008729 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008730 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008731 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008732
Douglas Gregore47f5a72009-10-14 23:41:34 +00008733 // Check the scope of this explicit instantiation.
8734 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008735
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008736 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00008737 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8738 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008739 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008740 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00008741 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008742 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008743
Larisse Voufo39a1e502013-08-06 01:03:05 +00008744 if (!HasNoEffect) {
8745 // Instantiate static data member or variable template.
8746
8747 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8748 if (PrevTemplate) {
8749 // Merge attributes.
8750 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8751 ProcessDeclAttributeList(S, Prev, Attr);
8752 }
8753 if (TSK == TSK_ExplicitInstantiationDefinition)
8754 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8755 }
8756
8757 // Check the new variable specialization against the parsed input.
8758 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8759 Diag(T->getTypeLoc().getLocStart(),
8760 diag::err_invalid_var_template_spec_type)
8761 << 0 << PrevTemplate << R << Prev->getType();
8762 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8763 << 2 << PrevTemplate->getDeclName();
8764 return true;
8765 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008766
Douglas Gregor450f00842009-09-25 18:43:00 +00008767 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00008768 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008770
8771 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00008772 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00008773 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00008774 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00008775 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00008776 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00008777 HasExplicitTemplateArgs = true;
8778 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008779
Douglas Gregor450f00842009-09-25 18:43:00 +00008780 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008781 // A [...] function [...] can be explicitly instantiated from its template.
8782 // A member function [...] of a class template can be explicitly
8783 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008784 // template.
John McCall58cc69d2010-01-27 01:50:18 +00008785 UnresolvedSet<8> Matches;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008786 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008787 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00008788 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8789 P != PEnd; ++P) {
8790 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00008791 if (!HasExplicitTemplateArgs) {
8792 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00008793 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
8794 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00008795 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00008796 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008797
John McCall58cc69d2010-01-27 01:50:18 +00008798 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008799 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8800 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00008801 }
Douglas Gregor450f00842009-09-25 18:43:00 +00008802 }
8803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008804
Douglas Gregor450f00842009-09-25 18:43:00 +00008805 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8806 if (!FunTmpl)
8807 continue;
8808
Larisse Voufo98b20f12013-07-19 23:00:19 +00008809 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008810 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008811 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008812 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00008813 (HasExplicitTemplateArgs ? &TemplateArgs
8814 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00008815 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008816 // Keep track of almost-matches.
8817 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00008818 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008819 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008820 (void)TDK;
8821 continue;
8822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008823
Artem Belevich64135c32016-12-08 19:38:13 +00008824 // Target attributes are part of the cuda function signature, so
8825 // the cuda target of the instantiated function must match that of its
8826 // template. Given that C++ template deduction does not take
8827 // target attributes into account, we reject candidates here that
8828 // have a different target.
8829 if (LangOpts.CUDA &&
8830 IdentifyCUDATarget(Specialization,
8831 /* IgnoreImplicitHDAttributes = */ true) !=
8832 IdentifyCUDATarget(Attr)) {
8833 FailedCandidates.addCandidate().set(
8834 P.getPair(), FunTmpl->getTemplatedDecl(),
8835 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8836 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008837 }
8838
John McCall58cc69d2010-01-27 01:50:18 +00008839 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008840 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008841
Douglas Gregor450f00842009-09-25 18:43:00 +00008842 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008843 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008844 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008845 D.getIdentifierLoc(),
8846 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8847 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8848 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008849
John McCall58cc69d2010-01-27 01:50:18 +00008850 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008851 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008852
8853 // Ignore access control bits, we don't need them for redeclaration checking.
8854 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008855
Alexey Bataev73983912014-11-06 10:10:50 +00008856 // C++11 [except.spec]p4
8857 // In an explicit instantiation an exception-specification may be specified,
8858 // but is not required.
8859 // If an exception-specification is specified in an explicit instantiation
8860 // directive, it shall be compatible with the exception-specifications of
8861 // other declarations of that function.
8862 if (auto *FPT = R->getAs<FunctionProtoType>())
8863 if (FPT->hasExceptionSpec()) {
8864 unsigned DiagID =
8865 diag::err_mismatched_exception_spec_explicit_instantiation;
8866 if (getLangOpts().MicrosoftExt)
8867 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8868 bool Result = CheckEquivalentExceptionSpec(
8869 PDiag(DiagID) << Specialization->getType(),
8870 PDiag(diag::note_explicit_instantiation_here),
8871 Specialization->getType()->getAs<FunctionProtoType>(),
8872 Specialization->getLocation(), FPT, D.getLocStart());
8873 // In Microsoft mode, mismatching exception specifications just cause a
8874 // warning.
8875 if (!getLangOpts().MicrosoftExt && Result)
8876 return true;
8877 }
8878
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008879 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008880 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008881 diag::err_explicit_instantiation_member_function_not_instantiated)
8882 << Specialization
8883 << (Specialization->getTemplateSpecializationKind() ==
8884 TSK_ExplicitSpecialization);
8885 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8886 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008887 }
8888
Douglas Gregorec9fd132012-01-14 16:38:05 +00008889 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008890 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8891 PrevDecl = Specialization;
8892
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008893 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008894 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008895 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008896 PrevDecl,
8897 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008898 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008899 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008900 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008901
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008902 // FIXME: We may still want to build some representation of this
8903 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008904 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008905 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008906 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008907
8908 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008909 if (Attr)
8910 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008911
Richard Smitheb36ddf2014-04-24 22:45:46 +00008912 if (Specialization->isDefined()) {
8913 // Let the ASTConsumer know that this function has been explicitly
8914 // instantiated now, and its linkage might have changed.
8915 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8916 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008917 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008918
Douglas Gregore47f5a72009-10-14 23:41:34 +00008919 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008920 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008921 // or a static data member of a class template specialization, the name of
8922 // the class template specialization in the qualified-id for the member
8923 // name shall be a simple-template-id.
8924 //
8925 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008926 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008927 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008928 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008929 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008930 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008931 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008932 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008933
Nathan Wilson83839122016-04-09 02:55:27 +00008934 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8935 // explicit instantiation (14.8.2) [...] of a concept definition.
8936 if (FunTmpl && FunTmpl->isConcept() &&
8937 !D.getDeclSpec().isConceptSpecified()) {
8938 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8939 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8940 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8941 return true;
8942 }
8943
Douglas Gregore47f5a72009-10-14 23:41:34 +00008944 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008945 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008946 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008947 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008948 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008949
Douglas Gregor450f00842009-09-25 18:43:00 +00008950 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008951 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008952}
8953
John McCallfaf5fb42010-08-26 23:41:50 +00008954TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008955Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8956 const CXXScopeSpec &SS, IdentifierInfo *Name,
8957 SourceLocation TagLoc, SourceLocation NameLoc) {
8958 // This has to hold, because SS is expected to be defined.
8959 assert(Name && "Expected a name in a dependent tag");
8960
Aaron Ballman4a979672014-01-03 13:56:08 +00008961 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008962 if (!NNS)
8963 return true;
8964
Abramo Bagnara6150c882010-05-11 21:36:43 +00008965 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008966
Douglas Gregorba41d012010-04-24 16:38:41 +00008967 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8968 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008969 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008970 return true;
8971 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008972
Douglas Gregore7c20652011-03-02 00:47:37 +00008973 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008974 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008975 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008976
Douglas Gregore7c20652011-03-02 00:47:37 +00008977 // Create type-source location information for this type.
8978 TypeLocBuilder TLB;
8979 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008980 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008981 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8982 TL.setNameLoc(NameLoc);
8983 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008984}
8985
John McCallfaf5fb42010-08-26 23:41:50 +00008986TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008987Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8988 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008989 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008990 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008991 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008992
Richard Smith0bf8a4922011-10-18 20:49:44 +00008993 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8994 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008995 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008996 diag::warn_cxx98_compat_typename_outside_of_template :
8997 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008998 << FixItHint::CreateRemoval(TypenameLoc);
8999
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009000 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009001 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9002 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009003 if (T.isNull())
9004 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009005
9006 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9007 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009008 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009009 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009010 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009011 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009012 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009013 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009014 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009015 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009016 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009017 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009018
John McCallba7bf592010-08-24 05:47:05 +00009019 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009020}
9021
John McCallfaf5fb42010-08-26 23:41:50 +00009022TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009023Sema::ActOnTypenameType(Scope *S,
9024 SourceLocation TypenameLoc,
9025 const CXXScopeSpec &SS,
9026 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009027 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009028 IdentifierInfo *TemplateII,
9029 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009030 SourceLocation LAngleLoc,
9031 ASTTemplateArgsPtr TemplateArgsIn,
9032 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009033 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9034 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009035 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009036 diag::warn_cxx98_compat_typename_outside_of_template :
9037 diag::ext_typename_outside_of_template)
9038 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009039
Richard Smith74f02342017-01-19 21:00:13 +00009040 // Strangely, non-type results are not ignored by this lookup, so the
9041 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009042 if (TypenameLoc.isValid()) {
9043 auto *LookupRD =
9044 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9045 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9046 Diag(TemplateIILoc,
9047 diag::ext_out_of_line_qualified_id_type_names_constructor)
9048 << TemplateII << 0 /*injected-class-name used as template name*/
9049 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9050 }
Richard Smith74f02342017-01-19 21:00:13 +00009051 }
9052
Douglas Gregorb09518c2011-02-27 22:46:49 +00009053 // Translate the parser's template argument list in our AST format.
9054 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9055 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009056
Douglas Gregorb09518c2011-02-27 22:46:49 +00009057 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009058 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9059 // Construct a dependent template specialization type.
9060 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009061 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009062 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9063 DTN->getQualifier(),
9064 DTN->getIdentifier(),
9065 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009066
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009067 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009068 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009069 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009070 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009071 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9072 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009073 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009074 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009075 SpecTL.setLAngleLoc(LAngleLoc);
9076 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009077 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9078 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009079 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009080 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009081
Richard Smith74f02342017-01-19 21:00:13 +00009082 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009083 if (T.isNull())
9084 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009085
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009086 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009087 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009088 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009089 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009090 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009091 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009092 SpecTL.setLAngleLoc(LAngleLoc);
9093 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009094 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9095 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009096
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009097 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9098 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009099 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009100 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009101
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009102 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9103 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009104}
9105
Douglas Gregorb09518c2011-02-27 22:46:49 +00009106
Richard Smith6f8d2c62012-05-09 05:17:00 +00009107/// Determine whether this failed name lookup should be treated as being
9108/// disabled by a usage of std::enable_if.
9109static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9110 SourceRange &CondRange) {
9111 // We must be looking for a ::type...
9112 if (!II.isStr("type"))
9113 return false;
9114
9115 // ... within an explicitly-written template specialization...
9116 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9117 return false;
9118 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009119 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9120 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9121 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009122 return false;
9123 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00009124 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00009125
9126 // ... which names a complete class template declaration...
9127 const TemplateDecl *EnableIfDecl =
9128 EnableIfTST->getTemplateName().getAsTemplateDecl();
9129 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9130 return false;
9131
9132 // ... called "enable_if".
9133 const IdentifierInfo *EnableIfII =
9134 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9135 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9136 return false;
9137
9138 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009139 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009140 return true;
9141}
9142
Douglas Gregor333489b2009-03-27 23:10:48 +00009143/// \brief Build the type that describes a C++ typename specifier,
9144/// e.g., "typename T::type".
9145QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009146Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009147 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009148 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009149 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009150 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009151 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009152 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009153
John McCall0b66eb32010-05-01 00:40:08 +00009154 DeclContext *Ctx = computeDeclContext(SS);
9155 if (!Ctx) {
9156 // If the nested-name-specifier is dependent and couldn't be
9157 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009158 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009159 return Context.getDependentNameType(Keyword,
9160 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009161 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009162 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009163
John McCall0b66eb32010-05-01 00:40:08 +00009164 // If the nested-name-specifier refers to the current instantiation,
9165 // the "typename" keyword itself is superfluous. In C++03, the
9166 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9167 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009168 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009169
John McCall0b66eb32010-05-01 00:40:08 +00009170 if (RequireCompleteDeclContext(SS, Ctx))
9171 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009172
9173 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009174 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009175 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009176 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009177 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009178 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009179 case LookupResult::NotFound: {
9180 // If we're looking up 'type' within a template named 'enable_if', produce
9181 // a more specific diagnostic.
9182 SourceRange CondRange;
9183 if (isEnableIf(QualifierLoc, II, CondRange)) {
9184 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9185 << Ctx << CondRange;
9186 return QualType();
9187 }
9188
Douglas Gregore40876a2009-10-13 21:16:44 +00009189 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009190 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009191 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009192
9193 case LookupResult::FoundUnresolvedValue: {
9194 // We found a using declaration that is a value. Most likely, the using
9195 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009196 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009197 IILoc);
9198 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9199 << Name << Ctx << FullRange;
9200 if (UnresolvedUsingValueDecl *Using
9201 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009202 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009203 Diag(Loc, diag::note_using_value_decl_missing_typename)
9204 << FixItHint::CreateInsertion(Loc, "typename ");
9205 }
9206 }
9207 // Fall through to create a dependent typename type, from which we can recover
9208 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009209
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009210 case LookupResult::NotFoundInCurrentInstantiation:
9211 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009212 return Context.getDependentNameType(Keyword,
9213 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009214 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009215
9216 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009217 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009218 // C++ [class.qual]p2:
9219 // In a lookup in which function names are not ignored and the
9220 // nested-name-specifier nominates a class C, if the name specified
9221 // after the nested-name-specifier, when looked up in C, is the
9222 // injected-class-name of C [...] then the name is instead considered
9223 // to name the constructor of class C.
9224 //
9225 // Unlike in an elaborated-type-specifier, function names are not ignored
9226 // in typename-specifier lookup. However, they are ignored in all the
9227 // contexts where we form a typename type with no keyword (that is, in
9228 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9229 //
9230 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9231 // ignore functions, but that appears to be an oversight.
9232 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9233 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9234 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9235 FoundRD->isInjectedClassName() &&
9236 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9237 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9238 << &II << 1 << 0 /*'typename' keyword used*/;
9239
Abramo Bagnara6150c882010-05-11 21:36:43 +00009240 // We found a type. Build an ElaboratedType, since the
9241 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009242 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009243 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009244 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009245 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009246 }
9247
Richard Smithee579842017-01-30 20:39:26 +00009248 // C++ [dcl.type.simple]p2:
9249 // A type-specifier of the form
9250 // typename[opt] nested-name-specifier[opt] template-name
9251 // is a placeholder for a deduced class type [...].
9252 if (getLangOpts().CPlusPlus1z) {
9253 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9254 return Context.getElaboratedType(
9255 Keyword, QualifierLoc.getNestedNameSpecifier(),
9256 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9257 QualType(), false));
9258 }
9259 }
Richard Smith600b5262017-01-26 20:40:47 +00009260
Douglas Gregor333489b2009-03-27 23:10:48 +00009261 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009262 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009263 break;
9264
9265 case LookupResult::FoundOverloaded:
9266 DiagID = diag::err_typename_nested_not_type;
9267 Referenced = *Result.begin();
9268 break;
9269
John McCall6538c932009-10-10 05:48:19 +00009270 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009271 return QualType();
9272 }
9273
9274 // If we get here, it's because name lookup did not find a
9275 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009276 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009277 IILoc);
9278 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009279 if (Referenced)
9280 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9281 << Name;
9282 return QualType();
9283}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009284
9285namespace {
9286 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009287 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009288 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009289 SourceLocation Loc;
9290 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009291
Douglas Gregor15acfb92009-08-06 16:20:37 +00009292 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009293 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009294
Mike Stump11289f42009-09-09 15:08:12 +00009295 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009296 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009297 DeclarationName Entity)
9298 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009299 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009300
9301 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009302 /// transformed.
9303 ///
9304 /// For the purposes of type reconstruction, a type has already been
9305 /// transformed if it is NULL or if it is not dependent.
9306 bool AlreadyTransformed(QualType T) {
9307 return T.isNull() || !T->isDependentType();
9308 }
Mike Stump11289f42009-09-09 15:08:12 +00009309
9310 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009311 /// rebuilt.
9312 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009313
Douglas Gregor15acfb92009-08-06 16:20:37 +00009314 /// \brief Returns the name of the entity whose type is being rebuilt.
9315 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009316
Douglas Gregoref6ab412009-10-27 06:26:26 +00009317 /// \brief Sets the "base" location and entity when that
9318 /// information is known based on another transformation.
9319 void setBase(SourceLocation Loc, DeclarationName Entity) {
9320 this->Loc = Loc;
9321 this->Entity = Entity;
9322 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009323
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00009324 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9325 // Lambdas never need to be transformed.
9326 return E;
9327 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00009328 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009329} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00009330
Douglas Gregor15acfb92009-08-06 16:20:37 +00009331/// \brief Rebuilds a type within the context of the current instantiation.
9332///
Mike Stump11289f42009-09-09 15:08:12 +00009333/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00009334/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00009335/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00009336/// partial specialization thereof). This routine will rebuild that type now
9337/// that we have entered the declarator's scope, which may produce different
9338/// canonical types, e.g.,
9339///
9340/// \code
9341/// template<typename T>
9342/// struct X {
9343/// typedef T* pointer;
9344/// pointer data();
9345/// };
9346///
9347/// template<typename T>
9348/// typename X<T>::pointer X<T>::data() { ... }
9349/// \endcode
9350///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00009351/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009352/// since we do not know that we can look into X<T> when we parsed the type.
9353/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00009354/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00009355/// as the canonical type of T*, allowing the return types of the out-of-line
9356/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00009357TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9358 SourceLocation Loc,
9359 DeclarationName Name) {
9360 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00009361 return T;
Mike Stump11289f42009-09-09 15:08:12 +00009362
Douglas Gregor15acfb92009-08-06 16:20:37 +00009363 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9364 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00009365}
Douglas Gregorbe999392009-09-15 16:23:51 +00009366
John McCalldadc5752010-08-24 06:29:42 +00009367ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00009368 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9369 DeclarationName());
9370 return Rebuilder.TransformExpr(E);
9371}
9372
John McCall99b2fe52010-04-29 23:50:39 +00009373bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00009374 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009375 return true;
John McCall2408e322010-04-27 00:57:59 +00009376
Douglas Gregor10176412011-02-25 16:07:42 +00009377 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009378 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9379 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009380 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009381 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009382 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009383 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009384
Douglas Gregor10176412011-02-25 16:07:42 +00009385 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009386 return false;
John McCall2408e322010-04-27 00:57:59 +00009387}
9388
Douglas Gregor041b0842011-10-14 15:31:12 +00009389/// \brief Rebuild the template parameters now that we know we're in a current
9390/// instantiation.
9391bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9392 TemplateParameterList *Params) {
9393 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9394 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009395
Douglas Gregor041b0842011-10-14 15:31:12 +00009396 // There is nothing to rebuild in a type parameter.
9397 if (isa<TemplateTypeParmDecl>(Param))
9398 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009399
Douglas Gregor041b0842011-10-14 15:31:12 +00009400 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009401 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009402 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9403 if (RebuildTemplateParamsInCurrentInstantiation(
9404 TTP->getTemplateParameters()))
9405 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009406
Douglas Gregor041b0842011-10-14 15:31:12 +00009407 continue;
9408 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009409
Douglas Gregor041b0842011-10-14 15:31:12 +00009410 // Rebuild the type of a non-type template parameter.
9411 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009412 TypeSourceInfo *NewTSI
9413 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9414 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009415 NTTP->getDeclName());
9416 if (!NewTSI)
9417 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009418
Douglas Gregor041b0842011-10-14 15:31:12 +00009419 if (NewTSI != NTTP->getTypeSourceInfo()) {
9420 NTTP->setTypeSourceInfo(NewTSI);
9421 NTTP->setType(NewTSI->getType());
9422 }
9423 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009424
Douglas Gregor041b0842011-10-14 15:31:12 +00009425 return false;
9426}
9427
Douglas Gregorbe999392009-09-15 16:23:51 +00009428/// \brief Produces a formatted string that describes the binding of
9429/// template parameters to template arguments.
9430std::string
9431Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9432 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009433 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00009434}
9435
9436std::string
9437Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9438 const TemplateArgument *Args,
9439 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009440 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00009441 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00009442
Douglas Gregore62e6a02009-11-11 19:13:48 +00009443 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009444 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009445
Douglas Gregorbe999392009-09-15 16:23:51 +00009446 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00009447 if (I >= NumArgs)
9448 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009449
Douglas Gregorbe999392009-09-15 16:23:51 +00009450 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009451 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00009452 else
Douglas Gregor0192c232010-12-20 16:52:59 +00009453 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009454
Douglas Gregorbe999392009-09-15 16:23:51 +00009455 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00009456 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00009457 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00009458 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00009459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009460
Douglas Gregor0192c232010-12-20 16:52:59 +00009461 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00009462 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00009463 }
Douglas Gregor0192c232010-12-20 16:52:59 +00009464
9465 Out << ']';
9466 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00009467}
Francois Pichet1c229c02011-04-22 22:18:13 +00009468
Richard Smithe40f2ba2013-08-07 21:41:30 +00009469void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9470 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00009471 if (!FD)
9472 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00009473
Justin Lebar28f09c52016-10-10 16:26:08 +00009474 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00009475
9476 // Take tokens to avoid allocations
9477 LPT->Toks.swap(Toks);
9478 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00009479 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00009480
9481 FD->setLateTemplateParsed(true);
9482}
9483
9484void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9485 if (!FD)
9486 return;
9487 FD->setLateTemplateParsed(false);
9488}
Francois Pichet1c229c02011-04-22 22:18:13 +00009489
9490bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9491 DeclContext *DC = CurContext;
9492
9493 while (DC) {
9494 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9495 const FunctionDecl *FD = RD->isLocalClass();
9496 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9497 } else if (DC->isTranslationUnit() || DC->isNamespace())
9498 return false;
9499
9500 DC = DC->getParent();
9501 }
9502 return false;
9503}
Richard Smith6739a102016-05-05 00:56:12 +00009504
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009505namespace {
Richard Smith6739a102016-05-05 00:56:12 +00009506/// \brief Walk the path from which a declaration was instantiated, and check
9507/// that every explicit specialization along that path is visible. This enforces
9508/// C++ [temp.expl.spec]/6:
9509///
9510/// If a template, a member template or a member of a class template is
9511/// explicitly specialized then that specialization shall be declared before
9512/// the first use of that specialization that would cause an implicit
9513/// instantiation to take place, in every translation unit in which such a
9514/// use occurs; no diagnostic is required.
9515///
9516/// and also C++ [temp.class.spec]/1:
9517///
9518/// A partial specialization shall be declared before the first use of a
9519/// class template specialization that would make use of the partial
9520/// specialization as the result of an implicit or explicit instantiation
9521/// in every translation unit in which such a use occurs; no diagnostic is
9522/// required.
9523class ExplicitSpecializationVisibilityChecker {
9524 Sema &S;
9525 SourceLocation Loc;
9526 llvm::SmallVector<Module *, 8> Modules;
9527
9528public:
9529 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9530 : S(S), Loc(Loc) {}
9531
9532 void check(NamedDecl *ND) {
9533 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9534 return checkImpl(FD);
9535 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9536 return checkImpl(RD);
9537 if (auto *VD = dyn_cast<VarDecl>(ND))
9538 return checkImpl(VD);
9539 if (auto *ED = dyn_cast<EnumDecl>(ND))
9540 return checkImpl(ED);
9541 }
9542
9543private:
9544 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9545 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9546 : Sema::MissingImportKind::ExplicitSpecialization;
9547 const bool Recover = true;
9548
9549 // If we got a custom set of modules (because only a subset of the
9550 // declarations are interesting), use them, otherwise let
9551 // diagnoseMissingImport intelligently pick some.
9552 if (Modules.empty())
9553 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9554 else
9555 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9556 }
9557
9558 // Check a specific declaration. There are three problematic cases:
9559 //
9560 // 1) The declaration is an explicit specialization of a template
9561 // specialization.
9562 // 2) The declaration is an explicit specialization of a member of an
9563 // templated class.
9564 // 3) The declaration is an instantiation of a template, and that template
9565 // is an explicit specialization of a member of a templated class.
9566 //
9567 // We don't need to go any deeper than that, as the instantiation of the
9568 // surrounding class / etc is not triggered by whatever triggered this
9569 // instantiation, and thus should be checked elsewhere.
9570 template<typename SpecDecl>
9571 void checkImpl(SpecDecl *Spec) {
9572 bool IsHiddenExplicitSpecialization = false;
9573 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9574 IsHiddenExplicitSpecialization =
9575 Spec->getMemberSpecializationInfo()
9576 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9577 : !S.hasVisibleDeclaration(Spec);
9578 } else {
9579 checkInstantiated(Spec);
9580 }
9581
9582 if (IsHiddenExplicitSpecialization)
9583 diagnose(Spec->getMostRecentDecl(), false);
9584 }
9585
9586 void checkInstantiated(FunctionDecl *FD) {
9587 if (auto *TD = FD->getPrimaryTemplate())
9588 checkTemplate(TD);
9589 }
9590
9591 void checkInstantiated(CXXRecordDecl *RD) {
9592 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9593 if (!SD)
9594 return;
9595
9596 auto From = SD->getSpecializedTemplateOrPartial();
9597 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9598 checkTemplate(TD);
9599 else if (auto *TD =
9600 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9601 if (!S.hasVisibleDeclaration(TD))
9602 diagnose(TD, true);
9603 checkTemplate(TD);
9604 }
9605 }
9606
9607 void checkInstantiated(VarDecl *RD) {
9608 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9609 if (!SD)
9610 return;
9611
9612 auto From = SD->getSpecializedTemplateOrPartial();
9613 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9614 checkTemplate(TD);
9615 else if (auto *TD =
9616 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9617 if (!S.hasVisibleDeclaration(TD))
9618 diagnose(TD, true);
9619 checkTemplate(TD);
9620 }
9621 }
9622
9623 void checkInstantiated(EnumDecl *FD) {}
9624
9625 template<typename TemplDecl>
9626 void checkTemplate(TemplDecl *TD) {
9627 if (TD->isMemberSpecialization()) {
9628 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9629 diagnose(TD->getMostRecentDecl(), false);
9630 }
9631 }
9632};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009633} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00009634
9635void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
9636 if (!getLangOpts().Modules)
9637 return;
9638
9639 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9640}
9641
9642/// \brief Check whether a template partial specialization that we've discovered
9643/// is hidden, and produce suitable diagnostics if so.
9644void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
9645 NamedDecl *Spec) {
9646 llvm::SmallVector<Module *, 8> Modules;
9647 if (!hasVisibleDeclaration(Spec, &Modules))
9648 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9649 MissingImportKind::PartialSpecialization,
9650 /*Recover*/true);
9651}