blob: 58614322f761b7f517eab9d055b9565bcf2a82e4 [file] [log] [blame]
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +000011
Douglas Gregor15acfb92009-08-06 16:20:37 +000012#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000013#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000015#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000019#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000020#include "clang/AST/TypeVisitor.h"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000021#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedTemplate.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000032#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000034#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000035
Eric Fiselier6ad68552016-07-01 01:24:09 +000036#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000037using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000039
John McCall9b72f892010-11-10 02:40:36 +000040// Exported for use by Parser.
41SourceRange
42clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 unsigned N) {
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46}
47
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000048namespace clang {
49/// \brief [temp.constr.decl]p2: A template's associated constraints are
50/// defined as a single constraint-expression derived from the introduced
51/// constraint-expressions [ ... ].
52///
53/// \param Params The template parameter list and optional requires-clause.
54///
55/// \param FD The underlying templated function declaration for a function
56/// template.
57static Expr *formAssociatedConstraints(TemplateParameterList *Params,
58 FunctionDecl *FD);
59}
60
61static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
62 FunctionDecl *FD) {
63 // FIXME: Concepts: collect additional introduced constraint-expressions
64 assert(!FD && "Cannot collect constraints from function declaration yet.");
65 return Params->getRequiresClause();
66}
67
Douglas Gregorb7bfe792009-09-02 22:59:36 +000068/// \brief Determine whether the declaration found is acceptable as the name
69/// of a template and, if so, return that template declaration. Otherwise,
70/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000071static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000072 NamedDecl *Orig,
73 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000074 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000076 if (isa<TemplateDecl>(D)) {
77 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000078 return nullptr;
79
John McCalle9cccd82010-06-16 08:42:20 +000080 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000081 }
Mike Stump11289f42009-09-09 15:08:12 +000082
Douglas Gregorb7bfe792009-09-02 22:59:36 +000083 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
84 // C++ [temp.local]p1:
85 // Like normal (non-template) classes, class templates have an
86 // injected-class-name (Clause 9). The injected-class-name
87 // can be used with or without a template-argument-list. When
88 // it is used without a template-argument-list, it is
89 // equivalent to the injected-class-name followed by the
90 // template-parameters of the class template enclosed in
91 // <>. When it is used with a template-argument-list, it
92 // refers to the specified class template specialization,
93 // which could be the current specialization or another
94 // specialization.
95 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000096 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000097 if (Record->getDescribedClassTemplate())
98 return Record->getDescribedClassTemplate();
99
100 if (ClassTemplateSpecializationDecl *Spec
101 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
102 return Spec->getSpecializedTemplate();
103 }
Mike Stump11289f42009-09-09 15:08:12 +0000104
Craig Topperc3ec1492014-05-26 06:22:03 +0000105 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106 }
Mike Stump11289f42009-09-09 15:08:12 +0000107
Craig Topperc3ec1492014-05-26 06:22:03 +0000108 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000109}
110
Simon Pilgrim6905d222016-12-30 22:55:33 +0000111void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000112 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000113 // The set of class templates we've already seen.
114 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +0000115 LookupResult::Filter filter = R.makeFilter();
116 while (filter.hasNext()) {
117 NamedDecl *Orig = filter.next();
Simon Pilgrim6905d222016-12-30 22:55:33 +0000118 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000119 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +0000120 if (!Repl)
121 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000122 else if (Repl != Orig) {
123
124 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000125 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000126 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000127 // one base class). If all of the injected-class-names that are found
128 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000129 // is used as a template-name, the reference refers to the class
130 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000131 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000132 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000133 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000134 filter.erase();
135 continue;
136 }
John McCallbd8062d2010-08-13 07:02:08 +0000137
138 // FIXME: we promote access to public here as a workaround to
139 // the fact that LookupResult doesn't let us remember that we
140 // found this template through a particular injected class name,
141 // which means we end up doing nasty things to the invariants.
142 // Pretending that access is public is *much* safer.
143 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000144 }
John McCalle66edc12009-11-24 19:00:30 +0000145 }
146 filter.done();
147}
148
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000149bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
150 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000151 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000152 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000153 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +0000154
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000155 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000156}
157
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000159 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000160 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000161 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000162 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000163 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000164 TemplateTy &TemplateResult,
165 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000166 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000167
Douglas Gregor3cf81312009-11-03 23:16:33 +0000168 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000169 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000170
Douglas Gregor3cf81312009-11-03 23:16:33 +0000171 switch (Name.getKind()) {
172 case UnqualifiedId::IK_Identifier:
173 TName = DeclarationName(Name.Identifier);
174 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000175
Douglas Gregor3cf81312009-11-03 23:16:33 +0000176 case UnqualifiedId::IK_OperatorFunctionId:
177 TName = Context.DeclarationNames.getCXXOperatorName(
178 Name.OperatorFunctionId.Operator);
179 break;
180
Alexis Hunted0530f2009-11-28 08:58:14 +0000181 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000182 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
183 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000184
Douglas Gregor3cf81312009-11-03 23:16:33 +0000185 default:
186 return TNK_Non_template;
187 }
Mike Stump11289f42009-09-09 15:08:12 +0000188
John McCallba7bf592010-08-24 05:47:05 +0000189 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000190
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000191 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000192 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
193 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000194 if (R.empty()) return TNK_Non_template;
195 if (R.isAmbiguous()) {
196 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000197 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000198
199 // FIXME: we might have ambiguous templates, in which case we
200 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000201 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000202 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000203
John McCalld28ae272009-12-02 08:04:21 +0000204 TemplateName Template;
205 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000206
John McCalld28ae272009-12-02 08:04:21 +0000207 unsigned ResultCount = R.end() - R.begin();
208 if (ResultCount > 1) {
209 // We assume that we'll preserve the qualifier from a function
210 // template name in other ways.
211 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
212 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000213
214 // We'll do this lookup again later.
215 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000216 } else {
John McCalld28ae272009-12-02 08:04:21 +0000217 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
218
219 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000220 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000221 Template = Context.getQualifiedTemplateName(Qualifier,
222 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000223 } else {
224 Template = TemplateName(TD);
225 }
226
John McCalldcc71402010-08-13 02:23:42 +0000227 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000228 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000229
230 // We'll do this lookup again later.
231 R.suppressDiagnostics();
232 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000233 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000234 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
235 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000236 TemplateKind =
237 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000238 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000239 }
Mike Stump11289f42009-09-09 15:08:12 +0000240
John McCalld28ae272009-12-02 08:04:21 +0000241 TemplateResult = TemplateTy::make(Template);
242 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000243}
244
Richard Smith278890f2017-02-10 20:39:58 +0000245bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
246 SourceLocation NameLoc,
247 ParsedTemplateTy *Template) {
248 CXXScopeSpec SS;
249 bool MemberOfUnknownSpecialization = false;
250
251 // We could use redeclaration lookup here, but we don't need to: the
252 // syntactic form of a deduction guide is enough to identify it even
253 // if we can't look up the template name at all.
254 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
255 LookupTemplateName(R, S, SS, /*ObjectType*/QualType(),
256 /*EnteringContext*/false, MemberOfUnknownSpecialization);
257
258 if (R.empty()) return false;
259 if (R.isAmbiguous()) {
260 // FIXME: Diagnose an ambiguity if we find at least one template.
261 R.suppressDiagnostics();
262 return false;
263 }
264
265 // We only treat template-names that name type templates as valid deduction
266 // guide names.
267 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
268 if (!TD || !getAsTypeTemplateDecl(TD))
269 return false;
270
271 if (Template)
272 *Template = TemplateTy::make(TemplateName(TD));
273 return true;
274}
275
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000277 SourceLocation IILoc,
278 Scope *S,
279 const CXXScopeSpec *SS,
280 TemplateTy &SuggestedTemplate,
281 TemplateNameKind &SuggestedKind) {
282 // We can't recover unless there's a dependent scope specifier preceding the
283 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000284 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000285 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
286 computeDeclContext(*SS))
287 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000288
Douglas Gregor18473f32010-01-12 21:28:44 +0000289 // The code is missing a 'template' keyword prior to the dependent template
290 // name.
291 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
292 Diag(IILoc, diag::err_template_kw_missing)
293 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000294 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000295 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000296 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
297 SuggestedKind = TNK_Dependent_template_name;
298 return true;
299}
300
John McCalle66edc12009-11-24 19:00:30 +0000301void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000302 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000303 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000304 bool EnteringContext,
305 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000306 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000307 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000308 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000309 bool isDependent = false;
310 if (!ObjectType.isNull()) {
311 // This nested-name-specifier occurs in a member access expression, e.g.,
312 // x->B::f, and we are looking into the type of the object.
313 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
314 LookupCtx = computeDeclContext(ObjectType);
315 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000316 assert((isDependent || !ObjectType->isIncompleteType() ||
317 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000318 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000319
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000320 // Template names cannot appear inside an Objective-C class or object type.
321 if (ObjectType->isObjCObjectOrInterfaceType()) {
322 Found.clear();
323 return;
324 }
John McCalle66edc12009-11-24 19:00:30 +0000325 } else if (SS.isSet()) {
326 // This nested-name-specifier occurs after another nested-name-specifier,
327 // so long into the context associated with the prior nested-name-specifier.
328 LookupCtx = computeDeclContext(SS, EnteringContext);
329 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000330
John McCalle66edc12009-11-24 19:00:30 +0000331 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000332 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000333 return;
334 }
335
336 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000337 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000338 if (LookupCtx) {
339 // Perform "qualified" name lookup into the declaration context we
340 // computed, which is either the type of the base of a member access
341 // expression or the declaration context associated with a prior
342 // nested-name-specifier.
343 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000344 if (!ObjectType.isNull() && Found.empty()) {
345 // C++ [basic.lookup.classref]p1:
346 // In a class member access expression (5.2.5), if the . or -> token is
347 // immediately followed by an identifier followed by a <, the
348 // identifier must be looked up to determine whether the < is the
349 // beginning of a template argument list (14.2) or a less-than operator.
350 // The identifier is first looked up in the class of the object
351 // expression. If the identifier is not found, it is then looked up in
352 // the context of the entire postfix-expression and shall name a class
353 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000354 if (S) LookupName(Found, S);
355 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000356 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000357 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000358 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000359 // We cannot look into a dependent object type or nested nme
360 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000361 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000362 return;
363 } else {
364 // Perform unqualified name lookup in the current scope.
365 LookupName(Found, S);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000366
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000367 if (!ObjectType.isNull())
368 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000369 }
370
Douglas Gregorc119dd52010-01-12 17:06:20 +0000371 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000372 // If we did not find any names, attempt to correct any typos.
373 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000374 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000375 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000376 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
377 FilterCCC->WantTypeSpecifiers = false;
378 FilterCCC->WantExpressionKeywords = false;
379 FilterCCC->WantRemainingKeywords = false;
380 FilterCCC->WantCXXNamedCasts = true;
381 if (TypoCorrection Corrected = CorrectTypo(
382 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
383 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000384 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000385 if (auto *ND = Corrected.getFoundDecl())
386 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000387 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000388 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000389 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000390 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
391 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000392 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000393 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
394 << Name << LookupCtx << DroppedSpecifier
395 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000396 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000397 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000398 }
John McCalle9cccd82010-06-16 08:42:20 +0000399 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000400 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000401 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000402 }
403 }
404
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000405 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000406 if (Found.empty()) {
407 if (isDependent)
408 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000409 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000410 }
John McCalle66edc12009-11-24 19:00:30 +0000411
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000412 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000413 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000414 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000415 // [...] If the lookup in the class of the object expression finds a
416 // template, the name is also looked up in the context of the entire
417 // postfix-expression and [...]
418 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000419 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000420 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
421 LookupOrdinaryName);
422 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000423 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000424
John McCalle66edc12009-11-24 19:00:30 +0000425 if (FoundOuter.empty()) {
426 // - if the name is not found, the name found in the class of the
427 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000428 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
429 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000430 // - if the name is found in the context of the entire
431 // postfix-expression and does not name a class template, the name
432 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000433 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000434 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000435 // - if the name found is a class template, it must refer to the same
436 // entity as the one found in the class of the object expression,
437 // otherwise the program is ill-formed.
438 if (!Found.isSingleResult() ||
439 Found.getFoundDecl()->getCanonicalDecl()
440 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000442 diag::ext_nested_name_member_ref_lookup_ambiguous)
443 << Found.getLookupName()
444 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000445 Diag(Found.getRepresentativeDecl()->getLocation(),
446 diag::note_ambig_member_ref_object_type)
447 << ObjectType;
448 Diag(FoundOuter.getFoundDecl()->getLocation(),
449 diag::note_ambig_member_ref_scope);
450
451 // Recover by taking the template that we found in the object
452 // expression's type.
453 }
454 }
455 }
456}
457
Richard Smith42bc73a2017-05-10 02:30:28 +0000458void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
459 SourceLocation Less,
460 SourceLocation Greater) {
461 if (TemplateName.isInvalid())
462 return;
463
464 DeclarationNameInfo NameInfo;
465 CXXScopeSpec SS;
466 LookupNameKind LookupKind;
467
468 DeclContext *LookupCtx = nullptr;
469 NamedDecl *Found = nullptr;
470
471 // Figure out what name we looked up.
472 if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
473 NameInfo = ME->getMemberNameInfo();
474 SS.Adopt(ME->getQualifierLoc());
475 LookupKind = LookupMemberName;
476 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
477 Found = ME->getMemberDecl();
478 } else {
479 auto *DRE = cast<DeclRefExpr>(TemplateName.get());
480 NameInfo = DRE->getNameInfo();
481 SS.Adopt(DRE->getQualifierLoc());
482 LookupKind = LookupOrdinaryName;
483 Found = DRE->getFoundDecl();
484 }
485
486 // Try to correct the name by looking for templates and C++ named casts.
487 struct TemplateCandidateFilter : CorrectionCandidateCallback {
488 TemplateCandidateFilter() {
489 WantTypeSpecifiers = false;
490 WantExpressionKeywords = false;
491 WantRemainingKeywords = false;
492 WantCXXNamedCasts = true;
493 };
494 bool ValidateCandidate(const TypoCorrection &Candidate) override {
495 if (auto *ND = Candidate.getCorrectionDecl())
496 return isAcceptableTemplateName(ND->getASTContext(), ND, true);
497 return Candidate.isKeyword();
498 }
499 };
500
501 DeclarationName Name = NameInfo.getName();
502 if (TypoCorrection Corrected =
503 CorrectTypo(NameInfo, LookupKind, S, &SS,
504 llvm::make_unique<TemplateCandidateFilter>(),
505 CTK_ErrorRecovery, LookupCtx)) {
506 auto *ND = Corrected.getFoundDecl();
507 if (ND)
508 ND = isAcceptableTemplateName(Context, ND,
509 /*AllowFunctionTemplates*/ true);
510 if (ND || Corrected.isKeyword()) {
511 if (LookupCtx) {
512 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
513 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
514 Name.getAsString() == CorrectedStr;
515 diagnoseTypo(Corrected,
516 PDiag(diag::err_non_template_in_member_template_id_suggest)
517 << Name << LookupCtx << DroppedSpecifier
Richard Smith52f8d192017-05-10 21:32:16 +0000518 << SS.getRange(), false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000519 } else {
520 diagnoseTypo(Corrected,
521 PDiag(diag::err_non_template_in_template_id_suggest)
Richard Smith52f8d192017-05-10 21:32:16 +0000522 << Name, false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000523 }
524 if (Found)
525 Diag(Found->getLocation(),
526 diag::note_non_template_in_template_id_found);
527 return;
528 }
529 }
530
531 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
532 << Name << SourceRange(Less, Greater);
533 if (Found)
534 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
535}
536
John McCallcd4b4772009-12-02 03:53:29 +0000537/// ActOnDependentIdExpression - Handle a dependent id-expression that
538/// was just parsed. This is only possible with an explicit scope
539/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000540ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000541Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000542 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000543 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000544 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000545 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000546 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547
Reid Kleckner1af391df2016-03-11 18:59:12 +0000548 // C++11 [expr.prim.general]p12:
549 // An id-expression that denotes a non-static data member or non-static
550 // member function of a class can only be used:
551 // (...)
552 // - if that id-expression denotes a non-static data member and it
553 // appears in an unevaluated operand.
554 //
555 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
556 // CXXDependentScopeMemberExpr. The former can instantiate to either
557 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
558 // always a MemberExpr.
559 bool MightBeCxx11UnevalField =
560 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
561
Akira Hatanakad644e022016-12-16 03:19:41 +0000562 // Check if the nested name specifier is an enum type.
563 bool IsEnum = false;
564 if (NestedNameSpecifier *NNS = SS.getScopeRep())
565 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
566
567 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000568 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000569 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570
John McCalle66edc12009-11-24 19:00:30 +0000571 // Since the 'this' expression is synthesized, we don't need to
572 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000573 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000574
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000575 return CXXDependentScopeMemberExpr::Create(
576 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
577 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
578 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000579 }
580
Abramo Bagnara7945c982012-01-27 09:46:47 +0000581 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000582}
583
John McCalldadc5752010-08-24 06:29:42 +0000584ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000585Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000586 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000587 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000588 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000589 return DependentScopeDeclRefExpr::Create(
590 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
591 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000592}
593
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000594
595/// Determine whether we would be unable to instantiate this template (because
596/// it either has no definition, or is in the process of being instantiated).
597bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
598 NamedDecl *Instantiation,
599 bool InstantiatedFromMember,
600 const NamedDecl *Pattern,
601 const NamedDecl *PatternDef,
602 TemplateSpecializationKind TSK,
603 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000604 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
605 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000606
Richard Smithedbc6e92016-10-14 21:41:24 +0000607 bool IsEntityBeingDefined = false;
608 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
609 IsEntityBeingDefined = TD->isBeingDefined();
610
611 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000612 NamedDecl *SuggestedDef = nullptr;
613 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
614 /*OnlyNeedComplete*/false)) {
615 // If we're allowed to diagnose this and recover, do so.
616 bool Recover = Complain && !isSFINAEContext();
617 if (Complain)
618 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
619 Sema::MissingImportKind::Definition, Recover);
620 return !Recover;
621 }
622 return false;
623 }
624
Richard Smith6f4e2e02016-08-23 19:41:39 +0000625 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
626 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000627
Richard Smithedbc6e92016-10-14 21:41:24 +0000628 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000629 QualType InstantiationTy;
630 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
631 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000632 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000633 Diag(PointOfInstantiation,
634 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000635 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000636 << InstantiationTy;
637 // Not much point in noting the template declaration here, since
638 // we're lexically inside it.
639 Instantiation->setInvalidDecl();
640 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000641 if (isa<FunctionDecl>(Instantiation)) {
642 Diag(PointOfInstantiation,
643 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000644 << /*member function*/ 1 << Instantiation->getDeclName()
645 << Instantiation->getDeclContext();
646 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000647 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000648 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000649 Diag(PointOfInstantiation,
650 diag::err_implicit_instantiate_member_undefined)
651 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000652 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000653 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000654 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000655 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000656 Diag(PointOfInstantiation,
657 diag::err_explicit_instantiation_undefined_func_template)
658 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000659 Note = diag::note_explicit_instantiation_here;
660 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000661 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
662 << (TSK != TSK_ImplicitInstantiation)
663 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000664 Note = diag::note_template_decl_here;
665 } else {
666 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
667 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
668 Diag(PointOfInstantiation,
669 diag::err_explicit_instantiation_undefined_var_template)
670 << Instantiation;
671 Instantiation->setInvalidDecl();
672 } else
673 Diag(PointOfInstantiation,
674 diag::err_explicit_instantiation_undefined_member)
675 << /*static data member*/ 2 << Instantiation->getDeclName()
676 << Instantiation->getDeclContext();
677 Note = diag::note_explicit_instantiation_here;
678 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000679 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000680 if (Note) // Diagnostics were emitted.
681 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000682
683 // In general, Instantiation isn't marked invalid to get more than one
684 // error for multiple undefined instantiations. But the code that does
685 // explicit declaration -> explicit definition conversion can't handle
686 // invalid declarations, so mark as invalid in that case.
687 if (TSK == TSK_ExplicitInstantiationDeclaration)
688 Instantiation->setInvalidDecl();
689 return true;
690}
691
Douglas Gregor5101c242008-12-05 18:15:24 +0000692/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
693/// that the template parameter 'PrevDecl' is being shadowed by a new
694/// declaration at location Loc. Returns true to indicate that this is
695/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000696void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000697 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000698
699 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000700 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000701 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000702
703 // C++ [temp.local]p4:
704 // A template-parameter shall not be redeclared within its
705 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000706 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000707 << cast<NamedDecl>(PrevDecl)->getDeclName();
708 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000709}
710
Douglas Gregor463421d2009-03-03 04:44:36 +0000711/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000712/// the parameter D to reference the templated declaration and return a pointer
713/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000714TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
715 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
716 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000717 return Temp;
718 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000719 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000720}
721
Douglas Gregoreb29d182011-01-05 17:40:24 +0000722ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
723 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000725 "Only template template arguments can be pack expansions here");
726 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
727 "Template template argument pack expansion without packs");
728 ParsedTemplateArgument Result(*this);
729 Result.EllipsisLoc = EllipsisLoc;
730 return Result;
731}
732
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000733static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
734 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000736 switch (Arg.getKind()) {
737 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000738 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000739 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000740 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000741 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000742 return TemplateArgumentLoc(TemplateArgument(T), DI);
743 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000744
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000745 case ParsedTemplateArgument::NonType: {
746 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
747 return TemplateArgumentLoc(TemplateArgument(E), E);
748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000749
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000750 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000751 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000752 TemplateArgument TArg;
753 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000754 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000755 else
756 TArg = Template;
757 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000758 Arg.getScopeSpec().getWithLocInContext(
759 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000760 Arg.getLocation(),
761 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000762 }
763 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000765 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000766}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000767
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000768/// \brief Translates template arguments as provided by the parser
769/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000770void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
771 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000772 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000773 TemplateArgs.addArgument(translateTemplateArgument(*this,
774 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000775}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000776
Richard Smithb80d5402013-06-25 22:21:36 +0000777static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
778 SourceLocation Loc,
779 IdentifierInfo *Name) {
780 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
781 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
782 if (PrevDecl && PrevDecl->isTemplateParameter())
783 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
784}
785
Douglas Gregor5101c242008-12-05 18:15:24 +0000786/// ActOnTypeParameter - Called when a C++ template type parameter
787/// (e.g., "typename T") has been parsed. Typename specifies whether
788/// the keyword "typename" was used to declare the type parameter
789/// (otherwise, "class" was used), and KeyLoc is the location of the
790/// "class" or "typename" keyword. ParamName is the name of the
791/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000792/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000793/// If the type parameter has a default argument, it will be added
794/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000795Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000796 SourceLocation EllipsisLoc,
797 SourceLocation KeyLoc,
798 IdentifierInfo *ParamName,
799 SourceLocation ParamNameLoc,
800 unsigned Depth, unsigned Position,
801 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000802 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000803 assert(S->isTemplateParamScope() &&
804 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000805
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000806 SourceLocation Loc = ParamNameLoc;
807 if (!ParamName)
808 Loc = KeyLoc;
809
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000810 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000811 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000812 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000813 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000814 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000815 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000816
817 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000818 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
819
Douglas Gregor5101c242008-12-05 18:15:24 +0000820 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000821 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000822 IdResolver.AddDecl(Param);
823 }
824
Douglas Gregorf5500772011-01-05 15:48:55 +0000825 // C++0x [temp.param]p9:
826 // A default template-argument may be specified for any kind of
827 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000828 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000829 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000830 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000831 }
832
Douglas Gregordc13ded2010-07-01 00:00:45 +0000833 // Handle the default argument, if provided.
834 if (DefaultArg) {
835 TypeSourceInfo *DefaultTInfo;
836 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000837
Douglas Gregordc13ded2010-07-01 00:00:45 +0000838 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000840 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000841 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000842 UPPC_DefaultArgument))
843 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844
Douglas Gregordc13ded2010-07-01 00:00:45 +0000845 // Check the template argument itself.
846 if (CheckTemplateArgument(Param, DefaultTInfo)) {
847 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000848 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000849 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850
Richard Smith1469b912015-06-10 00:29:03 +0000851 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000853
John McCall48871652010-08-21 09:40:31 +0000854 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000855}
856
Douglas Gregor463421d2009-03-03 04:44:36 +0000857/// \brief Check that the type of a non-type template parameter is
858/// well-formed.
859///
860/// \returns the (possibly-promoted) parameter type if valid;
861/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000862QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
863 SourceLocation Loc) {
864 if (TSI->getType()->isUndeducedType()) {
865 // C++1z [temp.dep.expr]p3:
866 // An id-expression is type-dependent if it contains
867 // - an identifier associated by name lookup with a non-type
868 // template-parameter declared with a type that contains a
869 // placeholder type (7.1.7.4),
870 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
871 }
872
873 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
874}
875
876QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
877 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000878 // We don't allow variably-modified types as the type of non-type template
879 // parameters.
880 if (T->isVariablyModifiedType()) {
881 Diag(Loc, diag::err_variably_modified_nontype_template_param)
882 << T;
883 return QualType();
884 }
885
Douglas Gregor463421d2009-03-03 04:44:36 +0000886 // C++ [temp.param]p4:
887 //
888 // A non-type template-parameter shall have one of the following
889 // (optionally cv-qualified) types:
890 //
891 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000892 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000893 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000894 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000895 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000896 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000897 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000898 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000899 // -- std::nullptr_t.
900 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000901 // If T is a dependent type, we can't do the check now, so we
902 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +0000903 T->isDependentType() ||
904 // Allow use of auto in template parameter declarations.
905 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +0000906 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
907 // are ignored when determining its type.
908 return T.getUnqualifiedType();
909 }
910
Douglas Gregor463421d2009-03-03 04:44:36 +0000911 // C++ [temp.param]p8:
912 //
913 // A non-type template-parameter of type "array of T" or
914 // "function returning T" is adjusted to be of type "pointer to
915 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000916 else if (T->isArrayType() || T->isFunctionType())
917 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000918
Douglas Gregor463421d2009-03-03 04:44:36 +0000919 Diag(Loc, diag::err_template_nontype_parm_bad_type)
920 << T;
921
922 return QualType();
923}
924
John McCall48871652010-08-21 09:40:31 +0000925Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
926 unsigned Depth,
927 unsigned Position,
928 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000929 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000930 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +0000931
932 if (TInfo->getType()->isUndeducedType()) {
933 Diag(D.getIdentifierLoc(),
934 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
935 << QualType(TInfo->getType()->getContainedAutoType(), 0);
936 }
Douglas Gregor5101c242008-12-05 18:15:24 +0000937
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000938 assert(S->isTemplateParamScope() &&
939 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000940 bool Invalid = false;
941
Richard Smith15361a22016-12-28 06:27:18 +0000942 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000943 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000944 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000945 Invalid = true;
946 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000947
Richard Smithb80d5402013-06-25 22:21:36 +0000948 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000949 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000950 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000951 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000952 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000953 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000955 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000956 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000957
Douglas Gregor5101c242008-12-05 18:15:24 +0000958 if (Invalid)
959 Param->setInvalidDecl();
960
Richard Smithb80d5402013-06-25 22:21:36 +0000961 if (ParamName) {
962 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
963 ParamName);
964
Douglas Gregor5101c242008-12-05 18:15:24 +0000965 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000966 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000967 IdResolver.AddDecl(Param);
968 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969
Douglas Gregorf5500772011-01-05 15:48:55 +0000970 // C++0x [temp.param]p9:
971 // A default template-argument may be specified for any kind of
972 // template-parameter that is not a template parameter pack.
973 if (Default && IsParameterPack) {
974 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000975 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000976 }
977
Douglas Gregordc13ded2010-07-01 00:00:45 +0000978 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000979 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000980 // Check for unexpanded parameter packs.
981 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
982 return Param;
983
Douglas Gregordc13ded2010-07-01 00:00:45 +0000984 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000985 ExprResult DefaultRes =
986 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000987 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000988 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000989 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000990 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000991 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000992
Richard Smith1469b912015-06-10 00:29:03 +0000993 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000994 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000995
John McCall48871652010-08-21 09:40:31 +0000996 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000997}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000998
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000999/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +00001000/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001001/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +00001002Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1003 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00001004 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +00001005 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +00001006 IdentifierInfo *Name,
1007 SourceLocation NameLoc,
1008 unsigned Depth,
1009 unsigned Position,
1010 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +00001011 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001012 assert(S->isTemplateParamScope() &&
1013 "Template template parameter not in template parameter scope!");
1014
1015 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +00001016 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001017 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +00001018 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001019 NameLoc.isInvalid()? TmpLoc : NameLoc,
1020 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +00001021 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001022 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001023
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001024 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +00001025 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001026 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +00001027 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1028
John McCall48871652010-08-21 09:40:31 +00001029 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001030 IdResolver.AddDecl(Param);
1031 }
1032
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001033 if (Params->size() == 0) {
1034 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1035 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1036 Param->setInvalidDecl();
1037 }
1038
Douglas Gregorf5500772011-01-05 15:48:55 +00001039 // C++0x [temp.param]p9:
1040 // A default template-argument may be specified for any kind of
1041 // template-parameter that is not a template parameter pack.
1042 if (IsParameterPack && !Default.isInvalid()) {
1043 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1044 Default = ParsedTemplateArgument();
1045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001046
Douglas Gregordc13ded2010-07-01 00:00:45 +00001047 if (!Default.isInvalid()) {
1048 // Check only that we have a template template argument. We don't want to
1049 // try to check well-formedness now, because our template template parameter
1050 // might have dependent types in its template parameters, which we wouldn't
1051 // be able to match now.
1052 //
1053 // If none of the template template parameter's template arguments mention
1054 // other template parameters, we could actually perform more checking here.
1055 // However, it isn't worth doing.
1056 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1057 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +00001058 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +00001059 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00001060 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001062
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001063 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001064 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001065 DefaultArg.getArgument().getAsTemplate(),
1066 UPPC_DefaultArgument))
1067 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001068
Richard Smith1469b912015-06-10 00:29:03 +00001069 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +00001070 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001071
John McCall48871652010-08-21 09:40:31 +00001072 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +00001073}
1074
Hubert Tongf608c052016-04-29 18:05:37 +00001075/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1076/// constrained by RequiresClause, that contains the template parameters in
1077/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +00001078TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001079Sema::ActOnTemplateParameterList(unsigned Depth,
1080 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001081 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001082 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +00001083 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001084 SourceLocation RAngleLoc,
1085 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001086 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001087 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001088
David Majnemer902f8c62015-12-27 07:16:27 +00001089 return TemplateParameterList::Create(
1090 Context, TemplateLoc, LAngleLoc,
1091 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001092 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001093}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001094
John McCall3e11ebe2010-03-15 10:12:16 +00001095static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1096 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +00001097 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00001098}
1099
John McCallfaf5fb42010-08-26 23:41:50 +00001100DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00001101Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001102 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001103 IdentifierInfo *Name, SourceLocation NameLoc,
1104 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001105 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00001106 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001107 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001108 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +00001109 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +00001110 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001111 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001112 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001113 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001114 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001115
1116 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001117 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001118 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001119
Abramo Bagnara6150c882010-05-11 21:36:43 +00001120 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1121 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001122
1123 // There is no such thing as an unnamed class template.
1124 if (!Name) {
1125 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001126 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001127 }
1128
Richard Smith6483d222012-04-21 01:27:54 +00001129 // Find any previous declaration with this name. For a friend with no
1130 // scope explicitly specified, we only look for tag declarations (per
1131 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001132 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001133 LookupResult Previous(*this, Name, NameLoc,
1134 (SS.isEmpty() && TUK == TUK_Friend)
1135 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00001136 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001137 if (SS.isNotEmpty() && !SS.isInvalid()) {
1138 SemanticContext = computeDeclContext(SS, true);
1139 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001140 // FIXME: Horrible, horrible hack! We can't currently represent this
1141 // in the AST, and historically we have just ignored such friend
1142 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001143 Diag(NameLoc, TUK == TUK_Friend
1144 ? diag::warn_template_qualified_friend_ignored
1145 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001146 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001147 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001148 }
Mike Stump11289f42009-09-09 15:08:12 +00001149
John McCall0b66eb32010-05-01 00:40:08 +00001150 if (RequireCompleteDeclContext(SS, SemanticContext))
1151 return true;
1152
Simon Pilgrim6905d222016-12-30 22:55:33 +00001153 // If we're adding a template to a dependent context, we may need to
1154 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001155 // now that we know what the current instantiation is.
1156 if (SemanticContext->isDependentContext()) {
1157 ContextRAII SavedContext(*this, SemanticContext);
1158 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1159 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001160 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1161 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +00001162
John McCall27b18f82009-11-17 02:14:36 +00001163 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001164 } else {
1165 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001166
1167 // C++14 [class.mem]p14:
1168 // If T is the name of a class, then each of the following shall have a
1169 // name different from T:
1170 // -- every member template of class T
1171 if (TUK != TUK_Friend &&
1172 DiagnoseClassNameShadow(SemanticContext,
1173 DeclarationNameInfo(Name, NameLoc)))
1174 return true;
1175
John McCall27b18f82009-11-17 02:14:36 +00001176 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001177 }
Mike Stump11289f42009-09-09 15:08:12 +00001178
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001179 if (Previous.isAmbiguous())
1180 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181
Craig Topperc3ec1492014-05-26 06:22:03 +00001182 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001183 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001184 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001185
Serge Pavlove50bf752016-06-10 04:39:07 +00001186 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1187 // Maybe we will complain about the shadowed template parameter.
1188 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1189 // Just pretend that we didn't see the previous declaration.
1190 PrevDecl = nullptr;
1191 }
1192
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001193 // If there is a previous declaration with the same name, check
1194 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +00001195 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001196 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001197
1198 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001199 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001200 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001201 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001202 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1203 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001204 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001205 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1206 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1207 PrevClassTemplate
1208 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1209 ->getSpecializedTemplate();
1210 }
1211 }
1212
John McCalld43784f2009-12-18 11:25:59 +00001213 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001214 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001215 // [...] When looking for a prior declaration of a class or a function
1216 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001217 // function is neither a qualified name nor a template-id, scopes outside
1218 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001219 if (!SS.isSet()) {
1220 DeclContext *OutermostContext = CurContext;
1221 while (!OutermostContext->isFileContext())
1222 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001223
Richard Smith61e582f2012-04-20 07:12:26 +00001224 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001225 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1226 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1227 SemanticContext = PrevDecl->getDeclContext();
1228 } else {
1229 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001230 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001231 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001232 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001233 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001234
1235 // Check that the chosen semantic context doesn't already contain a
1236 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001237 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001238 DeclContext *LookupContext = SemanticContext;
1239 while (LookupContext->isTransparentContext())
1240 LookupContext = LookupContext->getLookupParent();
1241 LookupQualifiedName(Previous, LookupContext);
1242
1243 if (Previous.isAmbiguous())
1244 return true;
1245
1246 if (Previous.begin() != Previous.end())
1247 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001248 }
John McCall90d3bb92009-12-17 23:21:11 +00001249 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001250 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001251 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1252 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001253 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001254
Richard Smithfc805ca2015-07-06 04:43:58 +00001255 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1256 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1257 if (SS.isEmpty() &&
1258 !(PrevClassTemplate &&
1259 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1260 SemanticContext->getRedeclContext()))) {
1261 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1262 Diag(Shadow->getTargetDecl()->getLocation(),
1263 diag::note_using_decl_target);
1264 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1265 // Recover by ignoring the old declaration.
1266 PrevDecl = PrevClassTemplate = nullptr;
1267 }
1268 }
1269
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001270 // TODO Memory management; associated constraints are not always stored.
1271 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1272
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001273 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001274 // Ensure that the template parameter lists are compatible. Skip this check
1275 // for a friend in a dependent context: the template parameter list itself
1276 // could be dependent.
1277 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1278 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001279 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001280 /*Complain=*/true,
1281 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001282 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001283
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001284 // Check for matching associated constraints on redeclarations.
1285 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1286 const bool RedeclACMismatch = [&] {
1287 if (!(CurAC || PrevAC))
1288 return false; // Nothing to check; no mismatch.
1289 if (CurAC && PrevAC) {
1290 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1291 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1292 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1293 if (CurACInfo == PrevACInfo)
1294 return false; // All good; no mismatch.
1295 }
1296 return true;
1297 }();
1298
1299 if (RedeclACMismatch) {
1300 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1301 diag::err_template_different_associated_constraints);
1302 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1303 diag::note_template_prev_declaration) << /*declaration*/0;
1304 return true;
1305 }
1306
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001307 // C++ [temp.class]p4:
1308 // In a redeclaration, partial specialization, explicit
1309 // specialization or explicit instantiation of a class template,
1310 // the class-key shall agree in kind with the original class
1311 // template declaration (7.1.5.3).
1312 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001313 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001314 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001315 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001316 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001317 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001318 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001319 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001320 }
1321
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001322 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001323 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001324 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001325 // If we have a prior definition that is not visible, treat this as
1326 // simply making that previous definition visible.
1327 NamedDecl *Hidden = nullptr;
1328 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001329 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001330 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1331 assert(Tmpl && "original definition of a class template is not a "
1332 "class template?");
Richard Smith858e0e02017-05-11 23:11:16 +00001333 makeMergedDefinitionVisible(Hidden);
1334 makeMergedDefinitionVisible(Tmpl);
Richard Smithbe3980b2015-03-27 00:41:57 +00001335 return Def;
1336 }
1337
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001338 Diag(NameLoc, diag::err_redefinition) << Name;
1339 Diag(Def->getLocation(), diag::note_previous_definition);
1340 // FIXME: Would it make sense to try to "forget" the previous
1341 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001342 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001343 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001344 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001345 } else if (PrevDecl) {
1346 // C++ [temp]p5:
1347 // A class template shall not have the same name as any other
1348 // template, class, function, object, enumeration, enumerator,
1349 // namespace, or type in the same scope (3.3), except as specified
1350 // in (14.5.4).
1351 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1352 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001353 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001354 }
1355
Douglas Gregordba32632009-02-10 19:49:53 +00001356 // Check the template parameter list of this declaration, possibly
1357 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001358 // template declaration. Skip this check for a friend in a dependent
1359 // context, because the template parameter list might be dependent.
1360 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001361 CheckTemplateParameterList(
1362 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001363 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1364 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001365 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1366 SemanticContext->isDependentContext())
1367 ? TPC_ClassTemplateMember
1368 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1369 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001370 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001371
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001372 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001373 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001374 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001375 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1376 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001377 : diag::err_member_decl_does_not_match)
1378 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001379 Invalid = true;
1380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001381 }
1382
Vassil Vassilev352e4412017-01-12 09:16:26 +00001383 // If this is a templated friend in a dependent context we should not put it
1384 // on the redecl chain. In some cases, the templated friend can be the most
1385 // recent declaration tricking the template instantiator to make substitutions
1386 // there.
1387 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1388 bool ShouldAddRedecl
1389 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1390
Mike Stump11289f42009-09-09 15:08:12 +00001391 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001392 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001393 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001394 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001395 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001396 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001397 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001398 NewClass->setTemplateParameterListsInfo(
1399 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1400 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001401
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001402 // Add alignment attributes if necessary; these attributes are checked when
1403 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001404 if (TUK == TUK_Definition) {
1405 AddAlignmentAttributesForRecord(NewClass);
1406 AddMsStructLayoutForRecord(NewClass);
1407 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001408
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001409 // Attach the associated constraints when the declaration will not be part of
1410 // a decl chain.
1411 Expr *const ACtoAttach =
1412 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1413
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001414 ClassTemplateDecl *NewTemplate
1415 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1416 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001417 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001418
1419 if (ShouldAddRedecl)
1420 NewTemplate->setPreviousDecl(PrevClassTemplate);
1421
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001422 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001423
Douglas Gregor21823bf2011-12-20 18:11:52 +00001424 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001425 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001426
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001427 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001428 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001429 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001430 assert(T->isDependentType() && "Class template type is not dependent?");
1431 (void)T;
1432
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001433 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001434 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001435 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001436 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1437 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001438
Anders Carlsson137108d2009-03-26 01:24:28 +00001439 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001440 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001441 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001442
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001443 // Set the lexical context of these templates
1444 NewClass->setLexicalDeclContext(CurContext);
1445 NewTemplate->setLexicalDeclContext(CurContext);
1446
John McCall9bb74a52009-07-31 02:45:11 +00001447 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001448 NewClass->startDefinition();
1449
1450 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001451 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001452
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001453 if (PrevClassTemplate)
1454 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1455
Rafael Espindola385c0422012-07-13 18:04:45 +00001456 AddPushedVisibilityAttribute(NewClass);
1457
Richard Smith234ff472014-08-23 00:49:01 +00001458 if (TUK != TUK_Friend) {
1459 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1460 Scope *Outer = S;
1461 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1462 Outer = Outer->getParent();
1463 PushOnScopeChains(NewTemplate, Outer);
1464 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001465 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001466 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001467 NewClass->setAccess(PrevClassTemplate->getAccess());
1468 }
John McCall27b5c252009-09-14 21:59:20 +00001469
Richard Smith64017682013-07-17 23:53:16 +00001470 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001471
John McCall27b5c252009-09-14 21:59:20 +00001472 // Friend templates are visible in fairly strange ways.
1473 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001474 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001475 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001476 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1477 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001478 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001480
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001481 FriendDecl *Friend = FriendDecl::Create(
1482 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001483 Friend->setAccess(AS_public);
1484 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001485 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001486
Douglas Gregordba32632009-02-10 19:49:53 +00001487 if (Invalid) {
1488 NewTemplate->setInvalidDecl();
1489 NewClass->setInvalidDecl();
1490 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001491
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001492 ActOnDocumentableDecl(NewTemplate);
1493
John McCall48871652010-08-21 09:40:31 +00001494 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001495}
1496
Richard Smith32918772017-02-14 00:25:28 +00001497namespace {
1498/// Transform to convert portions of a constructor declaration into the
1499/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1500struct ConvertConstructorToDeductionGuideTransform {
1501 ConvertConstructorToDeductionGuideTransform(Sema &S,
1502 ClassTemplateDecl *Template)
1503 : SemaRef(S), Template(Template) {}
1504
1505 Sema &SemaRef;
1506 ClassTemplateDecl *Template;
1507
1508 DeclContext *DC = Template->getDeclContext();
1509 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1510 DeclarationName DeductionGuideName =
1511 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1512
1513 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1514
1515 // Index adjustment to apply to convert depth-1 template parameters into
1516 // depth-0 template parameters.
1517 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1518
1519 /// Transform a constructor declaration into a deduction guide.
Richard Smithbc491202017-02-17 20:05:37 +00001520 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1521 CXXConstructorDecl *CD) {
Richard Smith32918772017-02-14 00:25:28 +00001522 SmallVector<TemplateArgument, 16> SubstArgs;
1523
Richard Smithb4f96252017-02-21 06:30:38 +00001524 LocalInstantiationScope Scope(SemaRef);
1525
Richard Smith32918772017-02-14 00:25:28 +00001526 // C++ [over.match.class.deduct]p1:
1527 // -- For each constructor of the class template designated by the
1528 // template-name, a function template with the following properties:
1529
1530 // -- The template parameters are the template parameters of the class
1531 // template followed by the template parameters (including default
1532 // template arguments) of the constructor, if any.
1533 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1534 if (FTD) {
1535 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1536 SmallVector<NamedDecl *, 16> AllParams;
1537 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1538 AllParams.insert(AllParams.begin(),
1539 TemplateParams->begin(), TemplateParams->end());
1540 SubstArgs.reserve(InnerParams->size());
1541
1542 // Later template parameters could refer to earlier ones, so build up
1543 // a list of substituted template arguments as we go.
1544 for (NamedDecl *Param : *InnerParams) {
1545 MultiLevelTemplateArgumentList Args;
1546 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001547 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001548 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1549 if (!NewParam)
1550 return nullptr;
1551 AllParams.push_back(NewParam);
1552 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1553 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1554 }
1555 TemplateParams = TemplateParameterList::Create(
1556 SemaRef.Context, InnerParams->getTemplateLoc(),
1557 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1558 /*FIXME: RequiresClause*/ nullptr);
1559 }
1560
1561 // If we built a new template-parameter-list, track that we need to
1562 // substitute references to the old parameters into references to the
1563 // new ones.
1564 MultiLevelTemplateArgumentList Args;
1565 if (FTD) {
1566 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001567 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001568 }
1569
Richard Smithbc491202017-02-17 20:05:37 +00001570 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
Richard Smith32918772017-02-14 00:25:28 +00001571 .getAsAdjusted<FunctionProtoTypeLoc>();
1572 assert(FPTL && "no prototype for constructor declaration");
1573
1574 // Transform the type of the function, adjusting the return type and
1575 // replacing references to the old parameters with references to the
1576 // new ones.
1577 TypeLocBuilder TLB;
1578 SmallVector<ParmVarDecl*, 8> Params;
1579 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1580 if (NewType.isNull())
1581 return nullptr;
1582 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1583
Richard Smithbc491202017-02-17 20:05:37 +00001584 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1585 CD->getLocStart(), CD->getLocation(),
1586 CD->getLocEnd());
Richard Smith32918772017-02-14 00:25:28 +00001587 }
1588
1589 /// Build a deduction guide with the specified parameter types.
1590 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1591 SourceLocation Loc = Template->getLocation();
1592
1593 // Build the requested type.
1594 FunctionProtoType::ExtProtoInfo EPI;
1595 EPI.HasTrailingReturn = true;
1596 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1597 DeductionGuideName, EPI);
1598 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1599
1600 FunctionProtoTypeLoc FPTL =
1601 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1602
1603 // Build the parameters, needed during deduction / substitution.
1604 SmallVector<ParmVarDecl*, 4> Params;
1605 for (auto T : ParamTypes) {
1606 ParmVarDecl *NewParam = ParmVarDecl::Create(
1607 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1608 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1609 NewParam->setScopeInfo(0, Params.size());
1610 FPTL.setParam(Params.size(), NewParam);
1611 Params.push_back(NewParam);
1612 }
1613
1614 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1615 Loc, Loc, Loc);
1616 }
1617
1618private:
1619 /// Transform a constructor template parameter into a deduction guide template
1620 /// parameter, rebuilding any internal references to earlier parameters and
1621 /// renumbering as we go.
1622 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1623 MultiLevelTemplateArgumentList &Args) {
1624 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1625 // TemplateTypeParmDecl's index cannot be changed after creation, so
1626 // substitute it directly.
1627 auto *NewTTP = TemplateTypeParmDecl::Create(
1628 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1629 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1630 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1631 TTP->isParameterPack());
1632 if (TTP->hasDefaultArgument()) {
1633 TypeSourceInfo *InstantiatedDefaultArg =
1634 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1635 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1636 if (InstantiatedDefaultArg)
1637 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1638 }
Richard Smithb4f96252017-02-21 06:30:38 +00001639 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1640 NewTTP);
Richard Smith32918772017-02-14 00:25:28 +00001641 return NewTTP;
1642 }
1643
1644 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1645 return transformTemplateParameterImpl(TTP, Args);
1646
1647 return transformTemplateParameterImpl(
1648 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1649 }
1650 template<typename TemplateParmDecl>
1651 TemplateParmDecl *
1652 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1653 MultiLevelTemplateArgumentList &Args) {
1654 // Ask the template instantiator to do the heavy lifting for us, then adjust
1655 // the index of the parameter once it's done.
1656 auto *NewParam =
1657 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1658 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1659 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1660 return NewParam;
1661 }
1662
1663 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1664 FunctionProtoTypeLoc TL,
1665 SmallVectorImpl<ParmVarDecl*> &Params,
1666 MultiLevelTemplateArgumentList &Args) {
1667 SmallVector<QualType, 4> ParamTypes;
1668 const FunctionProtoType *T = TL.getTypePtr();
1669
1670 // -- The types of the function parameters are those of the constructor.
1671 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001672 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001673 if (!NewParam)
1674 return QualType();
1675 ParamTypes.push_back(NewParam->getType());
1676 Params.push_back(NewParam);
1677 }
1678
1679 // -- The return type is the class template specialization designated by
1680 // the template-name and template arguments corresponding to the
1681 // template parameters obtained from the class template.
1682 //
1683 // We use the injected-class-name type of the primary template instead.
1684 // This has the convenient property that it is different from any type that
1685 // the user can write in a deduction-guide (because they cannot enter the
1686 // context of the template), so implicit deduction guides can never collide
1687 // with explicit ones.
1688 QualType ReturnType = DeducedType;
1689 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1690
1691 // Resolving a wording defect, we also inherit the variadicness of the
1692 // constructor.
1693 FunctionProtoType::ExtProtoInfo EPI;
1694 EPI.Variadic = T->isVariadic();
1695 EPI.HasTrailingReturn = true;
1696
1697 QualType Result = SemaRef.BuildFunctionType(
1698 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1699 if (Result.isNull())
1700 return QualType();
1701
1702 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1703 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1704 NewTL.setLParenLoc(TL.getLParenLoc());
1705 NewTL.setRParenLoc(TL.getRParenLoc());
1706 NewTL.setExceptionSpecRange(SourceRange());
1707 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1708 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1709 NewTL.setParam(I, Params[I]);
1710
1711 return Result;
1712 }
1713
1714 ParmVarDecl *
1715 transformFunctionTypeParam(ParmVarDecl *OldParam,
1716 MultiLevelTemplateArgumentList &Args) {
1717 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smith479ba8e2017-04-20 01:15:31 +00001718 TypeSourceInfo *NewDI;
1719 if (!Args.getNumLevels())
1720 NewDI = OldDI;
1721 else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1722 // Expand out the one and only element in each inner pack.
1723 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1724 NewDI =
1725 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1726 OldParam->getLocation(), OldParam->getDeclName());
1727 if (!NewDI) return nullptr;
1728 NewDI =
1729 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1730 PackTL.getTypePtr()->getNumExpansions());
1731 } else
1732 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1733 OldParam->getDeclName());
Richard Smith32918772017-02-14 00:25:28 +00001734 if (!NewDI)
1735 return nullptr;
1736
Richard Smithc27b3d72017-02-14 01:49:59 +00001737 // Canonicalize the type. This (for instance) replaces references to
1738 // typedef members of the current instantiations with the definitions of
1739 // those typedefs, avoiding triggering instantiation of the deduced type
1740 // during deduction.
1741 // FIXME: It would be preferable to retain type sugar and source
1742 // information here (and handle this in substitution instead).
1743 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1744 SemaRef.Context.getCanonicalType(NewDI->getType()),
1745 OldParam->getLocation());
1746
Richard Smith32918772017-02-14 00:25:28 +00001747 // Resolving a wording defect, we also inherit default arguments from the
1748 // constructor.
1749 ExprResult NewDefArg;
1750 if (OldParam->hasDefaultArg()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001751 NewDefArg = Args.getNumLevels()
1752 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1753 : OldParam->getDefaultArg();
Richard Smith32918772017-02-14 00:25:28 +00001754 if (NewDefArg.isInvalid())
1755 return nullptr;
1756 }
1757
1758 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1759 OldParam->getInnerLocStart(),
1760 OldParam->getLocation(),
1761 OldParam->getIdentifier(),
1762 NewDI->getType(),
1763 NewDI,
1764 OldParam->getStorageClass(),
1765 NewDefArg.get());
1766 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1767 OldParam->getFunctionScopeIndex());
1768 return NewParam;
1769 }
1770
1771 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1772 bool Explicit, TypeSourceInfo *TInfo,
1773 SourceLocation LocStart, SourceLocation Loc,
1774 SourceLocation LocEnd) {
Richard Smithbc491202017-02-17 20:05:37 +00001775 DeclarationNameInfo Name(DeductionGuideName, Loc);
Richard Smithefa919a2017-02-16 21:29:21 +00001776 ArrayRef<ParmVarDecl *> Params =
1777 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1778
Richard Smith32918772017-02-14 00:25:28 +00001779 // Build the implicit deduction guide template.
Richard Smithbc491202017-02-17 20:05:37 +00001780 auto *Guide =
1781 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1782 Name, TInfo->getType(), TInfo, LocEnd);
Richard Smith32918772017-02-14 00:25:28 +00001783 Guide->setImplicit();
Richard Smithefa919a2017-02-16 21:29:21 +00001784 Guide->setParams(Params);
1785
1786 for (auto *Param : Params)
1787 Param->setDeclContext(Guide);
Richard Smith32918772017-02-14 00:25:28 +00001788
1789 auto *GuideTemplate = FunctionTemplateDecl::Create(
1790 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1791 GuideTemplate->setImplicit();
1792 Guide->setDescribedFunctionTemplate(GuideTemplate);
1793
1794 if (isa<CXXRecordDecl>(DC)) {
1795 Guide->setAccess(AS_public);
1796 GuideTemplate->setAccess(AS_public);
1797 }
1798
1799 DC->addDecl(GuideTemplate);
1800 return GuideTemplate;
1801 }
1802};
1803}
1804
1805void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1806 SourceLocation Loc) {
1807 DeclContext *DC = Template->getDeclContext();
1808 if (DC->isDependentContext())
1809 return;
1810
1811 ConvertConstructorToDeductionGuideTransform Transform(
1812 *this, cast<ClassTemplateDecl>(Template));
1813 if (!isCompleteType(Loc, Transform.DeducedType))
1814 return;
1815
1816 // Check whether we've already declared deduction guides for this template.
1817 // FIXME: Consider storing a flag on the template to indicate this.
1818 auto Existing = DC->lookup(Transform.DeductionGuideName);
1819 for (auto *D : Existing)
1820 if (D->isImplicit())
1821 return;
1822
1823 // In case we were expanding a pack when we attempted to declare deduction
1824 // guides, turn off pack expansion for everything we're about to do.
1825 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1826 // Create a template instantiation record to track the "instantiation" of
1827 // constructors into deduction guides.
1828 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1829 // this substitution process actually fail?
1830 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1831
1832 // Convert declared constructors into deduction guide templates.
1833 // FIXME: Skip constructors for which deduction must necessarily fail (those
1834 // for which some class template parameter without a default argument never
1835 // appears in a deduced context).
1836 bool AddedAny = false;
1837 bool AddedCopyOrMove = false;
1838 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1839 D = D->getUnderlyingDecl();
1840 if (D->isInvalidDecl() || D->isImplicit())
1841 continue;
1842 D = cast<NamedDecl>(D->getCanonicalDecl());
1843
1844 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00001845 auto *CD =
1846 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00001847 // Class-scope explicit specializations (MS extension) do not result in
1848 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00001849 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00001850 continue;
1851
Richard Smithbc491202017-02-17 20:05:37 +00001852 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00001853 AddedAny = true;
1854
Richard Smith32918772017-02-14 00:25:28 +00001855 AddedCopyOrMove |= CD->isCopyOrMoveConstructor();
1856 }
1857
1858 // Synthesize an X() -> X<...> guide if there were no declared constructors.
1859 // FIXME: The standard doesn't say (how) to do this.
1860 if (!AddedAny)
1861 Transform.buildSimpleDeductionGuide(None);
1862
1863 // Synthesize an X(X<...>) -> X<...> guide if there was no declared constructor
1864 // resembling a copy or move constructor.
1865 // FIXME: The standard doesn't say (how) to do this.
1866 if (!AddedCopyOrMove)
1867 Transform.buildSimpleDeductionGuide(Transform.DeducedType);
1868}
1869
Douglas Gregored5731f2009-11-25 17:50:39 +00001870/// \brief Diagnose the presence of a default template argument on a
1871/// template parameter, which is ill-formed in certain contexts.
1872///
1873/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001874static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001875 Sema::TemplateParamListContext TPC,
1876 SourceLocation ParamLoc,
1877 SourceRange DefArgRange) {
1878 switch (TPC) {
1879 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001880 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001881 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001882 return false;
1883
1884 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001885 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001886 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001887 // A default template-argument shall not be specified in a
1888 // function template declaration or a function template
1889 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00001890 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001891 // template-argument, that declaration shall be a definition and shall be
1892 // the only declaration of the function template in the translation unit.
1893 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001894 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001895 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1896 : diag::ext_template_parameter_default_in_function_template)
1897 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001898 return false;
1899
1900 case Sema::TPC_ClassTemplateMember:
1901 // C++0x [temp.param]p9:
1902 // A default template-argument shall not be specified in the
1903 // template-parameter-lists of the definition of a member of a
1904 // class template that appears outside of the member's class.
1905 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1906 << DefArgRange;
1907 return true;
1908
David Majnemerba8f17a2013-06-25 22:08:55 +00001909 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001910 case Sema::TPC_FriendFunctionTemplate:
1911 // C++ [temp.param]p9:
1912 // A default template-argument shall not be specified in a
1913 // friend template declaration.
1914 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1915 << DefArgRange;
1916 return true;
1917
1918 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1919 // for friend function templates if there is only a single
1920 // declaration (and it is a definition). Strange!
1921 }
1922
David Blaikie8a40f702012-01-17 06:56:22 +00001923 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001924}
1925
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001926/// \brief Check for unexpanded parameter packs within the template parameters
1927/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001928static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1929 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001930 // A template template parameter which is a parameter pack is also a pack
1931 // expansion.
1932 if (TTP->isParameterPack())
1933 return false;
1934
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001935 TemplateParameterList *Params = TTP->getTemplateParameters();
1936 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1937 NamedDecl *P = Params->getParam(I);
1938 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001939 if (!NTTP->isParameterPack() &&
1940 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001941 NTTP->getTypeSourceInfo(),
1942 Sema::UPPC_NonTypeTemplateParameterType))
1943 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001944
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001945 continue;
1946 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001947
1948 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001949 = dyn_cast<TemplateTemplateParmDecl>(P))
1950 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1951 return true;
1952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001953
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001954 return false;
1955}
1956
Douglas Gregordba32632009-02-10 19:49:53 +00001957/// \brief Checks the validity of a template parameter list, possibly
1958/// considering the template parameter list from a previous
1959/// declaration.
1960///
1961/// If an "old" template parameter list is provided, it must be
1962/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1963/// template parameter list.
1964///
1965/// \param NewParams Template parameter list for a new template
1966/// declaration. This template parameter list will be updated with any
1967/// default arguments that are carried through from the previous
1968/// template parameter list.
1969///
1970/// \param OldParams If provided, template parameter list from a
1971/// previous declaration of the same template. Default template
1972/// arguments will be merged from the old template parameter list to
1973/// the new template parameter list.
1974///
Douglas Gregored5731f2009-11-25 17:50:39 +00001975/// \param TPC Describes the context in which we are checking the given
1976/// template parameter list.
1977///
Douglas Gregordba32632009-02-10 19:49:53 +00001978/// \returns true if an error occurred, false otherwise.
1979bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001980 TemplateParameterList *OldParams,
1981 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001982 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001983
Douglas Gregordba32632009-02-10 19:49:53 +00001984 // C++ [temp.param]p10:
1985 // The set of default template-arguments available for use with a
1986 // template declaration or definition is obtained by merging the
1987 // default arguments from the definition (if in scope) and all
1988 // declarations in scope in the same way default function
1989 // arguments are (8.3.6).
1990 bool SawDefaultArgument = false;
1991 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001992
Mike Stumpc89c8e32009-02-11 23:03:27 +00001993 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001994 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001995 if (OldParams)
1996 OldParam = OldParams->begin();
1997
Douglas Gregor0693def2011-01-27 01:40:17 +00001998 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001999 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2000 NewParamEnd = NewParams->end();
2001 NewParam != NewParamEnd; ++NewParam) {
2002 // Variables used to diagnose redundant default arguments
2003 bool RedundantDefaultArg = false;
2004 SourceLocation OldDefaultLoc;
2005 SourceLocation NewDefaultLoc;
2006
David Blaikie651c73c2011-10-19 05:19:50 +00002007 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00002008 bool MissingDefaultArg = false;
2009
David Blaikie651c73c2011-10-19 05:19:50 +00002010 // Variable used to diagnose non-final parameter packs
2011 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00002012
Douglas Gregordba32632009-02-10 19:49:53 +00002013 if (TemplateTypeParmDecl *NewTypeParm
2014 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00002015 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002016 if (NewTypeParm->hasDefaultArgument() &&
2017 DiagnoseDefaultTemplateArgument(*this, TPC,
2018 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002019 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002020 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00002021 NewTypeParm->removeDefaultArgument();
2022
2023 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002024 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002025 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00002026 if (NewTypeParm->isParameterPack()) {
2027 assert(!NewTypeParm->hasDefaultArgument() &&
2028 "Parameter packs can't have a default argument!");
2029 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002030 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00002031 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00002032 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2033 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2034 SawDefaultArgument = true;
2035 RedundantDefaultArg = true;
2036 PreviousDefaultArgLoc = NewDefaultLoc;
2037 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2038 // Merge the default argument from the old declaration to the
2039 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002040 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002041 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2042 } else if (NewTypeParm->hasDefaultArgument()) {
2043 SawDefaultArgument = true;
2044 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2045 } else if (SawDefaultArgument)
2046 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002047 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00002048 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002049 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002050 if (!NewNonTypeParm->isParameterPack() &&
2051 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002052 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002053 UPPC_NonTypeTemplateParameterType)) {
2054 Invalid = true;
2055 continue;
2056 }
2057
Douglas Gregored5731f2009-11-25 17:50:39 +00002058 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002059 if (NewNonTypeParm->hasDefaultArgument() &&
2060 DiagnoseDefaultTemplateArgument(*this, TPC,
2061 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002062 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00002063 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002064 }
2065
Mike Stump12b8ce12009-08-04 21:02:39 +00002066 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002067 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002068 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002069 if (NewNonTypeParm->isParameterPack()) {
2070 assert(!NewNonTypeParm->hasDefaultArgument() &&
2071 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002072 if (!NewNonTypeParm->isPackExpansion())
2073 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002074 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00002075 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00002076 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2077 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2078 SawDefaultArgument = true;
2079 RedundantDefaultArg = true;
2080 PreviousDefaultArgLoc = NewDefaultLoc;
2081 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2082 // Merge the default argument from the old declaration to the
2083 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002084 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002085 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2086 } else if (NewNonTypeParm->hasDefaultArgument()) {
2087 SawDefaultArgument = true;
2088 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2089 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002090 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002091 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00002092 TemplateTemplateParmDecl *NewTemplateParm
2093 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002094
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002095 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002096 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002097 Invalid = true;
2098 continue;
2099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002100
David Blaikie651c73c2011-10-19 05:19:50 +00002101 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002102 if (NewTemplateParm->hasDefaultArgument() &&
2103 DiagnoseDefaultTemplateArgument(*this, TPC,
2104 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002105 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002106 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002107
2108 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002109 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002110 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002111 if (NewTemplateParm->isParameterPack()) {
2112 assert(!NewTemplateParm->hasDefaultArgument() &&
2113 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002114 if (!NewTemplateParm->isPackExpansion())
2115 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002116 } else if (OldTemplateParm &&
2117 hasVisibleDefaultArgument(OldTemplateParm) &&
2118 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002119 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2120 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002121 SawDefaultArgument = true;
2122 RedundantDefaultArg = true;
2123 PreviousDefaultArgLoc = NewDefaultLoc;
2124 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2125 // Merge the default argument from the old declaration to the
2126 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002127 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002128 PreviousDefaultArgLoc
2129 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002130 } else if (NewTemplateParm->hasDefaultArgument()) {
2131 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002132 PreviousDefaultArgLoc
2133 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002134 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002135 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002136 }
2137
Richard Smith1fde8ec2012-09-07 02:06:42 +00002138 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002139 // If a template parameter of a primary class template or alias template
2140 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002141 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002142 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2143 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002144 Diag((*NewParam)->getLocation(),
2145 diag::err_template_param_pack_must_be_last_template_parameter);
2146 Invalid = true;
2147 }
2148
Douglas Gregordba32632009-02-10 19:49:53 +00002149 if (RedundantDefaultArg) {
2150 // C++ [temp.param]p12:
2151 // A template-parameter shall not be given default arguments
2152 // by two different declarations in the same scope.
2153 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2154 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2155 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002156 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002157 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002158 // If a template-parameter of a class template has a default
2159 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002160 // have a default template-argument supplied or be a template parameter
2161 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002162 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002163 diag::err_template_param_default_arg_missing);
2164 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2165 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002166 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002167 }
2168
2169 // If we have an old template parameter list that we're merging
2170 // in, move on to the next parameter.
2171 if (OldParams)
2172 ++OldParam;
2173 }
2174
Douglas Gregor0693def2011-01-27 01:40:17 +00002175 // We were missing some default arguments at the end of the list, so remove
2176 // all of the default arguments.
2177 if (RemoveDefaultArguments) {
2178 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2179 NewParamEnd = NewParams->end();
2180 NewParam != NewParamEnd; ++NewParam) {
2181 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2182 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002183 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002184 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2185 NTTP->removeDefaultArgument();
2186 else
2187 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2188 }
2189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002190
Douglas Gregordba32632009-02-10 19:49:53 +00002191 return Invalid;
2192}
Douglas Gregord32e0282009-02-09 23:23:08 +00002193
John McCalla020a012010-10-20 05:44:58 +00002194namespace {
2195
2196/// A class which looks for a use of a certain level of template
2197/// parameter.
2198struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2199 typedef RecursiveASTVisitor<DependencyChecker> super;
2200
2201 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00002202
2203 // Whether we're looking for a use of a template parameter that makes the
2204 // overall construct type-dependent / a dependent type. This is strictly
2205 // best-effort for now; we may fail to match at all for a dependent type
2206 // in some cases if this is set.
2207 bool IgnoreNonTypeDependent;
2208
John McCalla020a012010-10-20 05:44:58 +00002209 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002210 SourceLocation MatchLoc;
2211
Richard Smith13894182017-04-13 21:37:24 +00002212 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2213 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2214 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002215
Richard Smith57aae072016-12-28 02:37:25 +00002216 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith13894182017-04-13 21:37:24 +00002217 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2218 NamedDecl *ND = Params->getParam(0);
2219 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2220 Depth = PD->getDepth();
2221 } else if (NonTypeTemplateParmDecl *PD =
2222 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2223 Depth = PD->getDepth();
2224 } else {
2225 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2226 }
2227 }
John McCalla020a012010-10-20 05:44:58 +00002228
Richard Smith6056d5e2014-02-09 00:54:43 +00002229 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith13894182017-04-13 21:37:24 +00002230 if (ParmDepth >= Depth) {
John McCalla020a012010-10-20 05:44:58 +00002231 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002232 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002233 return true;
2234 }
2235 return false;
2236 }
2237
Richard Smith57aae072016-12-28 02:37:25 +00002238 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2239 // Prune out non-type-dependent expressions if requested. This can
2240 // sometimes result in us failing to find a template parameter reference
2241 // (if a value-dependent expression creates a dependent type), but this
2242 // mode is best-effort only.
2243 if (auto *E = dyn_cast_or_null<Expr>(S))
2244 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2245 return true;
2246 return super::TraverseStmt(S, Q);
2247 }
2248
2249 bool TraverseTypeLoc(TypeLoc TL) {
2250 if (IgnoreNonTypeDependent && !TL.isNull() &&
2251 !TL.getType()->isDependentType())
2252 return true;
2253 return super::TraverseTypeLoc(TL);
2254 }
2255
Richard Smith6056d5e2014-02-09 00:54:43 +00002256 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2257 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2258 }
2259
John McCalla020a012010-10-20 05:44:58 +00002260 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002261 // For a best-effort search, keep looking until we find a location.
2262 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002263 }
2264
2265 bool TraverseTemplateName(TemplateName N) {
2266 if (TemplateTemplateParmDecl *PD =
2267 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002268 if (Matches(PD->getDepth()))
2269 return false;
John McCalla020a012010-10-20 05:44:58 +00002270 return super::TraverseTemplateName(N);
2271 }
2272
2273 bool VisitDeclRefExpr(DeclRefExpr *E) {
2274 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002275 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2276 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002277 return false;
John McCalla020a012010-10-20 05:44:58 +00002278 return super::VisitDeclRefExpr(E);
2279 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002280
2281 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2282 return TraverseType(T->getReplacementType());
2283 }
2284
2285 bool
2286 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2287 return TraverseTemplateArgument(T->getArgumentPack());
2288 }
2289
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002290 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2291 return TraverseType(T->getInjectedSpecializationType());
2292 }
John McCalla020a012010-10-20 05:44:58 +00002293};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002294} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002295
Douglas Gregor972fe532011-05-10 18:27:06 +00002296/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002297/// list.
2298static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002299DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002300 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002301 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002302 return Checker.Match;
2303}
2304
Douglas Gregor972fe532011-05-10 18:27:06 +00002305// Find the source range corresponding to the named type in the given
2306// nested-name-specifier, if any.
2307static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2308 QualType T,
2309 const CXXScopeSpec &SS) {
2310 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2311 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2312 if (const Type *CurType = NNS->getAsType()) {
2313 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2314 return NNSLoc.getTypeLoc().getSourceRange();
2315 } else
2316 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002317
Douglas Gregor972fe532011-05-10 18:27:06 +00002318 NNSLoc = NNSLoc.getPrefix();
2319 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002320
Douglas Gregor972fe532011-05-10 18:27:06 +00002321 return SourceRange();
2322}
2323
Mike Stump11289f42009-09-09 15:08:12 +00002324/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002325/// specifier, returning the template parameter list that applies to the
2326/// name.
2327///
2328/// \param DeclStartLoc the start of the declaration that has a scope
2329/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002330///
Douglas Gregor972fe532011-05-10 18:27:06 +00002331/// \param DeclLoc The location of the declaration itself.
2332///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002333/// \param SS the scope specifier that will be matched to the given template
2334/// parameter lists. This scope specifier precedes a qualified name that is
2335/// being declared.
2336///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002337/// \param TemplateId The template-id following the scope specifier, if there
2338/// is one. Used to check for a missing 'template<>'.
2339///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002340/// \param ParamLists the template parameter lists, from the outermost to the
2341/// innermost template parameter lists.
2342///
John McCalle820e5e2010-04-13 20:37:33 +00002343/// \param IsFriend Whether to apply the slightly different rules for
2344/// matching template parameters to scope specifiers in friend
2345/// declarations.
2346///
Richard Smithf445f192017-02-09 21:04:43 +00002347/// \param IsMemberSpecialization will be set true if the scope specifier
2348/// denotes a fully-specialized type, and therefore this is a declaration of
2349/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002350///
Mike Stump11289f42009-09-09 15:08:12 +00002351/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002352/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002353/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002354/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002355/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002356/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002357TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2358 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002359 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002360 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002361 bool &IsMemberSpecialization, bool &Invalid) {
2362 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002363 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002364
Douglas Gregor972fe532011-05-10 18:27:06 +00002365 // The sequence of nested types to which we will match up the template
2366 // parameter lists. We first build this list by starting with the type named
2367 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002368 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002369 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002370 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002371 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002372 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2373 T = Context.getTypeDeclType(Record);
2374 else
2375 T = QualType(SS.getScopeRep()->getAsType(), 0);
2376 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002377
Douglas Gregor972fe532011-05-10 18:27:06 +00002378 // If we found an explicit specialization that prevents us from needing
2379 // 'template<>' headers, this will be set to the location of that
2380 // explicit specialization.
2381 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002382
Douglas Gregor972fe532011-05-10 18:27:06 +00002383 while (!T.isNull()) {
2384 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002385
Douglas Gregor972fe532011-05-10 18:27:06 +00002386 // Retrieve the parent of a record type.
2387 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2388 // If this type is an explicit specialization, we're done.
2389 if (ClassTemplateSpecializationDecl *Spec
2390 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002391 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002392 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2393 ExplicitSpecLoc = Spec->getLocation();
2394 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002395 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002396 } else if (Record->getTemplateSpecializationKind()
2397 == TSK_ExplicitSpecialization) {
2398 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002399 break;
2400 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002401
Douglas Gregor972fe532011-05-10 18:27:06 +00002402 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2403 T = Context.getTypeDeclType(Parent);
2404 else
2405 T = QualType();
2406 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002407 }
2408
Douglas Gregor972fe532011-05-10 18:27:06 +00002409 if (const TemplateSpecializationType *TST
2410 = T->getAs<TemplateSpecializationType>()) {
2411 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2412 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2413 T = Context.getTypeDeclType(Parent);
2414 else
2415 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002416 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002417 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002418 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002419
Douglas Gregor972fe532011-05-10 18:27:06 +00002420 // Look one step prior in a dependent template specialization type.
2421 if (const DependentTemplateSpecializationType *DependentTST
2422 = T->getAs<DependentTemplateSpecializationType>()) {
2423 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2424 T = QualType(NNS->getAsType(), 0);
2425 else
2426 T = QualType();
2427 continue;
2428 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002429
Douglas Gregor972fe532011-05-10 18:27:06 +00002430 // Look one step prior in a dependent name type.
2431 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2432 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2433 T = QualType(NNS->getAsType(), 0);
2434 else
2435 T = QualType();
2436 continue;
2437 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002438
Douglas Gregor972fe532011-05-10 18:27:06 +00002439 // Retrieve the parent of an enumeration type.
2440 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2441 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2442 // check here.
2443 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002444
Douglas Gregor972fe532011-05-10 18:27:06 +00002445 // Get to the parent type.
2446 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2447 T = Context.getTypeDeclType(Parent);
2448 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002449 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002450 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002451 }
Mike Stump11289f42009-09-09 15:08:12 +00002452
Douglas Gregor972fe532011-05-10 18:27:06 +00002453 T = QualType();
2454 }
2455 // Reverse the nested types list, since we want to traverse from the outermost
2456 // to the innermost while checking template-parameter-lists.
2457 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002458
Douglas Gregor972fe532011-05-10 18:27:06 +00002459 // C++0x [temp.expl.spec]p17:
2460 // A member or a member template may be nested within many
2461 // enclosing class templates. In an explicit specialization for
2462 // such a member, the member declaration shall be preceded by a
2463 // template<> for each enclosing class template that is
2464 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002465 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002466
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002467 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002468 if (SawNonEmptyTemplateParameterList) {
2469 Diag(DeclLoc, diag::err_specialize_member_of_template)
2470 << !Recovery << Range;
2471 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002472 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002473 return true;
2474 }
2475
2476 return false;
2477 };
2478
2479 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2480 // Check that we can have an explicit specialization here.
2481 if (CheckExplicitSpecialization(Range, true))
2482 return true;
2483
2484 // We don't have a template header, but we should.
2485 SourceLocation ExpectedTemplateLoc;
2486 if (!ParamLists.empty())
2487 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2488 else
2489 ExpectedTemplateLoc = DeclStartLoc;
2490
2491 Diag(DeclLoc, diag::err_template_spec_needs_header)
2492 << Range
2493 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2494 return false;
2495 };
2496
Douglas Gregor972fe532011-05-10 18:27:06 +00002497 unsigned ParamIdx = 0;
2498 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2499 ++TypeIdx) {
2500 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002501
Douglas Gregor972fe532011-05-10 18:27:06 +00002502 // Whether we expect a 'template<>' header.
2503 bool NeedEmptyTemplateHeader = false;
2504
2505 // Whether we expect a template header with parameters.
2506 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002507
Douglas Gregor972fe532011-05-10 18:27:06 +00002508 // For a dependent type, the set of template parameters that we
2509 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002510 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002511
Douglas Gregor373af9b2011-05-11 23:26:17 +00002512 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002513 // A member or a member template may be nested within many enclosing
2514 // class templates. In an explicit specialization for such a member, the
2515 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002516 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002517 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2518 if (ClassTemplatePartialSpecializationDecl *Partial
2519 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2520 ExpectedTemplateParams = Partial->getTemplateParameters();
2521 NeedNonemptyTemplateHeader = true;
2522 } else if (Record->isDependentType()) {
2523 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002524 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002525 ->getTemplateParameters();
2526 NeedNonemptyTemplateHeader = true;
2527 }
2528 } else if (ClassTemplateSpecializationDecl *Spec
2529 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2530 // C++0x [temp.expl.spec]p4:
2531 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002532 // in the same manner as members of normal classes, and not using
2533 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002534 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2535 NeedEmptyTemplateHeader = true;
2536 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002537 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002538 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002539 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002540 != TSK_ExplicitSpecialization &&
2541 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002542 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002543
Douglas Gregor373af9b2011-05-11 23:26:17 +00002544 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002545 }
2546 } else if (const TemplateSpecializationType *TST
2547 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002548 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002549 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002550 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002551 }
2552 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2553 // FIXME: We actually could/should check the template arguments here
2554 // against the corresponding template parameter list.
2555 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002556 }
2557
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002558 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002559 // In an explicit specialization declaration for a member of a class
2560 // template or a member template that ap- pears in namespace scope, the
2561 // member template and some of its enclosing class templates may remain
2562 // unspecialized, except that the declaration shall not explicitly
2563 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002564 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002565 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002566 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002567 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2568 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002569 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002570 } else
2571 SawNonEmptyTemplateParameterList = true;
2572 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002573
Douglas Gregor972fe532011-05-10 18:27:06 +00002574 if (NeedEmptyTemplateHeader) {
2575 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002576 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002577 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002578 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002579
2580 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002581 if (ParamLists[ParamIdx]->size() > 0) {
2582 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002583 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002584 diag::err_template_param_list_matches_nontemplate)
2585 << T
2586 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2587 ParamLists[ParamIdx]->getRAngleLoc())
2588 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2589 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002590 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002591 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002592
Douglas Gregor972fe532011-05-10 18:27:06 +00002593 // Consume this template header.
2594 ++ParamIdx;
2595 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002596 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002597
2598 if (!IsFriend)
2599 if (DiagnoseMissingExplicitSpecialization(
2600 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002601 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002602
Douglas Gregor972fe532011-05-10 18:27:06 +00002603 continue;
2604 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002605
Douglas Gregor972fe532011-05-10 18:27:06 +00002606 if (NeedNonemptyTemplateHeader) {
2607 // In friend declarations we can have template-ids which don't
2608 // depend on the corresponding template parameter lists. But
2609 // assume that empty parameter lists are supposed to match this
2610 // template-id.
2611 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002612 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002613 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002614 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002615 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002616 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002617 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002618
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002619 if (ParamIdx < ParamLists.size()) {
2620 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002621 if (ExpectedTemplateParams &&
2622 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2623 ExpectedTemplateParams,
2624 true, TPL_TemplateMatch))
2625 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002626
Douglas Gregor972fe532011-05-10 18:27:06 +00002627 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002628 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002629 TPC_ClassTemplateMember))
2630 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002631
Douglas Gregor972fe532011-05-10 18:27:06 +00002632 ++ParamIdx;
2633 continue;
2634 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002635
Douglas Gregor972fe532011-05-10 18:27:06 +00002636 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2637 << T
2638 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2639 Invalid = true;
2640 continue;
2641 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002642 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002643
Douglas Gregord8d297c2009-07-21 23:53:31 +00002644 // If there were at least as many template-ids as there were template
2645 // parameter lists, then there are no template parameter lists remaining for
2646 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002647 if (ParamIdx >= ParamLists.size()) {
2648 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002649 // We don't have a template header for the declaration itself, but we
2650 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002651 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2652 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002653
2654 // Fabricate an empty template parameter list for the invented header.
2655 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002656 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002657 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002658 }
2659
Craig Topperc3ec1492014-05-26 06:22:03 +00002660 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002661 }
Mike Stump11289f42009-09-09 15:08:12 +00002662
Douglas Gregord8d297c2009-07-21 23:53:31 +00002663 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002664 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002665 bool HasAnyExplicitSpecHeader = false;
2666 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002667 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002668 if (ParamLists[I]->size() == 0)
2669 HasAnyExplicitSpecHeader = true;
2670 else
2671 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002672 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002673
Douglas Gregor972fe532011-05-10 18:27:06 +00002674 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002675 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2676 : diag::err_template_spec_extra_headers)
2677 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2678 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002679
2680 // If there was a specialization somewhere, such that 'template<>' is
2681 // not required, and there were any 'template<>' headers, note where the
2682 // specialization occurred.
2683 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002684 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002685 diag::note_explicit_template_spec_does_not_need_header)
2686 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002687
Douglas Gregor972fe532011-05-10 18:27:06 +00002688 // We have a template parameter list with no corresponding scope, which
2689 // means that the resulting template declaration can't be instantiated
2690 // properly (we'll end up with dependent nodes when we shouldn't).
2691 if (!AllExplicitSpecHeaders)
2692 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002693 }
Mike Stump11289f42009-09-09 15:08:12 +00002694
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002695 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002696 // In an explicit specialization declaration for a member of a class
2697 // template or a member template that ap- pears in namespace scope, the
2698 // member template and some of its enclosing class templates may remain
2699 // unspecialized, except that the declaration shall not explicitly
2700 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002701 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002702 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002703 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2704 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002705 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002706
Douglas Gregord8d297c2009-07-21 23:53:31 +00002707 // Return the last template parameter list, which corresponds to the
2708 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002709 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002710}
2711
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002712void Sema::NoteAllFoundTemplates(TemplateName Name) {
2713 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2714 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002715 << (isa<FunctionTemplateDecl>(Template)
2716 ? 0
2717 : isa<ClassTemplateDecl>(Template)
2718 ? 1
2719 : isa<VarTemplateDecl>(Template)
2720 ? 2
2721 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2722 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002723 return;
2724 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002725
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002726 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002727 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002728 IEnd = OST->end();
2729 I != IEnd; ++I)
2730 Diag((*I)->getLocation(), diag::note_template_declared_here)
2731 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002732
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002733 return;
2734 }
2735}
2736
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002737static QualType
2738checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2739 const SmallVectorImpl<TemplateArgument> &Converted,
2740 SourceLocation TemplateLoc,
2741 TemplateArgumentListInfo &TemplateArgs) {
2742 ASTContext &Context = SemaRef.getASTContext();
2743 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002744 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002745 // Specializations of __make_integer_seq<S, T, N> are treated like
2746 // S<T, 0, ..., N-1>.
2747
2748 // C++14 [inteseq.intseq]p1:
2749 // T shall be an integer type.
2750 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2751 SemaRef.Diag(TemplateArgs[1].getLocation(),
2752 diag::err_integer_sequence_integral_element_type);
2753 return QualType();
2754 }
2755
2756 // C++14 [inteseq.make]p1:
2757 // If N is negative the program is ill-formed.
2758 TemplateArgument NumArgsArg = Converted[2];
2759 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2760 if (NumArgs < 0) {
2761 SemaRef.Diag(TemplateArgs[2].getLocation(),
2762 diag::err_integer_sequence_negative_length);
2763 return QualType();
2764 }
2765
2766 QualType ArgTy = NumArgsArg.getIntegralType();
2767 TemplateArgumentListInfo SyntheticTemplateArgs;
2768 // The type argument gets reused as the first template argument in the
2769 // synthetic template argument list.
2770 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2771 // Expand N into 0 ... N-1.
2772 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2773 I < NumArgs; ++I) {
2774 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002775 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2776 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002777 }
2778 // The first template argument will be reused as the template decl that
2779 // our synthetic template arguments will be applied to.
2780 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2781 TemplateLoc, SyntheticTemplateArgs);
2782 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002783
2784 case BTK__type_pack_element:
2785 // Specializations of
2786 // __type_pack_element<Index, T_1, ..., T_N>
2787 // are treated like T_Index.
2788 assert(Converted.size() == 2 &&
2789 "__type_pack_element should be given an index and a parameter pack");
2790
2791 // If the Index is out of bounds, the program is ill-formed.
2792 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2793 llvm::APSInt Index = IndexArg.getAsIntegral();
2794 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2795 "type std::size_t, and hence be non-negative");
2796 if (Index >= Ts.pack_size()) {
2797 SemaRef.Diag(TemplateArgs[0].getLocation(),
2798 diag::err_type_pack_element_out_of_bounds);
2799 return QualType();
2800 }
2801
2802 // We simply return the type at index `Index`.
2803 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2804 return Nth->getAsType();
2805 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002806 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2807}
2808
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002809/// Determine whether this alias template is "enable_if_t".
2810static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
2811 return AliasTemplate->getName().equals("enable_if_t");
2812}
2813
2814/// Collect all of the separable terms in the given condition, which
2815/// might be a conjunction.
2816///
2817/// FIXME: The right answer is to convert the logical expression into
2818/// disjunctive normal form, so we can find the first failed term
2819/// within each possible clause.
2820static void collectConjunctionTerms(Expr *Clause,
2821 SmallVectorImpl<Expr *> &Terms) {
2822 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
2823 if (BinOp->getOpcode() == BO_LAnd) {
2824 collectConjunctionTerms(BinOp->getLHS(), Terms);
2825 collectConjunctionTerms(BinOp->getRHS(), Terms);
2826 }
2827
2828 return;
2829 }
2830
2831 Terms.push_back(Clause);
2832}
2833
2834/// Find the failed subexpression within enable_if, and describe it
2835/// with a string.
2836static std::pair<Expr *, std::string>
2837findFailedEnableIfCondition(Sema &S, Expr *Cond) {
2838 // Separate out all of the terms in a conjunction.
2839 SmallVector<Expr *, 4> Terms;
2840 collectConjunctionTerms(Cond, Terms);
2841
2842 // Determine which term failed.
2843 Expr *FailedCond = nullptr;
2844 for (Expr *Term : Terms) {
2845 // The initialization of the parameter from the argument is
2846 // a constant-evaluated context.
2847 EnterExpressionEvaluationContext ConstantEvaluated(
2848 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2849
2850 bool Succeeded;
2851 if (Term->EvaluateAsBooleanCondition(Succeeded, S.Context) &&
2852 !Succeeded) {
2853 FailedCond = Term->IgnoreParenImpCasts();
2854 break;
2855 }
2856 }
2857
2858 if (!FailedCond)
2859 FailedCond = Cond->IgnoreParenImpCasts();
2860
2861 std::string Description;
2862 {
2863 llvm::raw_string_ostream Out(Description);
2864 FailedCond->printPretty(Out, nullptr,
2865 PrintingPolicy(S.Context.getLangOpts()));
2866 }
2867 return { FailedCond, Description };
2868}
2869
Douglas Gregordc572a32009-03-30 22:58:21 +00002870QualType Sema::CheckTemplateIdType(TemplateName Name,
2871 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002872 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002873 DependentTemplateName *DTN
2874 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002875 if (DTN && DTN->isIdentifier())
2876 // When building a template-id where the template-name is dependent,
2877 // assume the template is a type template. Either our assumption is
2878 // correct, or the code is ill-formed and will be diagnosed when the
2879 // dependent name is substituted.
2880 return Context.getDependentTemplateSpecializationType(ETK_None,
2881 DTN->getQualifier(),
2882 DTN->getIdentifier(),
2883 TemplateArgs);
2884
Douglas Gregordc572a32009-03-30 22:58:21 +00002885 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002886 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2887 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002888 // We might have a substituted template template parameter pack. If so,
2889 // build a template specialization type for it.
2890 if (Name.getAsSubstTemplateTemplateParmPack())
2891 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002892
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002893 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2894 << Name;
2895 NoteAllFoundTemplates(Name);
2896 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002897 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002898
Douglas Gregorc40290e2009-03-09 23:48:35 +00002899 // Check that the template argument list is well-formed for this
2900 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002901 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002902 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002903 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002904 return QualType();
2905
Douglas Gregorc40290e2009-03-09 23:48:35 +00002906 QualType CanonType;
2907
Douglas Gregor678d76c2011-07-01 01:22:09 +00002908 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002909 if (TypeAliasTemplateDecl *AliasTemplate =
2910 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002911 // Find the canonical type for this type alias template specialization.
2912 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2913 if (Pattern->isInvalidDecl())
2914 return QualType();
2915
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002916 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
2917 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002918
2919 // Only substitute for the innermost template argument list.
2920 MultiLevelTemplateArgumentList TemplateArgLists;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002921 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002922 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2923 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002924 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002925
Richard Smith802c4b72012-08-23 06:16:52 +00002926 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002927 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002928 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002929 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002930
Richard Smith3f1b5d02011-05-05 21:57:07 +00002931 CanonType = SubstType(Pattern->getUnderlyingType(),
2932 TemplateArgLists, AliasTemplate->getLocation(),
2933 AliasTemplate->getDeclName());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002934 if (CanonType.isNull()) {
2935 // If this was enable_if and we failed to find the nested type
2936 // within enable_if in a SFINAE context, dig out the specific
2937 // enable_if condition that failed and present that instead.
2938 if (isEnableIfAliasTemplate(AliasTemplate)) {
2939 if (auto DeductionInfo = isSFINAEContext()) {
2940 if (*DeductionInfo &&
2941 (*DeductionInfo)->hasSFINAEDiagnostic() &&
2942 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
2943 diag::err_typename_nested_not_found_enable_if &&
2944 TemplateArgs[0].getArgument().getKind()
2945 == TemplateArgument::Expression) {
2946 Expr *FailedCond;
2947 std::string FailedDescription;
2948 std::tie(FailedCond, FailedDescription) =
2949 findFailedEnableIfCondition(
2950 *this, TemplateArgs[0].getSourceExpression());
2951
2952 // Remove the old SFINAE diagnostic.
2953 PartialDiagnosticAt OldDiag =
2954 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
2955 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
2956
2957 // Add a new SFINAE diagnostic specifying which condition
2958 // failed.
2959 (*DeductionInfo)->addSFINAEDiagnostic(
2960 OldDiag.first,
2961 PDiag(diag::err_typename_nested_not_found_requirement)
2962 << FailedDescription
2963 << FailedCond->getSourceRange());
2964 }
2965 }
2966 }
2967
Richard Smith3f1b5d02011-05-05 21:57:07 +00002968 return QualType();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002969 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002970 } else if (Name.isDependent() ||
2971 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002972 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002973 // This class template specialization is a dependent
2974 // type. Therefore, its canonical type is another class template
2975 // specialization type that contains all of the converted
2976 // arguments in canonical form. This ensures that, e.g., A<T> and
2977 // A<T, T> have identical types when A is declared as:
2978 //
2979 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00002980 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00002981
2982 // This might work out to be a current instantiation, in which
2983 // case the canonical type needs to be the InjectedClassNameType.
2984 //
2985 // TODO: in theory this could be a simple hashtable lookup; most
2986 // changes to CurContext don't change the set of current
2987 // instantiations.
2988 if (isa<ClassTemplateDecl>(Template)) {
2989 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2990 // If we get out to a namespace, we're done.
2991 if (Ctx->isFileContext()) break;
2992
2993 // If this isn't a record, keep looking.
2994 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2995 if (!Record) continue;
2996
2997 // Look for one of the two cases with InjectedClassNameTypes
2998 // and check whether it's the same template.
2999 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3000 !Record->getDescribedClassTemplate())
3001 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003002
John McCall2408e322010-04-27 00:57:59 +00003003 // Fetch the injected class name type and check whether its
3004 // injected type is equal to the type we just built.
3005 QualType ICNT = Context.getTypeDeclType(Record);
3006 QualType Injected = cast<InjectedClassNameType>(ICNT)
3007 ->getInjectedSpecializationType();
3008
3009 if (CanonType != Injected->getCanonicalTypeInternal())
3010 continue;
3011
3012 // If so, the canonical type of this TST is the injected
3013 // class name type of the record we just found.
3014 assert(ICNT.isCanonical());
3015 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00003016 break;
3017 }
3018 }
Mike Stump11289f42009-09-09 15:08:12 +00003019 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00003020 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003021 // Find the class template specialization declaration that
3022 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003023 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003024 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00003025 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003026 if (!Decl) {
3027 // This is the first time we have referenced this class template
3028 // specialization. Create the canonical declaration and add it to
3029 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003030 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00003031 ClassTemplate->getTemplatedDecl()->getTagKind(),
3032 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00003033 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003034 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003035 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00003036 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003037 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00003038 if (ClassTemplate->isOutOfLine())
3039 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00003040 }
3041
Erich Keanea32910d2017-03-23 18:51:54 +00003042 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3043 MultiLevelTemplateArgumentList TemplateArgLists;
3044 TemplateArgLists.addOuterTemplateArguments(Converted);
3045 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3046 Decl);
3047 }
3048
Chandler Carruth2acfb222013-09-27 22:14:40 +00003049 // Diagnose uses of this specialization.
3050 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3051
Douglas Gregorc40290e2009-03-09 23:48:35 +00003052 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00003053 assert(isa<RecordType>(CanonType) &&
3054 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003055 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3056 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3057 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003058 }
Mike Stump11289f42009-09-09 15:08:12 +00003059
Douglas Gregorc40290e2009-03-09 23:48:35 +00003060 // Build the fully-sugared type for this class template
3061 // specialization, which refers back to the class template
3062 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00003063 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003064}
3065
John McCallfaf5fb42010-08-26 23:41:50 +00003066TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003067Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00003068 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3069 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00003070 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00003071 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00003072 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00003073 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003074 if (SS.isInvalid())
3075 return true;
3076
Richard Smith62559bd2017-02-01 21:36:38 +00003077 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3078 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3079
3080 // C++ [temp.res]p3:
3081 // A qualified-id that refers to a type and in which the
3082 // nested-name-specifier depends on a template-parameter (14.6.2)
3083 // shall be prefixed by the keyword typename to indicate that the
3084 // qualified-id denotes a type, forming an
3085 // elaborated-type-specifier (7.1.5.3).
3086 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00003087 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00003088 << SS.getScopeRep() << TemplateII->getName();
3089 // Recover as if 'typename' were specified.
3090 // FIXME: This is not quite correct recovery as we don't transform SS
3091 // into the corresponding dependent form (and we don't diagnose missing
3092 // 'template' keywords within SS as a result).
3093 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3094 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3095 TemplateArgsIn, RAngleLoc);
3096 }
3097
3098 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3099 // it's not actually allowed to be used as a type in most cases. Because
3100 // we annotate it before we know whether it's valid, we have to check for
3101 // this case here.
3102 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00003103 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3104 Diag(TemplateIILoc,
3105 TemplateKWLoc.isInvalid()
3106 ? diag::err_out_of_line_qualified_id_type_names_constructor
3107 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3108 << TemplateII << 0 /*injected-class-name used as template name*/
3109 << 1 /*if any keyword was present, it was 'template'*/;
3110 }
3111 }
3112
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003113 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00003114
Douglas Gregorc40290e2009-03-09 23:48:35 +00003115 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003116 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003117 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00003118
Douglas Gregor5a064722011-02-28 17:23:35 +00003119 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00003120 QualType T
3121 = Context.getDependentTemplateSpecializationType(ETK_None,
3122 DTN->getQualifier(),
3123 DTN->getIdentifier(),
3124 TemplateArgs);
3125 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00003126 TypeLocBuilder TLB;
3127 DependentTemplateSpecializationTypeLoc SpecTL
3128 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003129 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3130 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003131 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003132 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003133 SpecTL.setLAngleLoc(LAngleLoc);
3134 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003135 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3136 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3137 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3138 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003139
Richard Smith74f02342017-01-19 21:00:13 +00003140 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003141 if (Result.isNull())
3142 return true;
3143
Douglas Gregore7c20652011-03-02 00:47:37 +00003144 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003145 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00003146 TemplateSpecializationTypeLoc SpecTL
3147 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003148 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003149 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003150 SpecTL.setLAngleLoc(LAngleLoc);
3151 SpecTL.setRAngleLoc(RAngleLoc);
3152 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3153 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00003154
Abramo Bagnara4244b432012-01-27 08:46:19 +00003155 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3156 // constructor or destructor name (in such a case, the scope specifier
3157 // will be attached to the enclosing Decl or Expr node).
3158 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003159 // Create an elaborated-type-specifier containing the nested-name-specifier.
3160 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3161 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003162 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00003163 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3164 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003165
Douglas Gregore7c20652011-03-02 00:47:37 +00003166 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00003167}
John McCall06f6fe8d2009-09-04 01:14:41 +00003168
Douglas Gregore7c20652011-03-02 00:47:37 +00003169TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00003170 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00003171 SourceLocation TagLoc,
3172 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003173 SourceLocation TemplateKWLoc,
3174 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00003175 SourceLocation TemplateLoc,
3176 SourceLocation LAngleLoc,
3177 ASTTemplateArgsPtr TemplateArgsIn,
3178 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003179 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003180
Douglas Gregore7c20652011-03-02 00:47:37 +00003181 // Translate the parser's template argument list in our AST format.
3182 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3183 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003184
Douglas Gregore7c20652011-03-02 00:47:37 +00003185 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00003186 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00003187 ElaboratedTypeKeyword Keyword
3188 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00003189
Douglas Gregore7c20652011-03-02 00:47:37 +00003190 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3191 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00003192 DTN->getQualifier(),
3193 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00003194 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003195
3196 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00003197 TypeLocBuilder TLB;
3198 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003199 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3200 SpecTL.setElaboratedKeywordLoc(TagLoc);
3201 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003202 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003203 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003204 SpecTL.setLAngleLoc(LAngleLoc);
3205 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003206 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3207 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3208 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3209 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003210
3211 if (TypeAliasTemplateDecl *TAT =
3212 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3213 // C++0x [dcl.type.elab]p2:
3214 // If the identifier resolves to a typedef-name or the simple-template-id
3215 // resolves to an alias template specialization, the
3216 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003217 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3218 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003219 Diag(TAT->getLocation(), diag::note_declared_at);
3220 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003221
Douglas Gregore7c20652011-03-02 00:47:37 +00003222 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3223 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003224 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003225
Douglas Gregore7c20652011-03-02 00:47:37 +00003226 // Check the tag kind
3227 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003228 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003229
John McCalld8fe9af2009-09-08 17:47:29 +00003230 IdentifierInfo *Id = D->getIdentifier();
3231 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003232
Richard Trieucaa33d32011-06-10 03:11:26 +00003233 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003234 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003235 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003236 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003237 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003238 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003239 }
3240 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003241
Douglas Gregore7c20652011-03-02 00:47:37 +00003242 // Provide source-location information for the template specialization.
3243 TypeLocBuilder TLB;
3244 TemplateSpecializationTypeLoc SpecTL
3245 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003246 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003247 SpecTL.setTemplateNameLoc(TemplateLoc);
3248 SpecTL.setLAngleLoc(LAngleLoc);
3249 SpecTL.setRAngleLoc(RAngleLoc);
3250 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3251 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003252
Douglas Gregore7c20652011-03-02 00:47:37 +00003253 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003254 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003255 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3256 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003257 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003258 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3259 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003260}
3261
Larisse Voufo39a1e502013-08-06 01:03:05 +00003262static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3263 NamedDecl *PrevDecl,
3264 SourceLocation Loc,
3265 bool IsPartialSpecialization);
3266
3267static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003268
Richard Smith300e0c32013-09-24 04:49:23 +00003269static bool isTemplateArgumentTemplateParameter(
3270 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3271 switch (Arg.getKind()) {
3272 case TemplateArgument::Null:
3273 case TemplateArgument::NullPtr:
3274 case TemplateArgument::Integral:
3275 case TemplateArgument::Declaration:
3276 case TemplateArgument::Pack:
3277 case TemplateArgument::TemplateExpansion:
3278 return false;
3279
3280 case TemplateArgument::Type: {
3281 QualType Type = Arg.getAsType();
3282 const TemplateTypeParmType *TPT =
3283 Arg.getAsType()->getAs<TemplateTypeParmType>();
3284 return TPT && !Type.hasQualifiers() &&
3285 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3286 }
3287
3288 case TemplateArgument::Expression: {
3289 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3290 if (!DRE || !DRE->getDecl())
3291 return false;
3292 const NonTypeTemplateParmDecl *NTTP =
3293 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3294 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3295 }
3296
3297 case TemplateArgument::Template:
3298 const TemplateTemplateParmDecl *TTP =
3299 dyn_cast_or_null<TemplateTemplateParmDecl>(
3300 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3301 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3302 }
3303 llvm_unreachable("unexpected kind of template argument");
3304}
3305
3306static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3307 ArrayRef<TemplateArgument> Args) {
3308 if (Params->size() != Args.size())
3309 return false;
3310
3311 unsigned Depth = Params->getDepth();
3312
3313 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3314 TemplateArgument Arg = Args[I];
3315
3316 // If the parameter is a pack expansion, the argument must be a pack
3317 // whose only element is a pack expansion.
3318 if (Params->getParam(I)->isParameterPack()) {
3319 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3320 !Arg.pack_begin()->isPackExpansion())
3321 return false;
3322 Arg = Arg.pack_begin()->getPackExpansionPattern();
3323 }
3324
3325 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3326 return false;
3327 }
3328
3329 return true;
3330}
3331
Richard Smith4b55a9c2014-04-17 03:29:33 +00003332/// Convert the parser's template argument list representation into our form.
3333static TemplateArgumentListInfo
3334makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3335 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3336 TemplateId.RAngleLoc);
3337 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3338 TemplateId.NumArgs);
3339 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3340 return TemplateArgs;
3341}
3342
Richard Smith0e617ec2016-12-27 07:56:27 +00003343template<typename PartialSpecDecl>
3344static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3345 if (Partial->getDeclContext()->isDependentContext())
3346 return;
3347
3348 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3349 // for non-substitution-failure issues?
3350 TemplateDeductionInfo Info(Partial->getLocation());
3351 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3352 return;
3353
3354 auto *Template = Partial->getSpecializedTemplate();
3355 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003356 diag::ext_partial_spec_not_more_specialized_than_primary)
3357 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003358
3359 if (Info.hasSFINAEDiagnostic()) {
3360 PartialDiagnosticAt Diag = {SourceLocation(),
3361 PartialDiagnostic::NullDiagnostic()};
3362 Info.takeSFINAEDiagnostic(Diag);
3363 SmallString<128> SFINAEArgString;
3364 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3365 S.Diag(Diag.first,
3366 diag::note_partial_spec_not_more_specialized_than_primary)
3367 << SFINAEArgString;
3368 }
3369
3370 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3371}
3372
Richard Smith4e05eaa2017-02-16 00:36:47 +00003373static void
3374noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3375 const llvm::SmallBitVector &DeducibleParams) {
3376 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3377 if (!DeducibleParams[I]) {
3378 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3379 if (Param->getDeclName())
3380 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3381 << Param->getDeclName();
3382 else
3383 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3384 << "(anonymous)";
3385 }
3386 }
3387}
3388
3389
Richard Smith57aae072016-12-28 02:37:25 +00003390template<typename PartialSpecDecl>
3391static void checkTemplatePartialSpecialization(Sema &S,
3392 PartialSpecDecl *Partial) {
3393 // C++1z [temp.class.spec]p8: (DR1495)
3394 // - The specialization shall be more specialized than the primary
3395 // template (14.5.5.2).
3396 checkMoreSpecializedThanPrimary(S, Partial);
3397
3398 // C++ [temp.class.spec]p8: (DR1315)
3399 // - Each template-parameter shall appear at least once in the
3400 // template-id outside a non-deduced context.
3401 // C++1z [temp.class.spec.match]p3 (P0127R2)
3402 // If the template arguments of a partial specialization cannot be
3403 // deduced because of the structure of its template-parameter-list
3404 // and the template-id, the program is ill-formed.
3405 auto *TemplateParams = Partial->getTemplateParameters();
3406 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3407 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3408 TemplateParams->getDepth(), DeducibleParams);
3409
3410 if (!DeducibleParams.all()) {
3411 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3412 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3413 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3414 << (NumNonDeducible > 1)
3415 << SourceRange(Partial->getLocation(),
3416 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003417 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003418 }
3419}
3420
3421void Sema::CheckTemplatePartialSpecialization(
3422 ClassTemplatePartialSpecializationDecl *Partial) {
3423 checkTemplatePartialSpecialization(*this, Partial);
3424}
3425
3426void Sema::CheckTemplatePartialSpecialization(
3427 VarTemplatePartialSpecializationDecl *Partial) {
3428 checkTemplatePartialSpecialization(*this, Partial);
3429}
3430
Richard Smith4e05eaa2017-02-16 00:36:47 +00003431void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3432 // C++1z [temp.param]p11:
3433 // A template parameter of a deduction guide template that does not have a
3434 // default-argument shall be deducible from the parameter-type-list of the
3435 // deduction guide template.
3436 auto *TemplateParams = TD->getTemplateParameters();
3437 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3438 MarkDeducedTemplateParameters(TD, DeducibleParams);
3439 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3440 // A parameter pack is deducible (to an empty pack).
3441 auto *Param = TemplateParams->getParam(I);
3442 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3443 DeducibleParams[I] = true;
3444 }
3445
3446 if (!DeducibleParams.all()) {
3447 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3448 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3449 << (NumNonDeducible > 1);
3450 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3451 }
3452}
3453
Larisse Voufo39a1e502013-08-06 01:03:05 +00003454DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003455 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003456 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003457 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003458 // D must be variable template id.
3459 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
3460 "Variable template specialization is declared with a template it.");
3461
3462 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003463 TemplateArgumentListInfo TemplateArgs =
3464 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003465 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3466 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3467 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003468
Richard Smithbeef3452014-01-16 23:39:20 +00003469 TemplateName Name = TemplateId->Template.get();
3470
3471 // The template-id must name a variable template.
3472 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003473 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3474 if (!VarTemplate) {
3475 NamedDecl *FnTemplate;
3476 if (auto *OTS = Name.getAsOverloadedTemplate())
3477 FnTemplate = *OTS->begin();
3478 else
3479 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3480 if (FnTemplate)
3481 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3482 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003483 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3484 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003485 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003486
3487 // Check for unexpanded parameter packs in any of the template arguments.
3488 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3489 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3490 UPPC_PartialSpecialization))
3491 return true;
3492
3493 // Check that the template argument list is well-formed for this
3494 // template.
3495 SmallVector<TemplateArgument, 4> Converted;
3496 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3497 false, Converted))
3498 return true;
3499
Larisse Voufo39a1e502013-08-06 01:03:05 +00003500 // Find the variable template (partial) specialization declaration that
3501 // corresponds to these arguments.
3502 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003503 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3504 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003505 return true;
3506
Richard Smith57aae072016-12-28 02:37:25 +00003507 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3508 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003509 bool InstantiationDependent;
3510 if (!Name.isDependent() &&
3511 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003512 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003513 InstantiationDependent)) {
3514 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3515 << VarTemplate->getDeclName();
3516 IsPartialSpecialization = false;
3517 }
Richard Smith300e0c32013-09-24 04:49:23 +00003518
3519 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3520 Converted)) {
3521 // C++ [temp.class.spec]p9b3:
3522 //
3523 // -- The argument list of the specialization shall not be identical
3524 // to the implicit argument list of the primary template.
3525 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3526 << /*variable template*/ 1
3527 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3528 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3529 // FIXME: Recover from this by treating the declaration as a redeclaration
3530 // of the primary template.
3531 return true;
3532 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003533 }
3534
Craig Topperc3ec1492014-05-26 06:22:03 +00003535 void *InsertPos = nullptr;
3536 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003537
3538 if (IsPartialSpecialization)
3539 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003540 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003541 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003542 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003543
Craig Topperc3ec1492014-05-26 06:22:03 +00003544 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003545
3546 // Check whether we can declare a variable template specialization in
3547 // the current scope.
3548 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3549 TemplateNameLoc,
3550 IsPartialSpecialization))
3551 return true;
3552
3553 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3554 // Since the only prior variable template specialization with these
3555 // arguments was referenced but not declared, reuse that
3556 // declaration node as our own, updating its source location and
3557 // the list of outer template parameters to reflect our new declaration.
3558 Specialization = PrevDecl;
3559 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003560 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003561 } else if (IsPartialSpecialization) {
3562 // Create a new class template partial specialization declaration node.
3563 VarTemplatePartialSpecializationDecl *PrevPartial =
3564 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003565 VarTemplatePartialSpecializationDecl *Partial =
3566 VarTemplatePartialSpecializationDecl::Create(
3567 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3568 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003569 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003570
3571 if (!PrevPartial)
3572 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3573 Specialization = Partial;
3574
3575 // If we are providing an explicit specialization of a member variable
3576 // template specialization, make a note of that.
3577 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003578 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003579
Richard Smith57aae072016-12-28 02:37:25 +00003580 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003581 } else {
3582 // Create a new class template specialization declaration node for
3583 // this explicit specialization or friend declaration.
3584 Specialization = VarTemplateSpecializationDecl::Create(
3585 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003586 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003587 Specialization->setTemplateArgsInfo(TemplateArgs);
3588
3589 if (!PrevDecl)
3590 VarTemplate->AddSpecialization(Specialization, InsertPos);
3591 }
3592
3593 // C++ [temp.expl.spec]p6:
3594 // If a template, a member template or the member of a class template is
3595 // explicitly specialized then that specialization shall be declared
3596 // before the first use of that specialization that would cause an implicit
3597 // instantiation to take place, in every translation unit in which such a
3598 // use occurs; no diagnostic is required.
3599 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3600 bool Okay = false;
3601 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3602 // Is there any previous explicit specialization declaration?
3603 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3604 Okay = true;
3605 break;
3606 }
3607 }
3608
3609 if (!Okay) {
3610 SourceRange Range(TemplateNameLoc, RAngleLoc);
3611 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3612 << Name << Range;
3613
3614 Diag(PrevDecl->getPointOfInstantiation(),
3615 diag::note_instantiation_required_here)
3616 << (PrevDecl->getTemplateSpecializationKind() !=
3617 TSK_ImplicitInstantiation);
3618 return true;
3619 }
3620 }
3621
3622 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3623 Specialization->setLexicalDeclContext(CurContext);
3624
3625 // Add the specialization into its lexical context, so that it can
3626 // be seen when iterating through the list of declarations in that
3627 // context. However, specializations are not found by name lookup.
3628 CurContext->addDecl(Specialization);
3629
3630 // Note that this is an explicit specialization.
3631 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3632
3633 if (PrevDecl) {
3634 // Check that this isn't a redefinition of this specialization,
3635 // merging with previous declarations.
3636 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3637 ForRedeclaration);
3638 PrevSpec.addDecl(PrevDecl);
3639 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003640 } else if (Specialization->isStaticDataMember() &&
3641 Specialization->isOutOfLine()) {
3642 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003643 }
3644
3645 // Link instantiations of static data members back to the template from
3646 // which they were instantiated.
3647 if (Specialization->isStaticDataMember())
3648 Specialization->setInstantiationOfStaticDataMember(
3649 VarTemplate->getTemplatedDecl(),
3650 Specialization->getSpecializationKind());
3651
3652 return Specialization;
3653}
3654
3655namespace {
3656/// \brief A partial specialization whose template arguments have matched
3657/// a given template-id.
3658struct PartialSpecMatchResult {
3659 VarTemplatePartialSpecializationDecl *Partial;
3660 TemplateArgumentList *Args;
3661};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003662} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003663
3664DeclResult
3665Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3666 SourceLocation TemplateNameLoc,
3667 const TemplateArgumentListInfo &TemplateArgs) {
3668 assert(Template && "A variable template id without template?");
3669
3670 // Check that the template argument list is well-formed for this template.
3671 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003672 if (CheckTemplateArgumentList(
3673 Template, TemplateNameLoc,
3674 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003675 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003676 return true;
3677
3678 // Find the variable template specialization declaration that
3679 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003680 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003681 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003682 Converted, InsertPos)) {
3683 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003684 // If we already have a variable template specialization, return it.
3685 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003686 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003687
3688 // This is the first time we have referenced this variable template
3689 // specialization. Create the canonical declaration and add it to
3690 // the set of specializations, based on the closest partial specialization
3691 // that it represents. That is,
3692 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3693 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003694 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003695 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3696 bool AmbiguousPartialSpec = false;
3697 typedef PartialSpecMatchResult MatchResult;
3698 SmallVector<MatchResult, 4> Matched;
3699 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003700 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3701 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003702
3703 // 1. Attempt to find the closest partial specialization that this
3704 // specializes, if any.
3705 // If any of the template arguments is dependent, then this is probably
3706 // a placeholder for an incomplete declarative context; which must be
3707 // complete by instantiation time. Thus, do not search through the partial
3708 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003709 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3710 // Perhaps better after unification of DeduceTemplateArguments() and
3711 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003712 bool InstantiationDependent = false;
3713 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3714 TemplateArgs, InstantiationDependent)) {
3715
3716 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3717 Template->getPartialSpecializations(PartialSpecs);
3718
3719 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3720 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3721 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3722
3723 if (TemplateDeductionResult Result =
3724 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3725 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003726 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003727 FailedCandidates.addCandidate().set(
3728 DeclAccessPair::make(Template, AS_public), Partial,
3729 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003730 (void)Result;
3731 } else {
3732 Matched.push_back(PartialSpecMatchResult());
3733 Matched.back().Partial = Partial;
3734 Matched.back().Args = Info.take();
3735 }
3736 }
3737
Larisse Voufo39a1e502013-08-06 01:03:05 +00003738 if (Matched.size() >= 1) {
3739 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3740 if (Matched.size() == 1) {
3741 // -- If exactly one matching specialization is found, the
3742 // instantiation is generated from that specialization.
3743 // We don't need to do anything for this.
3744 } else {
3745 // -- If more than one matching specialization is found, the
3746 // partial order rules (14.5.4.2) are used to determine
3747 // whether one of the specializations is more specialized
3748 // than the others. If none of the specializations is more
3749 // specialized than all of the other matching
3750 // specializations, then the use of the variable template is
3751 // ambiguous and the program is ill-formed.
3752 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3753 PEnd = Matched.end();
3754 P != PEnd; ++P) {
3755 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3756 PointOfInstantiation) ==
3757 P->Partial)
3758 Best = P;
3759 }
3760
3761 // Determine if the best partial specialization is more specialized than
3762 // the others.
3763 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3764 PEnd = Matched.end();
3765 P != PEnd; ++P) {
3766 if (P != Best && getMoreSpecializedPartialSpecialization(
3767 P->Partial, Best->Partial,
3768 PointOfInstantiation) != Best->Partial) {
3769 AmbiguousPartialSpec = true;
3770 break;
3771 }
3772 }
3773 }
3774
3775 // Instantiate using the best variable template partial specialization.
3776 InstantiationPattern = Best->Partial;
3777 InstantiationArgs = Best->Args;
3778 } else {
3779 // -- If no match is found, the instantiation is generated
3780 // from the primary template.
3781 // InstantiationPattern = Template->getTemplatedDecl();
3782 }
3783 }
3784
Larisse Voufo39a1e502013-08-06 01:03:05 +00003785 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00003786 // Note that we do not instantiate a definition until we see an odr-use
3787 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003788 // FIXME: LateAttrs et al.?
3789 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3790 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3791 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3792 if (!Decl)
3793 return true;
3794
3795 if (AmbiguousPartialSpec) {
3796 // Partial ordering did not produce a clear winner. Complain.
3797 Decl->setInvalidDecl();
3798 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3799 << Decl;
3800
3801 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00003802 for (MatchResult P : Matched)
3803 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3804 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3805 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003806 return true;
3807 }
3808
3809 if (VarTemplatePartialSpecializationDecl *D =
3810 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3811 Decl->setInstantiationOf(D, InstantiationArgs);
3812
Richard Smith6739a102016-05-05 00:56:12 +00003813 checkSpecializationVisibility(TemplateNameLoc, Decl);
3814
Larisse Voufo39a1e502013-08-06 01:03:05 +00003815 assert(Decl && "No variable template specialization?");
3816 return Decl;
3817}
3818
3819ExprResult
3820Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3821 const DeclarationNameInfo &NameInfo,
3822 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3823 const TemplateArgumentListInfo *TemplateArgs) {
3824
3825 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3826 *TemplateArgs);
3827 if (Decl.isInvalid())
3828 return ExprError();
3829
3830 VarDecl *Var = cast<VarDecl>(Decl.get());
3831 if (!Var->getTemplateSpecializationKind())
3832 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3833 NameInfo.getLoc());
3834
3835 // Build an ordinary singleton decl ref.
3836 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003837 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003838}
3839
John McCalldadc5752010-08-24 06:29:42 +00003840ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003841 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003842 LookupResult &R,
3843 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003844 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003845 // FIXME: Can we do any checking at this point? I guess we could check the
3846 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003847 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003848 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003849 // foo<int> could identify a single function unambiguously
3850 // This approach does NOT work, since f<int>(1);
3851 // gets resolved prior to resorting to overload resolution
3852 // i.e., template<class T> void f(double);
3853 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003854
3855 // These should be filtered out by our callers.
3856 assert(!R.empty() && "empty lookup results when building templateid");
3857 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3858
Larisse Voufo39a1e502013-08-06 01:03:05 +00003859 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003860 bool InstantiationDependent;
3861 if (R.getAsSingle<VarTemplateDecl>() &&
3862 !TemplateSpecializationType::anyDependentTemplateArguments(
3863 *TemplateArgs, InstantiationDependent)) {
3864 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3865 R.getAsSingle<VarTemplateDecl>(),
3866 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003867 }
3868
John McCall58cc69d2010-01-27 01:50:18 +00003869 // We don't want lookup warnings at this point.
3870 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003871
John McCalle66edc12009-11-24 19:00:30 +00003872 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003873 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003874 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003875 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003876 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003877 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003878 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003879
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003880 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003881}
3882
John McCalle66edc12009-11-24 19:00:30 +00003883// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003884ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003885Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003886 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003887 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003888 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003889
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003890 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003891 DeclContext *DC;
3892 if (!(DC = computeDeclContext(SS, false)) ||
3893 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003894 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003895 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003896
Douglas Gregor786123d2010-05-21 23:18:07 +00003897 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003898 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003899 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003900 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003901
John McCalle66edc12009-11-24 19:00:30 +00003902 if (R.isAmbiguous())
3903 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003904
John McCalle66edc12009-11-24 19:00:30 +00003905 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003906 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3907 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003908 return ExprError();
3909 }
3910
3911 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003912 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003913 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003914 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003915 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3916 return ExprError();
3917 }
3918
Abramo Bagnara7945c982012-01-27 09:46:47 +00003919 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003920}
3921
Douglas Gregorb67535d2009-03-31 00:43:58 +00003922/// \brief Form a dependent template name.
3923///
3924/// This action forms a dependent template name given the template
3925/// name and its (presumably dependent) scope specifier. For
3926/// example, given "MetaFun::template apply", the scope specifier \p
3927/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3928/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003929TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003930 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003931 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003932 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003933 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003934 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00003935 TemplateTy &Result,
3936 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003937 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3938 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003939 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003940 diag::warn_cxx98_compat_template_outside_of_template :
3941 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003942 << FixItHint::CreateRemoval(TemplateKWLoc);
3943
Craig Topperc3ec1492014-05-26 06:22:03 +00003944 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003945 if (SS.isSet())
3946 LookupCtx = computeDeclContext(SS, EnteringContext);
3947 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003948 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003949 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003950 // C++0x [temp.names]p5:
3951 // If a name prefixed by the keyword template is not the name of
3952 // a template, the program is ill-formed. [Note: the keyword
3953 // template may not be applied to non-template members of class
3954 // templates. -end note ] [ Note: as is the case with the
3955 // typename prefix, the template prefix is allowed in cases
3956 // where it is not strictly necessary; i.e., when the
3957 // nested-name-specifier or the expression on the left of the ->
3958 // or . is not dependent on a template-parameter, or the use
3959 // does not appear in the scope of a template. -end note]
3960 //
3961 // Note: C++03 was more strict here, because it banned the use of
3962 // the "template" keyword prior to a template-name that was not a
3963 // dependent name. C++ DR468 relaxed this requirement (the
3964 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003965 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003966 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003967 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003968 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003969 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003970 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3971 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003972 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3973 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003974 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003975 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003976 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003977 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003978 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003979 << Name.getSourceRange()
3980 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003981 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003982 } else {
3983 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00003984 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
3985 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
3986 Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
3987 LookupRD->getIdentifier() == Name.Identifier) {
3988 // C++14 [class.qual]p2:
3989 // In a lookup in which function names are not ignored and the
3990 // nested-name-specifier nominates a class C, if the name specified
3991 // [...] is the injected-class-name of C, [...] the name is instead
3992 // considered to name the constructor
3993 //
3994 // We don't get here if naming the constructor would be valid, so we
3995 // just reject immediately and recover by treating the
3996 // injected-class-name as naming the template.
3997 Diag(Name.getLocStart(),
3998 diag::ext_out_of_line_qualified_id_type_names_constructor)
3999 << Name.Identifier << 0 /*injected-class-name used as template name*/
4000 << 1 /*'template' keyword was used*/;
4001 }
Douglas Gregorbb119652010-06-16 23:00:59 +00004002 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004003 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00004004 }
4005
Aaron Ballman4a979672014-01-03 13:56:08 +00004006 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004007
Douglas Gregor3cf81312009-11-03 23:16:33 +00004008 switch (Name.getKind()) {
4009 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004010 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00004011 Name.Identifier));
4012 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004013
Douglas Gregor71395fa2009-11-04 00:56:37 +00004014 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00004015 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00004016 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00004017 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00004018
4019 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00004020 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00004021
Douglas Gregor3cf81312009-11-03 23:16:33 +00004022 default:
4023 break;
4024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004025
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004026 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00004027 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004028 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00004029 << Name.getSourceRange()
4030 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004031 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004032}
4033
Mike Stump11289f42009-09-09 15:08:12 +00004034bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004035 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004036 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00004037 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00004038 QualType ArgType;
4039 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00004040
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004041 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004042 switch(Arg.getKind()) {
4043 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004044 // C++ [temp.arg.type]p1:
4045 // A template-argument for a template-parameter which is a
4046 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00004047 ArgType = Arg.getAsType();
4048 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004049 break;
4050 case TemplateArgument::Template: {
4051 // We have a template type parameter but the template argument
4052 // is a template without any arguments.
4053 SourceRange SR = AL.getSourceRange();
4054 TemplateName Name = Arg.getAsTemplate();
4055 Diag(SR.getBegin(), diag::err_template_missing_args)
Richard Smith0c062b42017-01-14 02:19:59 +00004056 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004057 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
4058 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004059
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004060 return true;
4061 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004062 case TemplateArgument::Expression: {
4063 // We have a template type parameter but the template argument is an
4064 // expression; see if maybe it is missing the "typename" keyword.
4065 CXXScopeSpec SS;
4066 DeclarationNameInfo NameInfo;
4067
4068 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4069 SS.Adopt(ArgExpr->getQualifierLoc());
4070 NameInfo = ArgExpr->getNameInfo();
4071 } else if (DependentScopeDeclRefExpr *ArgExpr =
4072 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4073 SS.Adopt(ArgExpr->getQualifierLoc());
4074 NameInfo = ArgExpr->getNameInfo();
4075 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4076 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004077 if (ArgExpr->isImplicitAccess()) {
4078 SS.Adopt(ArgExpr->getQualifierLoc());
4079 NameInfo = ArgExpr->getMemberNameInfo();
4080 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004081 }
4082
Reid Kleckner377c1592014-06-10 23:29:48 +00004083 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004084 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4085 LookupParsedName(Result, CurScope, &SS);
4086
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004087 if (Result.getAsSingle<TypeDecl>() ||
4088 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00004089 LookupResult::NotFoundInCurrentInstantiation) {
4090 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004091 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00004092 Diag(Loc, getLangOpts().MSVCCompat
4093 ? diag::ext_ms_template_type_arg_missing_typename
4094 : diag::err_template_arg_must_be_type_suggest)
4095 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004096 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00004097
4098 // Recover by synthesizing a type using the location information that we
4099 // already have.
4100 ArgType =
4101 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4102 TypeLocBuilder TLB;
4103 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4104 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4105 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4106 TL.setNameLoc(NameInfo.getLoc());
4107 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4108
4109 // Overwrite our input TemplateArgumentLoc so that we can recover
4110 // properly.
4111 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4112 TemplateArgumentLocInfo(TSI));
4113
4114 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004115 }
4116 }
4117 // fallthrough
Galina Kistanova3779cb32017-06-07 06:25:05 +00004118 LLVM_FALLTHROUGH;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004119 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004120 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004121 // We have a template type parameter but the template argument
4122 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00004123 SourceRange SR = AL.getSourceRange();
4124 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004125 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00004126
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004127 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004128 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004129 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004130
Reid Kleckner377c1592014-06-10 23:29:48 +00004131 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004132 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004133
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004134 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00004135 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004136
Douglas Gregore46db902011-06-17 22:11:49 +00004137 // Objective-C ARC:
4138 // If an explicitly-specified template argument type is a lifetime type
4139 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004140 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00004141 ArgType->isObjCLifetimeType() &&
4142 !ArgType.getObjCLifetime()) {
4143 Qualifiers Qs;
4144 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4145 ArgType = Context.getQualifiedType(ArgType, Qs);
4146 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004147
Douglas Gregore46db902011-06-17 22:11:49 +00004148 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004149 return false;
4150}
4151
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004152/// \brief Substitute template arguments into the default template argument for
4153/// the given template type parameter.
4154///
4155/// \param SemaRef the semantic analysis object for which we are performing
4156/// the substitution.
4157///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004158/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004159/// for.
4160///
4161/// \param TemplateLoc the location of the template name that started the
4162/// template-id we are checking.
4163///
4164/// \param RAngleLoc the location of the right angle bracket ('>') that
4165/// terminates the template-id.
4166///
4167/// \param Param the template template parameter whose default we are
4168/// substituting into.
4169///
4170/// \param Converted the list of template arguments provided for template
4171/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004172/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00004173static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004174SubstDefaultTemplateArgument(Sema &SemaRef,
4175 TemplateDecl *Template,
4176 SourceLocation TemplateLoc,
4177 SourceLocation RAngleLoc,
4178 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00004179 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00004180 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004181
4182 // If the argument type is dependent, instantiate it now based
4183 // on the previously-computed template arguments.
4184 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004185 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004186 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004187 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004188 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004189 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004190
David Majnemer8b622692016-07-03 21:17:51 +00004191 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004192
4193 // Only substitute for the innermost template argument list.
4194 MultiLevelTemplateArgumentList TemplateArgLists;
4195 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4196 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4197 TemplateArgLists.addOuterTemplateArguments(None);
4198
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004199 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004200 ArgType =
4201 SemaRef.SubstType(ArgType, TemplateArgLists,
4202 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004203 }
4204
4205 return ArgType;
4206}
4207
4208/// \brief Substitute template arguments into the default template argument for
4209/// the given non-type template parameter.
4210///
4211/// \param SemaRef the semantic analysis object for which we are performing
4212/// the substitution.
4213///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004214/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004215/// for.
4216///
4217/// \param TemplateLoc the location of the template name that started the
4218/// template-id we are checking.
4219///
4220/// \param RAngleLoc the location of the right angle bracket ('>') that
4221/// terminates the template-id.
4222///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004223/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004224/// substituting into.
4225///
4226/// \param Converted the list of template arguments provided for template
4227/// parameters that precede \p Param in the template parameter list.
4228///
4229/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004230static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004231SubstDefaultTemplateArgument(Sema &SemaRef,
4232 TemplateDecl *Template,
4233 SourceLocation TemplateLoc,
4234 SourceLocation RAngleLoc,
4235 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004236 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004237 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004238 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004239 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004240 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004241 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004242
David Majnemer8b622692016-07-03 21:17:51 +00004243 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004244
4245 // Only substitute for the innermost template argument list.
4246 MultiLevelTemplateArgumentList TemplateArgLists;
4247 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4248 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4249 TemplateArgLists.addOuterTemplateArguments(None);
4250
Faisal Valid143a0c2017-04-01 21:30:49 +00004251 EnterExpressionEvaluationContext ConstantEvaluated(
4252 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004253 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004254}
4255
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004256/// \brief Substitute template arguments into the default template argument for
4257/// the given template template parameter.
4258///
4259/// \param SemaRef the semantic analysis object for which we are performing
4260/// the substitution.
4261///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004263/// for.
4264///
4265/// \param TemplateLoc the location of the template name that started the
4266/// template-id we are checking.
4267///
4268/// \param RAngleLoc the location of the right angle bracket ('>') that
4269/// terminates the template-id.
4270///
4271/// \param Param the template template parameter whose default we are
4272/// substituting into.
4273///
4274/// \param Converted the list of template arguments provided for template
4275/// parameters that precede \p Param in the template parameter list.
4276///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004277/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004278/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004279///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004280/// \returns the substituted template argument, or NULL if an error occurred.
4281static TemplateName
4282SubstDefaultTemplateArgument(Sema &SemaRef,
4283 TemplateDecl *Template,
4284 SourceLocation TemplateLoc,
4285 SourceLocation RAngleLoc,
4286 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004287 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004288 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004289 Sema::InstantiatingTemplate Inst(
4290 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4291 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004292 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004293 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294
David Majnemer8b622692016-07-03 21:17:51 +00004295 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004296
4297 // Only substitute for the innermost template argument list.
4298 MultiLevelTemplateArgumentList TemplateArgLists;
4299 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4300 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4301 TemplateArgLists.addOuterTemplateArguments(None);
4302
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004303 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004304 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004305 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004306 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004307 QualifierLoc =
4308 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004309 if (!QualifierLoc)
4310 return TemplateName();
4311 }
David Majnemer89189202013-08-28 23:48:32 +00004312
4313 return SemaRef.SubstTemplateName(
4314 QualifierLoc,
4315 Param->getDefaultArgument().getArgument().getAsTemplate(),
4316 Param->getDefaultArgument().getTemplateNameLoc(),
4317 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004318}
4319
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004320/// \brief If the given template parameter has a default template
4321/// argument, substitute into that default template argument and
4322/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004324Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4325 SourceLocation TemplateLoc,
4326 SourceLocation RAngleLoc,
4327 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004328 SmallVectorImpl<TemplateArgument>
4329 &Converted,
4330 bool &HasDefaultArg) {
4331 HasDefaultArg = false;
4332
4333 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004334 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004335 return TemplateArgumentLoc();
4336
Richard Smithc87b9382013-07-04 01:01:24 +00004337 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004338 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004339 TemplateLoc,
4340 RAngleLoc,
4341 TypeParm,
4342 Converted);
4343 if (DI)
4344 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4345
4346 return TemplateArgumentLoc();
4347 }
4348
4349 if (NonTypeTemplateParmDecl *NonTypeParm
4350 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004351 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004352 return TemplateArgumentLoc();
4353
Richard Smithc87b9382013-07-04 01:01:24 +00004354 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004355 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004356 TemplateLoc,
4357 RAngleLoc,
4358 NonTypeParm,
4359 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004360 if (Arg.isInvalid())
4361 return TemplateArgumentLoc();
4362
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004363 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004364 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4365 }
4366
4367 TemplateTemplateParmDecl *TempTempParm
4368 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004369 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004370 return TemplateArgumentLoc();
4371
Richard Smithc87b9382013-07-04 01:01:24 +00004372 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004373 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004374 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004376 RAngleLoc,
4377 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004378 Converted,
4379 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004380 if (TName.isNull())
4381 return TemplateArgumentLoc();
4382
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004384 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004385 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4386}
4387
Richard Smith11255ec2017-01-18 19:19:22 +00004388/// Convert a template-argument that we parsed as a type into a template, if
4389/// possible. C++ permits injected-class-names to perform dual service as
4390/// template template arguments and as template type arguments.
4391static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4392 // Extract and step over any surrounding nested-name-specifier.
4393 NestedNameSpecifierLoc QualLoc;
4394 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4395 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4396 return TemplateArgumentLoc();
4397
4398 QualLoc = ETLoc.getQualifierLoc();
4399 TLoc = ETLoc.getNamedTypeLoc();
4400 }
4401
4402 // If this type was written as an injected-class-name, it can be used as a
4403 // template template argument.
4404 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4405 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4406 QualLoc, InjLoc.getNameLoc());
4407
4408 // If this type was written as an injected-class-name, it may have been
4409 // converted to a RecordType during instantiation. If the RecordType is
4410 // *not* wrapped in a TemplateSpecializationType and denotes a class
4411 // template specialization, it must have come from an injected-class-name.
4412 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4413 if (auto *CTSD =
4414 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4415 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4416 QualLoc, RecLoc.getNameLoc());
4417
4418 return TemplateArgumentLoc();
4419}
4420
Douglas Gregorda0fb532009-11-11 19:31:23 +00004421/// \brief Check that the given template argument corresponds to the given
4422/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004423///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004424/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004425/// checked.
4426///
Richard Trieu15b66532015-01-24 02:48:32 +00004427/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004428///
4429/// \param Template The template in which the template argument resides.
4430///
4431/// \param TemplateLoc The location of the template name for the template
4432/// whose argument list we're matching.
4433///
4434/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4435/// the template argument list.
4436///
4437/// \param ArgumentPackIndex The index into the argument pack where this
4438/// argument will be placed. Only valid if the parameter is a parameter pack.
4439///
4440/// \param Converted The checked, converted argument will be added to the
4441/// end of this small vector.
4442///
4443/// \param CTAK Describes how we arrived at this particular template argument:
4444/// explicitly written, deduced, etc.
4445///
4446/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004447bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004448 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004449 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004450 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004451 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004452 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004453 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004454 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004455 // Check template type parameters.
4456 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004457 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004458
Douglas Gregoreebed722009-11-11 19:41:09 +00004459 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004461 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004462 // with the template arguments we've seen thus far. But if the
4463 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004464 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004465 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4466 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467
Peter Collingbourne01687632010-12-10 17:08:53 +00004468 if (NTTPType->isDependentType() &&
4469 !isa<TemplateTemplateParmDecl>(Template) &&
4470 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004471 // Do substitution on the type of the non-type template parameter.
4472 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004473 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004474 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004475 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004476 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004477
4478 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004479 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004480 NTTPType = SubstType(NTTPType,
4481 MultiLevelTemplateArgumentList(TemplateArgs),
4482 NTTP->getLocation(),
4483 NTTP->getDeclName());
4484 // If that worked, check the non-type template parameter type
4485 // for validity.
4486 if (!NTTPType.isNull())
4487 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4488 NTTP->getLocation());
4489 if (NTTPType.isNull())
4490 return true;
4491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004492
Douglas Gregorda0fb532009-11-11 19:31:23 +00004493 switch (Arg.getArgument().getKind()) {
4494 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004495 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004496
Douglas Gregorda0fb532009-11-11 19:31:23 +00004497 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004498 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00004499 ExprResult Res =
4500 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4501 Result, CTAK);
4502 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004503 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004504
Richard Trieu15b66532015-01-24 02:48:32 +00004505 // If the resulting expression is new, then use it in place of the
4506 // old expression in the template argument.
4507 if (Res.get() != Arg.getArgument().getAsExpr()) {
4508 TemplateArgument TA(Res.get());
4509 Arg = TemplateArgumentLoc(TA, Res.get());
4510 }
4511
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004512 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004513 break;
4514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004515
Douglas Gregorda0fb532009-11-11 19:31:23 +00004516 case TemplateArgument::Declaration:
4517 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004518 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004519 // We've already checked this template argument, so just copy
4520 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004521 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004522 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004523
Douglas Gregorda0fb532009-11-11 19:31:23 +00004524 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004525 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004526 // We were given a template template argument. It may not be ill-formed;
4527 // see below.
4528 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004529 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4530 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004531 // We have a template argument such as \c T::template X, which we
4532 // parsed as a template template argument. However, since we now
4533 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004534 // template name into an expression.
4535
4536 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4537 Arg.getTemplateNameLoc());
4538
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004539 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004540 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004541 // FIXME: the template-template arg was a DependentTemplateName,
4542 // so it was provided with a template keyword. However, its source
4543 // location is not stored in the template argument structure.
4544 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004545 ExprResult E = DependentScopeDeclRefExpr::Create(
4546 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4547 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004548
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004549 // If we parsed the template argument as a pack expansion, create a
4550 // pack expansion expression.
4551 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004552 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004553 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004554 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004556
Douglas Gregorda0fb532009-11-11 19:31:23 +00004557 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004558 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004559 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004560 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004562 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004563 break;
4564 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004565
Douglas Gregorda0fb532009-11-11 19:31:23 +00004566 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004567 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004568 // therefore cannot be a non-type template argument.
4569 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4570 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004571
Douglas Gregorda0fb532009-11-11 19:31:23 +00004572 Diag(Param->getLocation(), diag::note_template_param_here);
4573 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574
Douglas Gregorda0fb532009-11-11 19:31:23 +00004575 case TemplateArgument::Type: {
4576 // We have a non-type template parameter but the template
4577 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578
Douglas Gregorda0fb532009-11-11 19:31:23 +00004579 // C++ [temp.arg]p2:
4580 // In a template-argument, an ambiguity between a type-id and
4581 // an expression is resolved to a type-id, regardless of the
4582 // form of the corresponding template-parameter.
4583 //
4584 // We warn specifically about this case, since it can be rather
4585 // confusing for users.
4586 QualType T = Arg.getArgument().getAsType();
4587 SourceRange SR = Arg.getSourceRange();
4588 if (T->isFunctionType())
4589 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4590 else
4591 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4592 Diag(Param->getLocation(), diag::note_template_param_here);
4593 return true;
4594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004595
Douglas Gregorda0fb532009-11-11 19:31:23 +00004596 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004597 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004599
Douglas Gregorda0fb532009-11-11 19:31:23 +00004600 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004601 }
4602
4603
Douglas Gregorda0fb532009-11-11 19:31:23 +00004604 // Check template template parameters.
4605 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004606
Douglas Gregorda0fb532009-11-11 19:31:23 +00004607 // Substitute into the template parameter list of the template
4608 // template parameter, since previously-supplied template arguments
4609 // may appear within the template template parameter.
4610 {
4611 // Set up a template instantiation context.
4612 LocalInstantiationScope Scope(*this);
4613 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004614 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004615 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004616 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004617 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004618
David Majnemer8b622692016-07-03 21:17:51 +00004619 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004620 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004622 MultiLevelTemplateArgumentList(TemplateArgs)));
4623 if (!TempParm)
4624 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004626
Richard Smith11255ec2017-01-18 19:19:22 +00004627 // C++1z [temp.local]p1: (DR1004)
4628 // When [the injected-class-name] is used [...] as a template-argument for
4629 // a template template-parameter [...] it refers to the class template
4630 // itself.
4631 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4632 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4633 Arg.getTypeSourceInfo()->getTypeLoc());
4634 if (!ConvertedArg.getArgument().isNull())
4635 Arg = ConvertedArg;
4636 }
4637
Douglas Gregorda0fb532009-11-11 19:31:23 +00004638 switch (Arg.getArgument().getKind()) {
4639 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004640 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004641
Douglas Gregorda0fb532009-11-11 19:31:23 +00004642 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004643 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00004644 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004645 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004646
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004647 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004648 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004649
Douglas Gregorda0fb532009-11-11 19:31:23 +00004650 case TemplateArgument::Expression:
4651 case TemplateArgument::Type:
4652 // We have a template template parameter but the template
4653 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004654 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004655 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004656 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004657
Douglas Gregorda0fb532009-11-11 19:31:23 +00004658 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004659 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004660 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004661 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004662 case TemplateArgument::NullPtr:
4663 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004664
Douglas Gregorda0fb532009-11-11 19:31:23 +00004665 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004666 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004667 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668
Douglas Gregorda0fb532009-11-11 19:31:23 +00004669 return false;
4670}
4671
Simon Pilgrim6905d222016-12-30 22:55:33 +00004672/// \brief Diagnose an arity mismatch in the
Douglas Gregor8e072612012-02-03 07:34:46 +00004673static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4674 SourceLocation TemplateLoc,
4675 TemplateArgumentListInfo &TemplateArgs) {
4676 TemplateParameterList *Params = Template->getTemplateParameters();
4677 unsigned NumParams = Params->size();
4678 unsigned NumArgs = TemplateArgs.size();
4679
4680 SourceRange Range;
4681 if (NumArgs > NumParams)
Simon Pilgrim6905d222016-12-30 22:55:33 +00004682 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
Douglas Gregor8e072612012-02-03 07:34:46 +00004683 TemplateArgs.getRAngleLoc());
4684 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4685 << (NumArgs > NumParams)
Richard Smith0c062b42017-01-14 02:19:59 +00004686 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
Douglas Gregor8e072612012-02-03 07:34:46 +00004687 << Template << Range;
4688 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4689 << Params->getSourceRange();
4690 return true;
4691}
4692
Richard Smith1fde8ec2012-09-07 02:06:42 +00004693/// \brief Check whether the template parameter is a pack expansion, and if so,
4694/// determine the number of parameters produced by that expansion. For instance:
4695///
4696/// \code
4697/// template<typename ...Ts> struct A {
4698/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4699/// };
4700/// \endcode
4701///
4702/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4703/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004704static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004705 if (NonTypeTemplateParmDecl *NTTP
4706 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4707 if (NTTP->isExpandedParameterPack())
4708 return NTTP->getNumExpansionTypes();
4709 }
4710
4711 if (TemplateTemplateParmDecl *TTP
4712 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4713 if (TTP->isExpandedParameterPack())
4714 return TTP->getNumExpansionTemplateParameters();
4715 }
4716
David Blaikie7a30dc52013-02-21 01:47:18 +00004717 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00004718}
4719
Richard Smith35c1df52015-06-17 20:16:32 +00004720/// Diagnose a missing template argument.
4721template<typename TemplateParmDecl>
4722static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4723 TemplateDecl *TD,
4724 const TemplateParmDecl *D,
4725 TemplateArgumentListInfo &Args) {
4726 // Dig out the most recent declaration of the template parameter; there may be
4727 // declarations of the template that are more recent than TD.
4728 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4729 ->getTemplateParameters()
4730 ->getParam(D->getIndex()));
4731
4732 // If there's a default argument that's not visible, diagnose that we're
4733 // missing a module import.
4734 llvm::SmallVector<Module*, 8> Modules;
4735 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4736 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4737 D->getDefaultArgumentLoc(), Modules,
4738 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00004739 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00004740 return true;
4741 }
4742
4743 // FIXME: If there's a more recent default argument that *is* visible,
4744 // diagnose that it was declared too late.
4745
4746 return diagnoseArityMismatch(S, TD, Loc, Args);
4747}
4748
Douglas Gregord32e0282009-02-09 23:23:08 +00004749/// \brief Check that the given template argument list is well-formed
4750/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00004751bool Sema::CheckTemplateArgumentList(
4752 TemplateDecl *Template, SourceLocation TemplateLoc,
4753 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4754 SmallVectorImpl<TemplateArgument> &Converted,
4755 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00004756 // Make a copy of the template arguments for processing. Only make the
4757 // changes at the end when successful in matching the arguments to the
4758 // template.
4759 TemplateArgumentListInfo NewArgs = TemplateArgs;
4760
Douglas Gregord32e0282009-02-09 23:23:08 +00004761 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00004762
Richard Trieu15b66532015-01-24 02:48:32 +00004763 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00004764
Mike Stump11289f42009-09-09 15:08:12 +00004765 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00004766 // [...] The type and form of each template-argument specified in
4767 // a template-id shall match the type and form specified for the
4768 // corresponding parameter declared by the template in its
4769 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00004770 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004771 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00004772 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00004773 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00004774 for (TemplateParameterList::iterator Param = Params->begin(),
4775 ParamEnd = Params->end();
4776 Param != ParamEnd; /* increment in loop */) {
4777 // If we have an expanded parameter pack, make sure we don't have too
4778 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00004779 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004780 if (*Expansions == ArgumentPack.size()) {
4781 // We're done with this parameter pack. Pack up its arguments and add
4782 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00004783 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00004784 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004785 ArgumentPack.clear();
4786
Richard Smith1fde8ec2012-09-07 02:06:42 +00004787 // This argument is assigned to the next parameter.
4788 ++Param;
4789 continue;
4790 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4791 // Not enough arguments for this parameter pack.
4792 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4793 << false
Richard Smith0c062b42017-01-14 02:19:59 +00004794 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00004795 << Template;
4796 Diag(Template->getLocation(), diag::note_template_decl_here)
4797 << Params->getSourceRange();
4798 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004799 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004801
Richard Smith1fde8ec2012-09-07 02:06:42 +00004802 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00004803 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00004804 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004805 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004806 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00004807 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004808
Richard Smith96d71c32014-11-12 23:38:38 +00004809 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00004810 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00004811 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4812 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00004813 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00004814 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00004815 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00004816 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00004817 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00004818 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00004819 Diag((*Param)->getLocation(), diag::note_template_param_here);
4820 return true;
4821 }
4822
Richard Smith1fde8ec2012-09-07 02:06:42 +00004823 // We're now done with this argument.
4824 ++ArgIdx;
4825
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004826 if ((*Param)->isTemplateParameterPack()) {
4827 // The template parameter was a template parameter pack, so take the
4828 // deduced argument and place it on the argument pack. Note that we
4829 // stay on the same template parameter so that we can deduce more
4830 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004831 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004832 } else {
4833 // Move to the next template parameter.
4834 ++Param;
4835 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004836
Richard Smith96d71c32014-11-12 23:38:38 +00004837 // If we just saw a pack expansion into a non-pack, then directly convert
4838 // the remaining arguments, because we don't know what parameters they'll
4839 // match up with.
4840 if (PackExpansionIntoNonPack) {
4841 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004842 // If we were part way through filling in an expanded parameter pack,
4843 // fall back to just producing individual arguments.
4844 Converted.insert(Converted.end(),
4845 ArgumentPack.begin(), ArgumentPack.end());
4846 ArgumentPack.clear();
4847 }
4848
4849 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00004850 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00004851 ++ArgIdx;
4852 }
4853
Richard Smith1fde8ec2012-09-07 02:06:42 +00004854 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00004855 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004856
Douglas Gregor84d49a22009-11-11 21:54:23 +00004857 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004858 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004859
Douglas Gregor2f157c92011-06-03 02:59:40 +00004860 // If we're checking a partial template argument list, we're done.
4861 if (PartialTemplateArgs) {
4862 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00004863 Converted.push_back(
4864 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4865
Richard Smith1fde8ec2012-09-07 02:06:42 +00004866 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00004867 }
4868
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004869 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004870 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00004871 if ((*Param)->isTemplateParameterPack()) {
4872 assert(!getExpandedPackSize(*Param) &&
4873 "Should have dealt with this already");
4874
4875 // A non-expanded parameter pack before the end of the parameter list
4876 // only occurs for an ill-formed template parameter list, unless we've
4877 // got a partial argument list for a function template, so just bail out.
4878 if (Param + 1 != ParamEnd)
4879 return true;
4880
Benjamin Kramercce63472015-08-05 09:40:22 +00004881 Converted.push_back(
4882 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004883 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00004884
4885 ++Param;
4886 continue;
4887 }
4888
Douglas Gregor8e072612012-02-03 07:34:46 +00004889 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00004890 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004891
Douglas Gregor84d49a22009-11-11 21:54:23 +00004892 // Retrieve the default template argument from the template
4893 // parameter. For each kind of template parameter, we substitute the
4894 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004896 // the default argument.
4897 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004898 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004899 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4900 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004901
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004902 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004903 Template,
4904 TemplateLoc,
4905 RAngleLoc,
4906 TTP,
4907 Converted);
4908 if (!ArgType)
4909 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004910
Douglas Gregor84d49a22009-11-11 21:54:23 +00004911 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4912 ArgType);
4913 } else if (NonTypeTemplateParmDecl *NTTP
4914 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004915 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004916 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4917 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004918
John McCalldadc5752010-08-24 06:29:42 +00004919 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004920 TemplateLoc,
4921 RAngleLoc,
4922 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004923 Converted);
4924 if (E.isInvalid())
4925 return true;
4926
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004927 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004928 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4929 } else {
4930 TemplateTemplateParmDecl *TempParm
4931 = cast<TemplateTemplateParmDecl>(*Param);
4932
Richard Smith95d83952015-06-10 20:36:34 +00004933 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004934 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4935 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004936
Douglas Gregordf846d12011-03-02 18:46:51 +00004937 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004938 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004939 TemplateLoc,
4940 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004941 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004942 Converted,
4943 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004944 if (Name.isNull())
4945 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004946
Douglas Gregor9d802122011-03-02 17:09:35 +00004947 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4948 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004949 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004950
Douglas Gregor84d49a22009-11-11 21:54:23 +00004951 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00004952 // the default template argument. We're not actually instantiating a
4953 // template here, we just create this object to put a note into the
4954 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004955 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4956 SourceRange(TemplateLoc, RAngleLoc));
4957 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004958 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004959
Douglas Gregor84d49a22009-11-11 21:54:23 +00004960 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004961 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004962 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004963 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004964
Richard Trieu15b66532015-01-24 02:48:32 +00004965 // Core issue 150 (assumed resolution): if this is a template template
4966 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004967 // template definition.
4968 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004969 NewArgs.addArgument(Arg);
4970
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004971 // Move to the next template parameter and argument.
4972 ++Param;
4973 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004974 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004975
Richard Smith07f79912014-06-06 16:00:50 +00004976 // If we're performing a partial argument substitution, allow any trailing
4977 // pack expansions; they might be empty. This can happen even if
4978 // PartialTemplateArgs is false (the list of arguments is complete but
4979 // still dependent).
4980 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4981 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004982 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4983 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004984 }
4985
Douglas Gregor8e072612012-02-03 07:34:46 +00004986 // If we have any leftover arguments, then there were too many arguments.
4987 // Complain and fail.
4988 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004989 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4990
4991 // No problems found with the new argument list, propagate changes back
4992 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00004993 if (UpdateArgsWithConversions)
4994 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004995
Richard Smith1fde8ec2012-09-07 02:06:42 +00004996 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004997}
4998
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004999namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005000 class UnnamedLocalNoLinkageFinder
5001 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005002 {
5003 Sema &S;
5004 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005005
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005006 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005007
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005008 public:
5009 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5010
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00005012 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005013 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005014
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005015#define TYPE(Class, Parent) \
5016 bool Visit##Class##Type(const Class##Type *);
5017#define ABSTRACT_TYPE(Class, Parent) \
5018 bool Visit##Class##Type(const Class##Type *) { return false; }
5019#define NON_CANONICAL_TYPE(Class, Parent) \
5020 bool Visit##Class##Type(const Class##Type *) { return false; }
5021#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005022
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005023 bool VisitTagDecl(const TagDecl *Tag);
5024 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5025 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005026} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005027
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005028bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005029 return false;
5030}
5031
5032bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5033 return Visit(T->getElementType());
5034}
5035
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005037 return Visit(T->getPointeeType());
5038}
5039
5040bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005042 return Visit(T->getPointeeType());
5043}
5044
5045bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005046 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005047 return Visit(T->getPointeeType());
5048}
5049
5050bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005051 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005052 return Visit(T->getPointeeType());
5053}
5054
5055bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005056 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005057 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5058}
5059
5060bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005061 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005062 return Visit(T->getElementType());
5063}
5064
5065bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005066 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005067 return Visit(T->getElementType());
5068}
5069
5070bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005071 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005072 return Visit(T->getElementType());
5073}
5074
5075bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005077 return Visit(T->getElementType());
5078}
5079
5080bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005081 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005082 return Visit(T->getElementType());
5083}
5084
5085bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5086 return Visit(T->getElementType());
5087}
5088
5089bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5090 return Visit(T->getElementType());
5091}
5092
5093bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5094 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005095 for (const auto &A : T->param_types()) {
5096 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005097 return true;
5098 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005099
Alp Toker314cc812014-01-25 16:55:45 +00005100 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005101}
5102
5103bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5104 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00005105 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005106}
5107
5108bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5109 const UnresolvedUsingType*) {
5110 return false;
5111}
5112
5113bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5114 return false;
5115}
5116
5117bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5118 return Visit(T->getUnderlyingType());
5119}
5120
5121bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5122 return false;
5123}
5124
Alexis Hunte852b102011-05-24 22:41:36 +00005125bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5126 const UnaryTransformType*) {
5127 return false;
5128}
5129
Richard Smith30482bc2011-02-20 03:19:35 +00005130bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5131 return Visit(T->getDeducedType());
5132}
5133
Richard Smith600b5262017-01-26 20:40:47 +00005134bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5135 const DeducedTemplateSpecializationType *T) {
5136 return Visit(T->getDeducedType());
5137}
5138
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005139bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5140 return VisitTagDecl(T->getDecl());
5141}
5142
5143bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5144 return VisitTagDecl(T->getDecl());
5145}
5146
5147bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5148 const TemplateTypeParmType*) {
5149 return false;
5150}
5151
Douglas Gregorada4b792011-01-14 02:55:32 +00005152bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5153 const SubstTemplateTypeParmPackType *) {
5154 return false;
5155}
5156
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005157bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5158 const TemplateSpecializationType*) {
5159 return false;
5160}
5161
5162bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5163 const InjectedClassNameType* T) {
5164 return VisitTagDecl(T->getDecl());
5165}
5166
5167bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5168 const DependentNameType* T) {
5169 return VisitNestedNameSpecifier(T->getQualifier());
5170}
5171
5172bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5173 const DependentTemplateSpecializationType* T) {
5174 return VisitNestedNameSpecifier(T->getQualifier());
5175}
5176
Douglas Gregord2fa7662010-12-20 02:24:11 +00005177bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5178 const PackExpansionType* T) {
5179 return Visit(T->getPattern());
5180}
5181
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005182bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5183 return false;
5184}
5185
5186bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5187 const ObjCInterfaceType *) {
5188 return false;
5189}
5190
5191bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5192 const ObjCObjectPointerType *) {
5193 return false;
5194}
5195
Eli Friedman0dfb8892011-10-06 23:00:33 +00005196bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5197 return Visit(T->getValueType());
5198}
5199
Xiuli Pan9c14e282016-01-09 12:53:17 +00005200bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5201 return false;
5202}
5203
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005204bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5205 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005206 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005207 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005208 diag::warn_cxx98_compat_template_arg_local_type :
5209 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005210 << S.Context.getTypeDeclType(Tag) << SR;
5211 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005212 }
5213
John McCall5ea95772013-03-09 00:54:27 +00005214 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005215 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005216 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005217 diag::warn_cxx98_compat_template_arg_unnamed_type :
5218 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005219 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5220 return true;
5221 }
5222
5223 return false;
5224}
5225
5226bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5227 NestedNameSpecifier *NNS) {
5228 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5229 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005230
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005231 switch (NNS->getKind()) {
5232 case NestedNameSpecifier::Identifier:
5233 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005234 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005235 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005236 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005237 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005238
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005239 case NestedNameSpecifier::TypeSpec:
5240 case NestedNameSpecifier::TypeSpecWithTemplate:
5241 return Visit(QualType(NNS->getAsType(), 0));
5242 }
David Blaikie8a40f702012-01-17 06:56:22 +00005243 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005244}
5245
Douglas Gregord32e0282009-02-09 23:23:08 +00005246/// \brief Check a template argument against its corresponding
5247/// template type parameter.
5248///
5249/// This routine implements the semantics of C++ [temp.arg.type]. It
5250/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005251bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005252 TypeSourceInfo *ArgInfo) {
5253 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005254 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005255 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005256
5257 if (Arg->isVariablyModifiedType()) {
5258 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005259 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005260 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005261 }
5262
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005263 // C++03 [temp.arg.type]p2:
5264 // A local type, a type with no linkage, an unnamed type or a type
5265 // compounded from any of these types shall not be used as a
5266 // template-argument for a template type-parameter.
5267 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005268 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005269 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005270 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005271 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5272 (void)Finder.Visit(Context.getCanonicalType(Arg));
5273 }
5274
Douglas Gregord32e0282009-02-09 23:23:08 +00005275 return false;
5276}
5277
Douglas Gregor20fdef32012-04-10 17:08:25 +00005278enum NullPointerValueKind {
5279 NPV_NotNullPointer,
5280 NPV_NullPointer,
5281 NPV_Error
5282};
5283
5284/// \brief Determine whether the given template argument is a null pointer
5285/// value of the appropriate type.
5286static NullPointerValueKind
5287isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5288 QualType ParamType, Expr *Arg) {
5289 if (Arg->isValueDependent() || Arg->isTypeDependent())
5290 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005291
Richard Smithdb0ac552015-12-18 22:40:25 +00005292 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005293 llvm_unreachable(
5294 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005295
David Majnemer5c734ad2014-08-14 00:49:23 +00005296 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005297 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005298
Douglas Gregor20fdef32012-04-10 17:08:25 +00005299 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005300 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5301 if (ArgRV.isInvalid())
5302 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005303 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005304
Douglas Gregor20fdef32012-04-10 17:08:25 +00005305 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005306 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005307 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005308 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005309 EvalResult.HasSideEffects) {
5310 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005311
Douglas Gregor350880c2012-04-10 19:03:30 +00005312 // If our only note is the usual "invalid subexpression" note, just point
5313 // the caret at its location rather than producing an essentially
5314 // redundant note.
5315 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5316 diag::note_invalid_subexpr_in_const_expr) {
5317 DiagLoc = Notes[0].first;
5318 Notes.clear();
5319 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005320
Douglas Gregor350880c2012-04-10 19:03:30 +00005321 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5322 << Arg->getType() << Arg->getSourceRange();
5323 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5324 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005325
Douglas Gregor350880c2012-04-10 19:03:30 +00005326 S.Diag(Param->getLocation(), diag::note_template_param_here);
5327 return NPV_Error;
5328 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005329
Douglas Gregor20fdef32012-04-10 17:08:25 +00005330 // C++11 [temp.arg.nontype]p1:
5331 // - an address constant expression of type std::nullptr_t
5332 if (Arg->getType()->isNullPtrType())
5333 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005334
Douglas Gregor20fdef32012-04-10 17:08:25 +00005335 // - a constant expression that evaluates to a null pointer value (4.10); or
5336 // - a constant expression that evaluates to a null member pointer value
5337 // (4.11); or
5338 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5339 (EvalResult.Val.isMemberPointer() &&
5340 !EvalResult.Val.getMemberPointerDecl())) {
5341 // If our expression has an appropriate type, we've succeeded.
5342 bool ObjCLifetimeConversion;
5343 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5344 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5345 ObjCLifetimeConversion))
5346 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005347
Douglas Gregor20fdef32012-04-10 17:08:25 +00005348 // The types didn't match, but we know we got a null pointer; complain,
5349 // then recover as if the types were correct.
5350 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5351 << Arg->getType() << ParamType << Arg->getSourceRange();
5352 S.Diag(Param->getLocation(), diag::note_template_param_here);
5353 return NPV_NullPointer;
5354 }
5355
5356 // If we don't have a null pointer value, but we do have a NULL pointer
5357 // constant, suggest a cast to the appropriate type.
5358 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5359 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5360 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005361 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5362 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5363 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005364 S.Diag(Param->getLocation(), diag::note_template_param_here);
5365 return NPV_NullPointer;
5366 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005367
Douglas Gregor20fdef32012-04-10 17:08:25 +00005368 // FIXME: If we ever want to support general, address-constant expressions
5369 // as non-type template arguments, we should return the ExprResult here to
5370 // be interpreted by the caller.
5371 return NPV_NotNullPointer;
5372}
5373
David Majnemer61c39a12013-08-23 05:39:39 +00005374/// \brief Checks whether the given template argument is compatible with its
5375/// template parameter.
5376static bool CheckTemplateArgumentIsCompatibleWithParameter(
5377 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5378 Expr *Arg, QualType ArgType) {
5379 bool ObjCLifetimeConversion;
5380 if (ParamType->isPointerType() &&
5381 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5382 S.IsQualificationConversion(ArgType, ParamType, false,
5383 ObjCLifetimeConversion)) {
5384 // For pointer-to-object types, qualification conversions are
5385 // permitted.
5386 } else {
5387 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5388 if (!ParamRef->getPointeeType()->isFunctionType()) {
5389 // C++ [temp.arg.nontype]p5b3:
5390 // For a non-type template-parameter of type reference to
5391 // object, no conversions apply. The type referred to by the
5392 // reference may be more cv-qualified than the (otherwise
5393 // identical) type of the template- argument. The
5394 // template-parameter is bound directly to the
5395 // template-argument, which shall be an lvalue.
5396
5397 // FIXME: Other qualifiers?
5398 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5399 unsigned ArgQuals = ArgType.getCVRQualifiers();
5400
5401 if ((ParamQuals | ArgQuals) != ParamQuals) {
5402 S.Diag(Arg->getLocStart(),
5403 diag::err_template_arg_ref_bind_ignores_quals)
5404 << ParamType << Arg->getType() << Arg->getSourceRange();
5405 S.Diag(Param->getLocation(), diag::note_template_param_here);
5406 return true;
5407 }
5408 }
5409 }
5410
5411 // At this point, the template argument refers to an object or
5412 // function with external linkage. We now need to check whether the
5413 // argument and parameter types are compatible.
5414 if (!S.Context.hasSameUnqualifiedType(ArgType,
5415 ParamType.getNonReferenceType())) {
5416 // We can't perform this conversion or binding.
5417 if (ParamType->isReferenceType())
5418 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5419 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5420 else
5421 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5422 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5423 S.Diag(Param->getLocation(), diag::note_template_param_here);
5424 return true;
5425 }
5426 }
5427
5428 return false;
5429}
5430
Douglas Gregorccb07762009-02-11 19:52:55 +00005431/// \brief Checks whether the given template argument is the address
5432/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005433static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005434CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5435 NonTypeTemplateParmDecl *Param,
5436 QualType ParamType,
5437 Expr *ArgIn,
5438 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005439 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005440 Expr *Arg = ArgIn;
5441 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005442
Douglas Gregorb242683d2010-04-01 18:32:35 +00005443 bool AddressTaken = false;
5444 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005445 if (S.getLangOpts().MicrosoftExt) {
5446 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5447 // dereference and address-of operators.
5448 Arg = Arg->IgnoreParenCasts();
5449
5450 bool ExtWarnMSTemplateArg = false;
5451 UnaryOperatorKind FirstOpKind;
5452 SourceLocation FirstOpLoc;
5453 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5454 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5455 if (UnOpKind == UO_Deref)
5456 ExtWarnMSTemplateArg = true;
5457 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5458 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5459 if (!AddrOpLoc.isValid()) {
5460 FirstOpKind = UnOpKind;
5461 FirstOpLoc = UnOp->getOperatorLoc();
5462 }
5463 } else
5464 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005465 }
David Majnemer61c39a12013-08-23 05:39:39 +00005466 if (FirstOpLoc.isValid()) {
5467 if (ExtWarnMSTemplateArg)
5468 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5469 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005470
David Majnemer61c39a12013-08-23 05:39:39 +00005471 if (FirstOpKind == UO_AddrOf)
5472 AddressTaken = true;
5473 else if (Arg->getType()->isPointerType()) {
5474 // We cannot let pointers get dereferenced here, that is obviously not a
5475 // constant expression.
5476 assert(FirstOpKind == UO_Deref);
5477 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5478 << Arg->getSourceRange();
5479 }
5480 }
5481 } else {
5482 // See through any implicit casts we added to fix the type.
5483 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005484
David Majnemer61c39a12013-08-23 05:39:39 +00005485 // C++ [temp.arg.nontype]p1:
5486 //
5487 // A template-argument for a non-type, non-template
5488 // template-parameter shall be one of: [...]
5489 //
5490 // -- the address of an object or function with external
5491 // linkage, including function templates and function
5492 // template-ids but excluding non-static class members,
5493 // expressed as & id-expression where the & is optional if
5494 // the name refers to a function or array, or if the
5495 // corresponding template-parameter is a reference; or
5496
5497 // In C++98/03 mode, give an extension warning on any extra parentheses.
5498 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5499 bool ExtraParens = false;
5500 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5501 if (!Invalid && !ExtraParens) {
5502 S.Diag(Arg->getLocStart(),
5503 S.getLangOpts().CPlusPlus11
5504 ? diag::warn_cxx98_compat_template_arg_extra_parens
5505 : diag::ext_template_arg_extra_parens)
5506 << Arg->getSourceRange();
5507 ExtraParens = true;
5508 }
5509
5510 Arg = Parens->getSubExpr();
5511 }
5512
5513 while (SubstNonTypeTemplateParmExpr *subst =
5514 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5515 Arg = subst->getReplacement()->IgnoreImpCasts();
5516
5517 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5518 if (UnOp->getOpcode() == UO_AddrOf) {
5519 Arg = UnOp->getSubExpr();
5520 AddressTaken = true;
5521 AddrOpLoc = UnOp->getOperatorLoc();
5522 }
5523 }
5524
5525 while (SubstNonTypeTemplateParmExpr *subst =
5526 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5527 Arg = subst->getReplacement()->IgnoreImpCasts();
5528 }
John McCall7c454bb2011-07-15 05:09:51 +00005529
David Majnemer07910d62014-06-26 07:48:46 +00005530 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5531 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5532
5533 // If our parameter has pointer type, check for a null template value.
5534 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5535 NullPointerValueKind NPV;
5536 // dllimport'd entities aren't constant but are available inside of template
5537 // arguments.
5538 if (Entity && Entity->hasAttr<DLLImportAttr>())
5539 NPV = NPV_NotNullPointer;
5540 else
5541 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
5542 switch (NPV) {
5543 case NPV_NullPointer:
5544 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005545 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5546 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005547 return false;
5548
5549 case NPV_Error:
5550 return true;
5551
5552 case NPV_NotNullPointer:
5553 break;
5554 }
5555 }
5556
Chandler Carruth724a8a12010-01-31 10:01:20 +00005557 // Stop checking the precise nature of the argument if it is value dependent,
5558 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005559 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005560 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005561 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005562 }
David Majnemer61c39a12013-08-23 05:39:39 +00005563
5564 if (isa<CXXUuidofExpr>(Arg)) {
5565 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5566 ArgIn, Arg, ArgType))
5567 return true;
5568
5569 Converted = TemplateArgument(ArgIn);
5570 return false;
5571 }
5572
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005573 if (!DRE) {
5574 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5575 << Arg->getSourceRange();
5576 S.Diag(Param->getLocation(), diag::note_template_param_here);
5577 return true;
5578 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00005579
Douglas Gregorccb07762009-02-11 19:52:55 +00005580 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00005581 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005582 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00005583 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005584 S.Diag(Param->getLocation(), diag::note_template_param_here);
5585 return true;
5586 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005587
5588 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00005589 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005590 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005591 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00005592 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005593 S.Diag(Param->getLocation(), diag::note_template_param_here);
5594 return true;
5595 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005596 }
Mike Stump11289f42009-09-09 15:08:12 +00005597
Richard Smith9380e0e2012-04-04 21:11:30 +00005598 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5599 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00005600
Richard Smith9380e0e2012-04-04 21:11:30 +00005601 // A non-type template argument must refer to an object or function.
5602 if (!Func && !Var) {
5603 // We found something, but we don't know specifically what it is.
5604 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5605 << Arg->getSourceRange();
5606 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5607 return true;
5608 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005609
Richard Smith9380e0e2012-04-04 21:11:30 +00005610 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00005611 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005612 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00005613 diag::warn_cxx98_compat_template_arg_object_internal :
5614 diag::ext_template_arg_object_internal)
5615 << !Func << Entity << Arg->getSourceRange();
5616 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5617 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00005618 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005619 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5620 << !Func << Entity << Arg->getSourceRange();
5621 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5622 << !Func;
5623 return true;
5624 }
5625
5626 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005627 // If the template parameter has pointer type, the function decays.
5628 if (ParamType->isPointerType() && !AddressTaken)
5629 ArgType = S.Context.getPointerType(Func->getType());
5630 else if (AddressTaken && ParamType->isReferenceType()) {
5631 // If we originally had an address-of operator, but the
5632 // parameter has reference type, complain and (if things look
5633 // like they will work) drop the address-of operator.
5634 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5635 ParamType.getNonReferenceType())) {
5636 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5637 << ParamType;
5638 S.Diag(Param->getLocation(), diag::note_template_param_here);
5639 return true;
5640 }
5641
5642 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5643 << ParamType
5644 << FixItHint::CreateRemoval(AddrOpLoc);
5645 S.Diag(Param->getLocation(), diag::note_template_param_here);
5646
5647 ArgType = Func->getType();
5648 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005649 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005650 // A value of reference type is not an object.
5651 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005652 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00005653 diag::err_template_arg_reference_var)
5654 << Var->getType() << Arg->getSourceRange();
5655 S.Diag(Param->getLocation(), diag::note_template_param_here);
5656 return true;
5657 }
5658
Richard Smith9380e0e2012-04-04 21:11:30 +00005659 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005660 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005661 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5662 << Arg->getSourceRange();
5663 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5664 return true;
5665 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005666
5667 // If the template parameter has pointer type, we must have taken
5668 // the address of this object.
5669 if (ParamType->isReferenceType()) {
5670 if (AddressTaken) {
5671 // If we originally had an address-of operator, but the
5672 // parameter has reference type, complain and (if things look
5673 // like they will work) drop the address-of operator.
5674 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5675 ParamType.getNonReferenceType())) {
5676 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5677 << ParamType;
5678 S.Diag(Param->getLocation(), diag::note_template_param_here);
5679 return true;
5680 }
5681
5682 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5683 << ParamType
5684 << FixItHint::CreateRemoval(AddrOpLoc);
5685 S.Diag(Param->getLocation(), diag::note_template_param_here);
5686
5687 ArgType = Var->getType();
5688 }
5689 } else if (!AddressTaken && ParamType->isPointerType()) {
5690 if (Var->getType()->isArrayType()) {
5691 // Array-to-pointer decay.
5692 ArgType = S.Context.getArrayDecayedType(Var->getType());
5693 } else {
5694 // If the template parameter has pointer type but the address of
5695 // this object was not taken, complain and (possibly) recover by
5696 // taking the address of the entity.
5697 ArgType = S.Context.getPointerType(Var->getType());
5698 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5699 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5700 << ParamType;
5701 S.Diag(Param->getLocation(), diag::note_template_param_here);
5702 return true;
5703 }
5704
5705 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5706 << ParamType
5707 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5708
5709 S.Diag(Param->getLocation(), diag::note_template_param_here);
5710 }
5711 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005712 }
Mike Stump11289f42009-09-09 15:08:12 +00005713
David Majnemer61c39a12013-08-23 05:39:39 +00005714 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5715 Arg, ArgType))
5716 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005717
5718 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00005719 Converted =
5720 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00005721 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00005722 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005723}
5724
5725/// \brief Checks whether the given template argument is a pointer to
5726/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005727static bool CheckTemplateArgumentPointerToMember(Sema &S,
5728 NonTypeTemplateParmDecl *Param,
5729 QualType ParamType,
5730 Expr *&ResultArg,
5731 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005732 bool Invalid = false;
5733
Douglas Gregor20fdef32012-04-10 17:08:25 +00005734 // Check for a null pointer value.
5735 Expr *Arg = ResultArg;
5736 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
5737 case NPV_Error:
5738 return true;
5739 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005740 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005741 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5742 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00005743 return false;
5744 case NPV_NotNullPointer:
5745 break;
5746 }
5747
5748 bool ObjCLifetimeConversion;
5749 if (S.IsQualificationConversion(Arg->getType(),
5750 ParamType.getNonReferenceType(),
5751 false, ObjCLifetimeConversion)) {
5752 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005753 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00005754 ResultArg = Arg;
5755 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
5756 ParamType.getNonReferenceType())) {
5757 // We can't perform this conversion.
5758 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5759 << Arg->getType() << ParamType << Arg->getSourceRange();
5760 S.Diag(Param->getLocation(), diag::note_template_param_here);
5761 return true;
5762 }
5763
Douglas Gregorccb07762009-02-11 19:52:55 +00005764 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00005765 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00005766 Arg = Cast->getSubExpr();
5767
5768 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005769 //
Douglas Gregorccb07762009-02-11 19:52:55 +00005770 // A template-argument for a non-type, non-template
5771 // template-parameter shall be one of: [...]
5772 //
5773 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00005774 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00005775
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005776 // In C++98/03 mode, give an extension warning on any extra parentheses.
5777 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5778 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005779 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005780 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005781 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005782 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00005783 diag::warn_cxx98_compat_template_arg_extra_parens :
5784 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00005785 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005786 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00005787 }
5788
5789 Arg = Parens->getSubExpr();
5790 }
5791
John McCall7c454bb2011-07-15 05:09:51 +00005792 while (SubstNonTypeTemplateParmExpr *subst =
5793 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5794 Arg = subst->getReplacement()->IgnoreImpCasts();
5795
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005796 // A pointer-to-member constant written &Class::member.
5797 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00005798 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005799 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5800 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005801 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005802 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005803 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005804 // A constant of pointer-to-member type.
5805 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5806 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5807 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00005808 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005809 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005810 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005811 } else {
5812 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005813 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005814 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005815 return Invalid;
5816 }
5817 }
5818 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005819
Craig Topperc3ec1492014-05-26 06:22:03 +00005820 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005821 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005822
Douglas Gregorccb07762009-02-11 19:52:55 +00005823 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005824 return S.Diag(Arg->getLocStart(),
5825 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00005826 << Arg->getSourceRange();
5827
David Majnemer3ac84e62013-10-22 21:56:38 +00005828 if (isa<FieldDecl>(DRE->getDecl()) ||
5829 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5830 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005831 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00005832 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00005833 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5834 "Only non-static member pointers can make it here");
5835
5836 // Okay: this is the address of a non-static member, and therefore
5837 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00005838 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005839 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005840 } else {
5841 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005842 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005843 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005844 return Invalid;
5845 }
5846
5847 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005848 S.Diag(Arg->getLocStart(),
5849 diag::err_template_arg_not_pointer_to_member_form)
5850 << Arg->getSourceRange();
5851 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00005852 return true;
5853}
5854
Douglas Gregord32e0282009-02-09 23:23:08 +00005855/// \brief Check a template argument against its corresponding
5856/// non-type template parameter.
5857///
Douglas Gregor463421d2009-03-03 04:44:36 +00005858/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00005859/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00005860/// returns the converted template argument. \p ParamType is the
5861/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00005862ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00005863 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00005864 TemplateArgument &Converted,
5865 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005866 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00005867
Richard Smith5f274382016-09-28 23:55:27 +00005868 // If the parameter type somehow involves auto, deduce the type now.
5869 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
Richard Smith4ae5ec82017-02-22 20:01:55 +00005870 // During template argument deduction, we allow 'decltype(auto)' to
5871 // match an arbitrary dependent argument.
5872 // FIXME: The language rules don't say what happens in this case.
5873 // FIXME: We get an opaque dependent type out of decltype(auto) if the
5874 // expression is merely instantiation-dependent; is this enough?
5875 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
5876 auto *AT = dyn_cast<AutoType>(ParamType);
5877 if (AT && AT->isDecltypeAuto()) {
5878 Converted = TemplateArgument(Arg);
5879 return Arg;
5880 }
5881 }
5882
Richard Smith87d263e2016-12-25 08:05:23 +00005883 // When checking a deduced template argument, deduce from its type even if
5884 // the type is dependent, in order to check the types of non-type template
5885 // arguments line up properly in partial ordering.
5886 Optional<unsigned> Depth;
5887 if (CTAK != CTAK_Specified)
5888 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00005889 if (DeduceAutoType(
5890 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00005891 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00005892 Diag(Arg->getExprLoc(),
5893 diag::err_non_type_template_parm_type_deduction_failure)
5894 << Param->getDeclName() << Param->getType() << Arg->getType()
5895 << Arg->getSourceRange();
5896 Diag(Param->getLocation(), diag::note_template_param_here);
5897 return ExprError();
5898 }
5899 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5900 // an error. The error message normally references the parameter
5901 // declaration, but here we'll pass the argument location because that's
5902 // where the parameter type is deduced.
5903 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5904 if (ParamType.isNull()) {
5905 Diag(Param->getLocation(), diag::note_template_param_here);
5906 return ExprError();
5907 }
5908 }
5909
Richard Smithd663fdd2014-12-17 20:42:37 +00005910 // We should have already dropped all cv-qualifiers by now.
5911 assert(!ParamType.hasQualifiers() &&
5912 "non-type template parameter type cannot be qualified");
5913
5914 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00005915 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00005916 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00005917 // FIXME: If either type is dependent, we skip the check. This isn't
5918 // correct, since during deduction we're supposed to have replaced each
5919 // template parameter with some unique (non-dependent) placeholder.
5920 // FIXME: If the argument type contains 'auto', we carry on and fail the
5921 // type check in order to force specific types to be more specialized than
5922 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5923 // work.
5924 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5925 !Arg->getType()->getContainedAutoType()) {
5926 Converted = TemplateArgument(Arg);
5927 return Arg;
5928 }
5929 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5930 // we should actually be checking the type of the template argument in P,
5931 // not the type of the template argument deduced from A, against the
5932 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00005933 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00005934 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00005935 << ParamType.getUnqualifiedType();
5936 Diag(Param->getLocation(), diag::note_template_param_here);
5937 return ExprError();
5938 }
5939
Richard Smith87d263e2016-12-25 08:05:23 +00005940 // If either the parameter has a dependent type or the argument is
5941 // type-dependent, there's nothing we can check now.
5942 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5943 // FIXME: Produce a cloned, canonical expression?
5944 Converted = TemplateArgument(Arg);
5945 return Arg;
5946 }
5947
Richard Smithe5945872017-01-06 22:52:53 +00005948 // The initialization of the parameter from the argument is
5949 // a constant-evaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00005950 EnterExpressionEvaluationContext ConstantEvaluated(
5951 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smithe5945872017-01-06 22:52:53 +00005952
Richard Smith410cc892014-11-26 03:26:53 +00005953 if (getLangOpts().CPlusPlus1z) {
Richard Smith410cc892014-11-26 03:26:53 +00005954 // C++1z [temp.arg.nontype]p1:
5955 // A template-argument for a non-type template parameter shall be
5956 // a converted constant expression of the type of the template-parameter.
5957 APValue Value;
5958 ExprResult ArgResult = CheckConvertedConstantExpression(
5959 Arg, ParamType, Value, CCEK_TemplateArg);
5960 if (ArgResult.isInvalid())
5961 return ExprError();
5962
Richard Smith52e624f2016-12-21 21:42:57 +00005963 // For a value-dependent argument, CheckConvertedConstantExpression is
5964 // permitted (and expected) to be unable to determine a value.
5965 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00005966 Converted = TemplateArgument(ArgResult.get());
5967 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00005968 }
5969
Richard Smithd663fdd2014-12-17 20:42:37 +00005970 QualType CanonParamType = Context.getCanonicalType(ParamType);
5971
Richard Smith410cc892014-11-26 03:26:53 +00005972 // Convert the APValue to a TemplateArgument.
5973 switch (Value.getKind()) {
5974 case APValue::Uninitialized:
5975 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005976 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005977 break;
5978 case APValue::Int:
5979 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005980 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005981 break;
5982 case APValue::MemberPointer: {
5983 assert(ParamType->isMemberPointerType());
5984
5985 // FIXME: We need TemplateArgument representation and mangling for these.
5986 if (!Value.getMemberPointerPath().empty()) {
5987 Diag(Arg->getLocStart(),
5988 diag::err_template_arg_member_ptr_base_derived_not_supported)
5989 << Value.getMemberPointerDecl() << ParamType
5990 << Arg->getSourceRange();
5991 return ExprError();
5992 }
5993
5994 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005995 Converted = VD ? TemplateArgument(VD, CanonParamType)
5996 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005997 break;
5998 }
5999 case APValue::LValue: {
6000 // For a non-type template-parameter of pointer or reference type,
6001 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00006002 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6003 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00006004 // -- a temporary object
6005 // -- a string literal
6006 // -- the result of a typeid expression, or
Eric Christopher0d2c56a2017-03-31 01:45:39 +00006007 // -- a predefined __func__ variable
Richard Smith410cc892014-11-26 03:26:53 +00006008 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6009 if (isa<CXXUuidofExpr>(E)) {
6010 Converted = TemplateArgument(const_cast<Expr*>(E));
6011 break;
6012 }
6013 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
6014 << Arg->getSourceRange();
6015 return ExprError();
6016 }
6017 auto *VD = const_cast<ValueDecl *>(
6018 Value.getLValueBase().dyn_cast<const ValueDecl *>());
6019 // -- a subobject
6020 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6021 VD && VD->getType()->isArrayType() &&
6022 Value.getLValuePath()[0].ArrayIndex == 0 &&
6023 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6024 // Per defect report (no number yet):
6025 // ... other than a pointer to the first element of a complete array
6026 // object.
6027 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6028 Value.isLValueOnePastTheEnd()) {
6029 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6030 << Value.getAsString(Context, ParamType);
6031 return ExprError();
6032 }
Richard Smithd663fdd2014-12-17 20:42:37 +00006033 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00006034 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00006035 assert((!VD || !ParamType->isNullPtrType()) &&
6036 "non-null value of type nullptr_t?");
6037 Converted = VD ? TemplateArgument(VD, CanonParamType)
6038 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006039 break;
6040 }
6041 case APValue::AddrLabelDiff:
6042 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6043 case APValue::Float:
6044 case APValue::ComplexInt:
6045 case APValue::ComplexFloat:
6046 case APValue::Vector:
6047 case APValue::Array:
6048 case APValue::Struct:
6049 case APValue::Union:
6050 llvm_unreachable("invalid kind for template argument");
6051 }
6052
6053 return ArgResult.get();
6054 }
6055
Douglas Gregor86560402009-02-10 23:36:10 +00006056 // C++ [temp.arg.nontype]p5:
6057 // The following conversions are performed on each expression used
6058 // as a non-type template-argument. If a non-type
6059 // template-argument cannot be converted to the type of the
6060 // corresponding template-parameter then the program is
6061 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00006062 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00006063 // C++11:
6064 // -- for a non-type template-parameter of integral or
6065 // enumeration type, conversions permitted in a converted
6066 // constant expression are applied.
6067 //
6068 // C++98:
6069 // -- for a non-type template-parameter of integral or
6070 // enumeration type, integral promotions (4.5) and integral
6071 // conversions (4.7) are applied.
6072
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006073 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00006074 // C++ [temp.arg.nontype]p1:
6075 // A template-argument for a non-type, non-template template-parameter
6076 // shall be one of:
6077 //
6078 // -- for a non-type template-parameter of integral or enumeration
6079 // type, a converted constant expression of the type of the
6080 // template-parameter; or
6081 llvm::APSInt Value;
6082 ExprResult ArgResult =
6083 CheckConvertedConstantExpression(Arg, ParamType, Value,
6084 CCEK_TemplateArg);
6085 if (ArgResult.isInvalid())
6086 return ExprError();
6087
Richard Smith01bfa682016-12-27 02:02:09 +00006088 // We can't check arbitrary value-dependent arguments.
6089 if (ArgResult.get()->isValueDependent()) {
6090 Converted = TemplateArgument(ArgResult.get());
6091 return ArgResult;
6092 }
6093
Richard Smithf8379a02012-01-18 23:55:52 +00006094 // Widen the argument value to sizeof(parameter type). This is almost
6095 // always a no-op, except when the parameter type is bool. In
6096 // that case, this may extend the argument from 1 bit to 8 bits.
6097 QualType IntegerType = ParamType;
6098 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6099 IntegerType = Enum->getDecl()->getIntegerType();
6100 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6101
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006102 Converted = TemplateArgument(Context, Value,
6103 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00006104 return ArgResult;
6105 }
6106
Richard Smith08b12f12011-10-27 22:11:44 +00006107 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6108 if (ArgResult.isInvalid())
6109 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006110 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00006111
6112 QualType ArgType = Arg->getType();
6113
Douglas Gregor86560402009-02-10 23:36:10 +00006114 // C++ [temp.arg.nontype]p1:
6115 // A template-argument for a non-type, non-template
6116 // template-parameter shall be one of:
6117 //
6118 // -- an integral constant-expression of integral or enumeration
6119 // type; or
6120 // -- the name of a non-type template-parameter; or
6121 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006122 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00006123 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006124 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00006125 diag::err_template_arg_not_integral_or_enumeral)
6126 << ArgType << Arg->getSourceRange();
6127 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006128 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00006129 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00006130 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6131 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006132
Douglas Gregore2b37442012-05-04 22:38:52 +00006133 public:
6134 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00006135
6136 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6137 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00006138 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6139 }
6140 } Diagnoser(ArgType);
6141
6142 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006143 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00006144 if (!Arg)
6145 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006146 }
6147
Richard Smithd663fdd2014-12-17 20:42:37 +00006148 // From here on out, all we care about is the unqualified form
6149 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006150 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00006151
6152 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00006153 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00006154 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00006155 } else if (ParamType->isBooleanType()) {
6156 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006157 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006158 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6159 !ParamType->isEnumeralType()) {
6160 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006161 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006162 } else {
6163 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006164 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00006165 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00006166 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006167 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006168 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006169 }
6170
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006171 // Add the value of this argument to the list of converted
6172 // arguments. We use the bitwidth and signedness of the template
6173 // parameter.
6174 if (Arg->isValueDependent()) {
6175 // The argument is value-dependent. Create a new
6176 // TemplateArgument with the converted expression.
6177 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006178 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006179 }
6180
Douglas Gregor52aba872009-03-14 00:20:21 +00006181 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00006182 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00006183 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00006184
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006185 if (ParamType->isBooleanType()) {
6186 // Value must be zero or one.
6187 Value = Value != 0;
6188 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6189 if (Value.getBitWidth() != AllowedBits)
6190 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006191 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006192 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006193 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006194
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006195 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006196 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006197 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006198 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006199 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006200 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00006201
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006202 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006203 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006204 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006205 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006206 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6207 << Arg->getSourceRange();
6208 Diag(Param->getLocation(), diag::note_template_param_here);
6209 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006210
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006211 // Complain if we overflowed the template parameter's type.
6212 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006213 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006214 RequiredBits = OldValue.getActiveBits();
6215 else if (OldValue.isUnsigned())
6216 RequiredBits = OldValue.getActiveBits() + 1;
6217 else
6218 RequiredBits = OldValue.getMinSignedBits();
6219 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006220 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006221 diag::warn_template_arg_too_large)
6222 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6223 << Arg->getSourceRange();
6224 Diag(Param->getLocation(), diag::note_template_param_here);
6225 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006226 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006227
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006228 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006229 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006230 ? Context.getCanonicalType(ParamType)
6231 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006232 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006233 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006234
Richard Smith08b12f12011-10-27 22:11:44 +00006235 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006236 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6237
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006238 // Handle pointer-to-function, reference-to-function, and
6239 // pointer-to-member-function all in (roughly) the same way.
6240 if (// -- For a non-type template-parameter of type pointer to
6241 // function, only the function-to-pointer conversion (4.3) is
6242 // applied. If the template-argument represents a set of
6243 // overloaded functions (or a pointer to such), the matching
6244 // function is selected from the set (13.4).
6245 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006246 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006247 // -- For a non-type template-parameter of type reference to
6248 // function, no conversions apply. If the template-argument
6249 // represents a set of overloaded functions, the matching
6250 // function is selected from the set (13.4).
6251 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006252 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006253 // -- For a non-type template-parameter of type pointer to
6254 // member function, no conversions apply. If the
6255 // template-argument represents a set of overloaded member
6256 // functions, the matching member function is selected from
6257 // the set (13.4).
6258 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006259 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006260 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006261
Douglas Gregor064fdb22010-04-14 23:11:21 +00006262 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006263 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006264 true,
6265 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006266 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006267 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006268
6269 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6270 ArgType = Arg->getType();
6271 } else
John Wiegley01296292011-04-08 18:41:53 +00006272 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006273 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006274
John Wiegley01296292011-04-08 18:41:53 +00006275 if (!ParamType->isMemberPointerType()) {
6276 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6277 ParamType,
6278 Arg, Converted))
6279 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006280 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006281 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006282
Douglas Gregor20fdef32012-04-10 17:08:25 +00006283 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6284 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006285 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006286 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006287 }
6288
Chris Lattner696197c2009-02-20 21:37:53 +00006289 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006290 // -- for a non-type template-parameter of type pointer to
6291 // object, qualification conversions (4.4) and the
6292 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006293 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006294 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006295 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006296
John Wiegley01296292011-04-08 18:41:53 +00006297 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6298 ParamType,
6299 Arg, Converted))
6300 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006301 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006302 }
Mike Stump11289f42009-09-09 15:08:12 +00006303
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006304 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006305 // -- For a non-type template-parameter of type reference to
6306 // object, no conversions apply. The type referred to by the
6307 // reference may be more cv-qualified than the (otherwise
6308 // identical) type of the template-argument. The
6309 // template-parameter is bound directly to the
6310 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006311 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006312 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006313
Douglas Gregor064fdb22010-04-14 23:11:21 +00006314 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006315 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6316 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006317 true,
6318 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006319 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006320 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006321
6322 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6323 ArgType = Arg->getType();
6324 } else
John Wiegley01296292011-04-08 18:41:53 +00006325 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006327
John Wiegley01296292011-04-08 18:41:53 +00006328 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6329 ParamType,
6330 Arg, Converted))
6331 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006332 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006333 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006334
Douglas Gregor20fdef32012-04-10 17:08:25 +00006335 // Deal with parameters of type std::nullptr_t.
6336 if (ParamType->isNullPtrType()) {
6337 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6338 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006339 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006340 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006341
Douglas Gregor20fdef32012-04-10 17:08:25 +00006342 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6343 case NPV_NotNullPointer:
6344 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6345 << Arg->getType() << ParamType;
6346 Diag(Param->getLocation(), diag::note_template_param_here);
6347 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006348
Douglas Gregor20fdef32012-04-10 17:08:25 +00006349 case NPV_Error:
6350 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006351
Douglas Gregor20fdef32012-04-10 17:08:25 +00006352 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006353 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006354 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6355 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006356 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006357 }
6358 }
6359
Douglas Gregor0e558532009-02-11 16:16:59 +00006360 // -- For a non-type template-parameter of type pointer to data
6361 // member, qualification conversions (4.4) are applied.
6362 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6363
Douglas Gregor20fdef32012-04-10 17:08:25 +00006364 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6365 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006366 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006367 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006368}
6369
Richard Smith26b86ea2016-12-31 21:41:23 +00006370static void DiagnoseTemplateParameterListArityMismatch(
6371 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6372 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6373
Douglas Gregord32e0282009-02-09 23:23:08 +00006374/// \brief Check a template argument against its corresponding
6375/// template template parameter.
6376///
6377/// This routine implements the semantics of C++ [temp.arg.template].
6378/// It returns true if an error occurred, and false otherwise.
6379bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00006380 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00006381 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006382 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006383 TemplateDecl *Template = Name.getAsTemplateDecl();
6384 if (!Template) {
6385 // Any dependent template name is fine.
6386 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6387 return false;
6388 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006389
Richard Smith26b86ea2016-12-31 21:41:23 +00006390 if (Template->isInvalidDecl())
6391 return true;
6392
Richard Smith3f1b5d02011-05-05 21:57:07 +00006393 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006394 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006395 // the name of a class template or an alias template, expressed as an
6396 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006397 // primary class templates are considered when matching the
6398 // template template argument with the corresponding parameter;
6399 // partial specializations are not considered even if their
6400 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006401 //
6402 // Note that we also allow template template parameters here, which
6403 // will happen when we are dealing with, e.g., class template
6404 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006405 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006406 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006407 !isa<TypeAliasTemplateDecl>(Template) &&
6408 !isa<BuiltinTemplateDecl>(Template)) {
6409 assert(isa<FunctionTemplateDecl>(Template) &&
6410 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006411 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006412 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6413 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006414 }
6415
Richard Smith1fde8ec2012-09-07 02:06:42 +00006416 TemplateParameterList *Params = Param->getTemplateParameters();
6417 if (Param->isExpandedParameterPack())
6418 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6419
Richard Smith26b86ea2016-12-31 21:41:23 +00006420 // C++1z [temp.arg.template]p3: (DR 150)
6421 // A template-argument matches a template template-parameter P when P
6422 // is at least as specialized as the template-argument A.
6423 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6424 // Quick check for the common case:
6425 // If P contains a parameter pack, then A [...] matches P if each of A's
6426 // template parameters matches the corresponding template parameter in
6427 // the template-parameter-list of P.
6428 if (TemplateParameterListsAreEqual(
6429 Template->getTemplateParameters(), Params, false,
6430 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6431 return false;
6432
6433 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6434 Arg.getLocation()))
6435 return false;
6436 // FIXME: Produce better diagnostics for deduction failures.
6437 }
6438
Douglas Gregor85e0f662009-02-10 00:24:35 +00006439 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006440 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006441 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006442 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006443 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006444}
6445
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006446/// \brief Given a non-type template argument that refers to a
6447/// declaration and the type of its corresponding non-type template
6448/// parameter, produce an expression that properly refers to that
6449/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006450ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006451Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6452 QualType ParamType,
6453 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006454 // C++ [temp.param]p8:
6455 //
6456 // A non-type template-parameter of type "array of T" or
6457 // "function returning T" is adjusted to be of type "pointer to
6458 // T" or "pointer to function returning T", respectively.
6459 if (ParamType->isArrayType())
6460 ParamType = Context.getArrayDecayedType(ParamType);
6461 else if (ParamType->isFunctionType())
6462 ParamType = Context.getPointerType(ParamType);
6463
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006464 // For a NULL non-type template argument, return nullptr casted to the
6465 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006466 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006467 return ImpCastExprToType(
6468 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6469 ParamType,
6470 ParamType->getAs<MemberPointerType>()
6471 ? CK_NullToMemberPointer
6472 : CK_NullToPointer);
6473 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006474 assert(Arg.getKind() == TemplateArgument::Declaration &&
6475 "Only declaration template arguments permitted here");
6476
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006477 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6478
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006479 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006480 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6481 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006482 // If the value is a class member, we might have a pointer-to-member.
6483 // Determine whether the non-type template template parameter is of
6484 // pointer-to-member type. If so, we need to build an appropriate
6485 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6486 // would refer to the member itself.
6487 if (ParamType->isMemberPointerType()) {
6488 QualType ClassType
6489 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6490 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006491 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006492 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006493 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006494 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006495
6496 // The actual value-ness of this is unimportant, but for
6497 // internal consistency's sake, references to instance methods
6498 // are r-values.
6499 ExprValueKind VK = VK_LValue;
6500 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6501 VK = VK_RValue;
6502
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006503 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006504 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006505 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006506 Loc,
6507 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006508 if (RefExpr.isInvalid())
6509 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006510
John McCalle3027922010-08-25 11:45:40 +00006511 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006512
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006513 // We might need to perform a trailing qualification conversion, since
6514 // the element type on the parameter could be more qualified than the
6515 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006516 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006517 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006518 ParamType.getUnqualifiedType(), false,
6519 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006520 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006521
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006522 assert(!RefExpr.isInvalid() &&
6523 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006524 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006525 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006526 }
6527 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006528
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006529 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006530
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006531 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006532 // When the non-type template parameter is a pointer, take the
6533 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006534 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006535 if (RefExpr.isInvalid())
6536 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006537
Richard Smithfc6fca12017-01-28 00:38:35 +00006538 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6539 (T->isFunctionType() || T->isArrayType())) {
6540 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006541 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006542 if (RefExpr.isInvalid())
6543 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006544
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006545 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006547
Douglas Gregorb242683d2010-04-01 18:32:35 +00006548 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006549 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006550 }
6551
John McCall7decc9e2010-11-18 06:31:45 +00006552 ExprValueKind VK = VK_RValue;
6553
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006554 // If the non-type template parameter has reference type, qualify the
6555 // resulting declaration reference with the extra qualifiers on the
6556 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006557 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6558 VK = VK_LValue;
6559 T = Context.getQualifiedType(T,
6560 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006561 } else if (isa<FunctionDecl>(VD)) {
6562 // References to functions are always lvalues.
6563 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006564 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006565
John McCall7decc9e2010-11-18 06:31:45 +00006566 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006567}
6568
6569/// \brief Construct a new expression that refers to the given
6570/// integral template argument with the given source-location
6571/// information.
6572///
6573/// This routine takes care of the mapping from an integral template
6574/// argument (which may have any integral type) to the appropriate
6575/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006576ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006577Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6578 SourceLocation Loc) {
6579 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006580 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006581 QualType OrigT = Arg.getIntegralType();
6582
6583 // If this is an enum type that we're instantiating, we need to use an integer
6584 // type the same size as the enumerator. We don't want to build an
6585 // IntegerLiteral with enum type. The integer type of an enum type can be of
6586 // any integral type with C++11 enum classes, make sure we create the right
6587 // type of literal for it.
6588 QualType T = OrigT;
6589 if (const EnumType *ET = OrigT->getAs<EnumType>())
6590 T = ET->getDecl()->getIntegerType();
6591
6592 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006593 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00006594 // This does not need to handle u8 character literals because those are
6595 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00006596 CharacterLiteral::CharacterKind Kind;
6597 if (T->isWideCharType())
6598 Kind = CharacterLiteral::Wide;
6599 else if (T->isChar16Type())
6600 Kind = CharacterLiteral::UTF16;
6601 else if (T->isChar32Type())
6602 Kind = CharacterLiteral::UTF32;
6603 else
6604 Kind = CharacterLiteral::Ascii;
6605
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006606 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6607 Kind, T, Loc);
6608 } else if (T->isBooleanType()) {
6609 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6610 T, Loc);
6611 } else if (T->isNullPtrType()) {
6612 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6613 } else {
6614 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00006615 }
6616
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006617 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00006618 // FIXME: This is a hack. We need a better way to handle substituted
6619 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00006620 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6621 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006622 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00006623 Loc, Loc);
6624 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006625
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006626 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006627}
6628
Douglas Gregor641040a2011-01-12 23:45:44 +00006629/// \brief Match two template parameters within template parameter lists.
6630static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6631 bool Complain,
6632 Sema::TemplateParameterListEqualKind Kind,
6633 SourceLocation TemplateArgLoc) {
6634 // Check the actual kind (type, non-type, template).
6635 if (Old->getKind() != New->getKind()) {
6636 if (Complain) {
6637 unsigned NextDiag = diag::err_template_param_different_kind;
6638 if (TemplateArgLoc.isValid()) {
6639 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6640 NextDiag = diag::note_template_param_different_kind;
6641 }
6642 S.Diag(New->getLocation(), NextDiag)
6643 << (Kind != Sema::TPL_TemplateMatch);
6644 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6645 << (Kind != Sema::TPL_TemplateMatch);
6646 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006647
Douglas Gregor641040a2011-01-12 23:45:44 +00006648 return false;
6649 }
6650
Richard Smith26b86ea2016-12-31 21:41:23 +00006651 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006652 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006653 // template template parameter, the template template parameter can have
6654 // a parameter pack where the template template argument does not.
6655 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6656 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6657 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006658 if (Complain) {
6659 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6660 if (TemplateArgLoc.isValid()) {
6661 S.Diag(TemplateArgLoc,
6662 diag::err_template_arg_template_params_mismatch);
6663 NextDiag = diag::note_template_parameter_pack_non_pack;
6664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006665
Douglas Gregor641040a2011-01-12 23:45:44 +00006666 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6667 : isa<NonTypeTemplateParmDecl>(New)? 1
6668 : 2;
6669 S.Diag(New->getLocation(), NextDiag)
6670 << ParamKind << New->isParameterPack();
6671 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6672 << ParamKind << Old->isParameterPack();
6673 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006674
Douglas Gregor641040a2011-01-12 23:45:44 +00006675 return false;
6676 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006677
Douglas Gregor641040a2011-01-12 23:45:44 +00006678 // For non-type template parameters, check the type of the parameter.
6679 if (NonTypeTemplateParmDecl *OldNTTP
6680 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6681 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006682
Douglas Gregor641040a2011-01-12 23:45:44 +00006683 // If we are matching a template template argument to a template
6684 // template parameter and one of the non-type template parameter types
Richard Smith13894182017-04-13 21:37:24 +00006685 // is dependent, then we must wait until template instantiation time
6686 // to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00006687 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith13894182017-04-13 21:37:24 +00006688 (OldNTTP->getType()->isDependentType() ||
6689 NewNTTP->getType()->isDependentType()))
Douglas Gregor641040a2011-01-12 23:45:44 +00006690 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006691
Douglas Gregor641040a2011-01-12 23:45:44 +00006692 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6693 if (Complain) {
6694 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6695 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006696 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00006697 diag::err_template_arg_template_params_mismatch);
6698 NextDiag = diag::note_template_nontype_parm_different_type;
6699 }
6700 S.Diag(NewNTTP->getLocation(), NextDiag)
6701 << NewNTTP->getType()
6702 << (Kind != Sema::TPL_TemplateMatch);
6703 S.Diag(OldNTTP->getLocation(),
6704 diag::note_template_nontype_parm_prev_declaration)
6705 << OldNTTP->getType();
6706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006707
Douglas Gregor641040a2011-01-12 23:45:44 +00006708 return false;
6709 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006710
Douglas Gregor641040a2011-01-12 23:45:44 +00006711 return true;
6712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006713
Douglas Gregor641040a2011-01-12 23:45:44 +00006714 // For template template parameters, check the template parameter types.
6715 // The template parameter lists of template template
6716 // parameters must agree.
6717 if (TemplateTemplateParmDecl *OldTTP
6718 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006719 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00006720 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6721 OldTTP->getTemplateParameters(),
6722 Complain,
6723 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006724 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00006725 : Kind),
6726 TemplateArgLoc);
6727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006728
Douglas Gregor641040a2011-01-12 23:45:44 +00006729 return true;
6730}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006731
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006732/// \brief Diagnose a known arity mismatch when comparing template argument
6733/// lists.
6734static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006735void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006736 TemplateParameterList *New,
6737 TemplateParameterList *Old,
6738 Sema::TemplateParameterListEqualKind Kind,
6739 SourceLocation TemplateArgLoc) {
6740 unsigned NextDiag = diag::err_template_param_list_different_arity;
6741 if (TemplateArgLoc.isValid()) {
6742 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6743 NextDiag = diag::note_template_param_list_different_arity;
6744 }
6745 S.Diag(New->getTemplateLoc(), NextDiag)
6746 << (New->size() > Old->size())
6747 << (Kind != Sema::TPL_TemplateMatch)
6748 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6749 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6750 << (Kind != Sema::TPL_TemplateMatch)
6751 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6752}
6753
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006754/// \brief Determine whether the given template parameter lists are
6755/// equivalent.
6756///
Mike Stump11289f42009-09-09 15:08:12 +00006757/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006758/// source code as part of a new template declaration.
6759///
6760/// \param Old The old template parameter list, typically found via
6761/// name lookup of the template declared with this template parameter
6762/// list.
6763///
6764/// \param Complain If true, this routine will produce a diagnostic if
6765/// the template parameter lists are not equivalent.
6766///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006767/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00006768///
6769/// \param TemplateArgLoc If this source location is valid, then we
6770/// are actually checking the template parameter list of a template
6771/// argument (New) against the template parameter list of its
6772/// corresponding template template parameter (Old). We produce
6773/// slightly different diagnostics in this scenario.
6774///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006775/// \returns True if the template parameter lists are equal, false
6776/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00006777bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006778Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6779 TemplateParameterList *Old,
6780 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006781 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00006782 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006783 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6784 if (Complain)
6785 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6786 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006787
6788 return false;
6789 }
6790
Douglas Gregor641040a2011-01-12 23:45:44 +00006791 // C++0x [temp.arg.template]p3:
6792 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006793 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00006794 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006795 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006796 // template-parameter-list of P. [...]
6797 TemplateParameterList::iterator NewParm = New->begin();
6798 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006799 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006800 OldParmEnd = Old->end();
6801 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00006802 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6803 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006804 if (NewParm == NewParmEnd) {
6805 if (Complain)
6806 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6807 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006808
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006809 return false;
6810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006811
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006812 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6813 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006814 return false;
6815
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006816 ++NewParm;
6817 continue;
6818 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006819
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006820 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006821 // [...] When P's template- parameter-list contains a template parameter
6822 // pack (14.5.3), the template parameter pack will match zero or more
6823 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006824 // template-parameter-list of A with the same type and form as the
6825 // template parameter pack in P (ignoring whether those template
6826 // parameters are template parameter packs).
6827 for (; NewParm != NewParmEnd; ++NewParm) {
6828 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6829 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006830 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006831 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006832 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006833
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006834 // Make sure we exhausted all of the arguments.
6835 if (NewParm != NewParmEnd) {
6836 if (Complain)
6837 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6838 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006839
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006840 return false;
6841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006842
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006843 return true;
6844}
6845
6846/// \brief Check whether a template can be declared within this scope.
6847///
6848/// If the template declaration is valid in this scope, returns
6849/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00006850bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006851Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00006852 if (!S)
6853 return false;
6854
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006855 // Find the nearest enclosing declaration scope.
6856 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6857 (S->getFlags() & Scope::TemplateParamScope) != 0)
6858 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006859
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006860 // C++ [temp]p4:
6861 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00006862 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00006863 if (Ctx && Ctx->isExternCContext()) {
6864 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6865 << TemplateParams->getSourceRange();
6866 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6867 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6868 return true;
6869 }
Richard Smith8df390f2016-09-08 23:14:54 +00006870 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006871
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006872 // C++ [temp]p2:
6873 // A template-declaration can appear only as a namespace scope or
6874 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00006875 if (Ctx) {
6876 if (Ctx->isFileContext())
6877 return false;
6878 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6879 // C++ [temp.mem]p2:
6880 // A local class shall not have member templates.
6881 if (RD->isLocalClass())
6882 return Diag(TemplateParams->getTemplateLoc(),
6883 diag::err_template_inside_local_class)
6884 << TemplateParams->getSourceRange();
6885 else
6886 return false;
6887 }
6888 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006889
Mike Stump11289f42009-09-09 15:08:12 +00006890 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006891 diag::err_template_outside_namespace_or_class_scope)
6892 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006893}
Douglas Gregor67a65642009-02-17 23:15:12 +00006894
Douglas Gregor54888652009-10-07 00:13:32 +00006895/// \brief Determine what kind of template specialization the given declaration
6896/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006897static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00006898 if (!D)
6899 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006900
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006901 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6902 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00006903 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6904 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006905 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6906 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006907
Douglas Gregor54888652009-10-07 00:13:32 +00006908 return TSK_Undeclared;
6909}
6910
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006911/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006912/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00006913///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006914/// This routine determines whether a template specialization can be declared
6915/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00006916///
6917/// \param S the semantic analysis object for which this check is being
6918/// performed.
6919///
6920/// \param Specialized the entity being specialized or instantiated, which
6921/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006922/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00006923/// member class).
6924///
6925/// \param PrevDecl the previous declaration of this entity, if any.
6926///
6927/// \param Loc the location of the explicit specialization or instantiation of
6928/// this entity.
6929///
6930/// \param IsPartialSpecialization whether this is a partial specialization of
6931/// a class template.
6932///
Douglas Gregor54888652009-10-07 00:13:32 +00006933/// \returns true if there was an error that we cannot recover from, false
6934/// otherwise.
6935static bool CheckTemplateSpecializationScope(Sema &S,
6936 NamedDecl *Specialized,
6937 NamedDecl *PrevDecl,
6938 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006939 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00006940 // Keep these "kind" numbers in sync with the %select statements in the
6941 // various diagnostics emitted by this routine.
6942 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006943 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006944 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006945 else if (isa<VarTemplateDecl>(Specialized))
6946 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006947 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006948 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006949 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006950 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006951 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00006952 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006953 else if (isa<RecordDecl>(Specialized))
6954 EntityKind = 7;
6955 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6956 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00006957 else {
Richard Smith7d137e32012-03-23 03:33:32 +00006958 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006959 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006960 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00006961 return true;
6962 }
6963
Douglas Gregorf47b9112009-02-25 22:02:03 +00006964 // C++ [temp.expl.spec]p2:
6965 // An explicit specialization shall be declared in the namespace
6966 // of which the template is a member, or, for member templates, in
6967 // the namespace of which the enclosing class or enclosing class
6968 // template is a member. An explicit specialization of a member
6969 // function, member class or static data member of a class
6970 // template shall be declared in the namespace of which the class
6971 // template is a member. Such a declaration may also be a
6972 // definition. If the declaration is not a definition, the
6973 // specialization may be defined later in the name- space in which
6974 // the explicit specialization was declared, or in a namespace
6975 // that encloses the one in which the explicit specialization was
6976 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00006977 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00006978 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006979 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006980 return true;
6981 }
Douglas Gregore4b05162009-10-07 17:21:34 +00006982
Douglas Gregor40fb7442009-10-07 17:30:37 +00006983 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006984 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006985 // Do not warn for class scope explicit specialization during
6986 // instantiation, warning was already emitted during pattern
6987 // semantic analysis.
Richard Smith51ec0cf2017-02-21 01:17:38 +00006988 if (!S.inTemplateInstantiation())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006989 S.Diag(Loc, diag::ext_function_specialization_in_class)
6990 << Specialized;
6991 } else {
6992 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6993 << Specialized;
6994 return true;
6995 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006996 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006997
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006998 if (S.CurContext->isRecord() &&
6999 !S.CurContext->Equals(Specialized->getDeclContext())) {
7000 // Make sure that we're specializing in the right record context.
7001 // Otherwise, things can go horribly wrong.
7002 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
7003 << Specialized;
7004 return true;
7005 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00007006
Douglas Gregore4b05162009-10-07 17:21:34 +00007007 // C++ [temp.class.spec]p6:
7008 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007009 // in any namespace scope in which its definition may be defined (14.5.1
7010 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00007011 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00007012 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00007013 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00007014
7015 // Make sure that this redeclaration (or definition) occurs in an enclosing
7016 // namespace.
7017 // Note that HandleDeclarator() performs this check for explicit
7018 // specializations of function templates, static data members, and member
7019 // functions, so we skip the check here for those kinds of entities.
7020 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
7021 // Should we refactor that check, so that it occurs later?
7022 if (!DC->Encloses(SpecializedContext) &&
7023 !(isa<FunctionTemplateDecl>(Specialized) ||
7024 isa<FunctionDecl>(Specialized) ||
7025 isa<VarTemplateDecl>(Specialized) ||
7026 isa<VarDecl>(Specialized))) {
7027 if (isa<TranslationUnitDecl>(SpecializedContext))
7028 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7029 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00007030 else if (isa<NamespaceDecl>(SpecializedContext)) {
7031 int Diag = diag::err_template_spec_redecl_out_of_scope;
7032 if (S.getLangOpts().MicrosoftExt)
7033 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7034 S.Diag(Loc, Diag) << EntityKind << Specialized
7035 << cast<NamedDecl>(SpecializedContext);
7036 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00007037 llvm_unreachable("unexpected namespace context for specialization");
7038
7039 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7040 } else if ((!PrevDecl ||
7041 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
7042 getTemplateSpecializationKind(PrevDecl) ==
7043 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00007044 // C++ [temp.exp.spec]p2:
7045 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007046 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00007047 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007048 // An explicit specialization of a member function, member class or
7049 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00007050 // namespace of which the class template is a member.
7051 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00007052 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007053 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00007054 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00007055 // C++11 [temp.explicit]p3:
7056 // An explicit instantiation shall appear in an enclosing namespace of its
7057 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00007058 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007059 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00007060 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007061 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00007062 "DC encloses TU but isn't in enclosing namespace set");
7063 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00007064 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00007065 } else if (isa<NamespaceDecl>(SpecializedContext)) {
7066 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007067 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007068 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007069 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007070 Diag = diag::ext_template_spec_decl_out_of_scope;
7071 else
7072 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
7073 S.Diag(Loc, Diag)
7074 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
7075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007076
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007077 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00007078 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007080
Douglas Gregorf47b9112009-02-25 22:02:03 +00007081 return false;
7082}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007083
Richard Smith57aae072016-12-28 02:37:25 +00007084static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7085 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00007086 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007087 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007088 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00007089 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007090 return E->getSourceRange();
7091 return Checker.MatchLoc;
7092}
7093
7094static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7095 if (!TL.getType()->isDependentType())
7096 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007097 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007098 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00007099 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007100 return TL.getSourceRange();
7101 return Checker.MatchLoc;
7102}
7103
Larisse Voufo39a1e502013-08-06 01:03:05 +00007104/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007105/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007106static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007107 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7108 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007109 for (unsigned I = 0; I != NumArgs; ++I) {
7110 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007111 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007112 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7113 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007114 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007115
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007116 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007117 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007118
Eli Friedmanb826a002012-09-26 02:36:12 +00007119 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007120 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00007121
7122 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007123
Douglas Gregor98318c22011-01-03 21:37:45 +00007124 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007125 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7126 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00007127
7128 // Strip off any implicit casts we added as part of type checking.
7129 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7130 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007131
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007132 // C++ [temp.class.spec]p8:
7133 // A non-type argument is non-specialized if it is the name of a
7134 // non-type parameter. All other non-type arguments are
7135 // specialized.
7136 //
7137 // Below, we check the two conditions that only apply to
7138 // specialized non-type arguments, so skip any non-specialized
7139 // arguments.
7140 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00007141 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007142 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007143
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007144 // C++ [temp.class.spec]p9:
7145 // Within the argument list of a class template partial
7146 // specialization, the following restrictions apply:
7147 // -- A partially specialized non-type argument expression
7148 // shall not involve a template parameter of the partial
7149 // specialization except when the argument expression is a
7150 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00007151 // -- The type of a template parameter corresponding to a
7152 // specialized non-type argument shall not be dependent on a
7153 // parameter of the specialization.
7154 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7155 // We implement a compromise between the original rules and DR1315:
7156 // -- A specialized non-type template argument shall not be
7157 // type-dependent and the corresponding template parameter
7158 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00007159 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00007160 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00007161 if (ParamUseRange.isValid()) {
7162 if (IsDefaultArgument) {
7163 S.Diag(TemplateNameLoc,
7164 diag::err_dependent_non_type_arg_in_partial_spec);
7165 S.Diag(ParamUseRange.getBegin(),
7166 diag::note_dependent_non_type_default_arg_in_partial_spec)
7167 << ParamUseRange;
7168 } else {
7169 S.Diag(ParamUseRange.getBegin(),
7170 diag::err_dependent_non_type_arg_in_partial_spec)
7171 << ParamUseRange;
7172 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007173 return true;
7174 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007175
Richard Smith6056d5e2014-02-09 00:54:43 +00007176 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00007177 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00007178 if (ParamUseRange.isValid()) {
7179 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7180 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Richard Smith57aae072016-12-28 02:37:25 +00007181 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00007182 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00007183 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7184 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007185 return true;
7186 }
7187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007188
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007189 return false;
7190}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007191
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007192/// \brief Check the non-type template arguments of a class template
7193/// partial specialization according to C++ [temp.class.spec]p9.
7194///
Richard Smith6056d5e2014-02-09 00:54:43 +00007195/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00007196/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00007197/// template.
7198/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00007199/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00007200/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007201///
Richard Smith6056d5e2014-02-09 00:54:43 +00007202/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00007203bool Sema::CheckTemplatePartialSpecializationArgs(
7204 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7205 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7206 // We have to be conservative when checking a template in a dependent
7207 // context.
7208 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7209 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007210
Richard Smith57aae072016-12-28 02:37:25 +00007211 TemplateParameterList *TemplateParams =
7212 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007213 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7214 NonTypeTemplateParmDecl *Param
7215 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7216 if (!Param)
7217 continue;
7218
Richard Smith57aae072016-12-28 02:37:25 +00007219 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7220 Param, &TemplateArgs[I],
7221 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007222 return true;
7223 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007224
7225 return false;
7226}
7227
John McCall48871652010-08-21 09:40:31 +00007228DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00007229Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
7230 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00007231 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007232 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007233 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00007234 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00007235 MultiTemplateParamsArg
7236 TemplateParameterLists,
7237 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007238 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007239
Richard Smith4b55a9c2014-04-17 03:29:33 +00007240 CXXScopeSpec &SS = TemplateId.SS;
7241
Abramo Bagnara60804e12011-03-18 15:16:37 +00007242 // NOTE: KWLoc is the location of the tag keyword. This will instead
7243 // store the location of the outermost template keyword in the declaration.
7244 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007245 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7246 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7247 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7248 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007249
Douglas Gregor67a65642009-02-17 23:15:12 +00007250 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007251 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007252 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007253 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7254
7255 if (!ClassTemplate) {
7256 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007257 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007258 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7259 return true;
7260 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007261
Richard Smithf445f192017-02-09 21:04:43 +00007262 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007263 bool isPartialSpecialization = false;
7264
Douglas Gregorf47b9112009-02-25 22:02:03 +00007265 // Check the validity of the template headers that introduce this
7266 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007267 // FIXME: We probably shouldn't complain about these headers for
7268 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007269 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007270 TemplateParameterList *TemplateParams =
7271 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007272 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007273 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007274 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007275 if (Invalid)
7276 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007277
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007278 if (TemplateParams && TemplateParams->size() > 0) {
7279 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007280
Douglas Gregorec9518b2010-12-21 08:14:57 +00007281 if (TUK == TUK_Friend) {
7282 Diag(KWLoc, diag::err_partial_specialization_friend)
7283 << SourceRange(LAngleLoc, RAngleLoc);
7284 return true;
7285 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007286
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007287 // C++ [temp.class.spec]p10:
7288 // The template parameter list of a specialization shall not
7289 // contain default template argument values.
7290 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7291 Decl *Param = TemplateParams->getParam(I);
7292 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7293 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007294 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007295 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007296 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007297 }
7298 } else if (NonTypeTemplateParmDecl *NTTP
7299 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7300 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007301 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007302 diag::err_default_arg_in_partial_spec)
7303 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007304 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007305 }
7306 } else {
7307 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007308 if (TTP->hasDefaultArgument()) {
7309 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007310 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007311 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007312 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007313 }
7314 }
7315 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007316 } else if (TemplateParams) {
7317 if (TUK == TUK_Friend)
7318 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007319 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007320 SourceRange(TemplateParams->getTemplateLoc(),
7321 TemplateParams->getRAngleLoc()))
7322 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007323 } else {
7324 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007325 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007326
Douglas Gregor67a65642009-02-17 23:15:12 +00007327 // Check that the specialization uses the same tag kind as the
7328 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007329 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7330 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007331 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007332 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007333 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007334 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007335 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007336 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007337 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007338 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007339 diag::note_previous_use);
7340 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7341 }
7342
Douglas Gregorc40290e2009-03-09 23:48:35 +00007343 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007344 TemplateArgumentListInfo TemplateArgs =
7345 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007346
Douglas Gregor14406932011-01-03 20:35:03 +00007347 // Check for unexpanded parameter packs in any of the template arguments.
7348 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007349 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007350 UPPC_PartialSpecialization))
7351 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007352
Douglas Gregor67a65642009-02-17 23:15:12 +00007353 // Check that the template argument list is well-formed for this
7354 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007355 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007356 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7357 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007358 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007359
Douglas Gregor2373c592009-05-31 09:31:02 +00007360 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007361 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007362 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007363 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7364 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007365 return true;
7366
Richard Smith57aae072016-12-28 02:37:25 +00007367 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7368 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007369 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007370 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007371 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007372 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007373 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7374 << ClassTemplate->getDeclName();
7375 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007376 }
7377 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007378
Craig Topperc3ec1492014-05-26 06:22:03 +00007379 void *InsertPos = nullptr;
7380 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007381
7382 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007383 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007384 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007385 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007386 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007387
Craig Topperc3ec1492014-05-26 06:22:03 +00007388 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007389
Douglas Gregorf47b9112009-02-25 22:02:03 +00007390 // Check whether we can declare a class template specialization in
7391 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007392 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007393 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7394 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007395 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007396 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007397
Douglas Gregor15301382009-07-30 17:40:51 +00007398 // The canonical type
7399 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007400 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007401 // Build the canonical type that describes the converted template
7402 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007403 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7404 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007405 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007406
7407 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007408 ClassTemplate->getInjectedClassNameSpecialization())) {
7409 // C++ [temp.class.spec]p9b3:
7410 //
7411 // -- The argument list of the specialization shall not be identical
7412 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007413 //
7414 // This rule has since been removed, because it's redundant given DR1495,
7415 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007416 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007417 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007418 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007419 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7420 ClassTemplate->getIdentifier(),
7421 TemplateNameLoc,
7422 Attr,
7423 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007424 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007425 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007426 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007427 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007428 }
Douglas Gregor15301382009-07-30 17:40:51 +00007429
Douglas Gregor2373c592009-05-31 09:31:02 +00007430 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007431 ClassTemplatePartialSpecializationDecl *PrevPartial
7432 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007433 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007434 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007435 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007436 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007437 TemplateParams,
7438 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007439 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007440 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007441 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007442 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00007443 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007444 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007445 Partial->setTemplateParameterListsInfo(
7446 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007447 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007448
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007449 if (!PrevPartial)
7450 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007451 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007452
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007453 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007454 // template specialization, make a note of that.
7455 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7456 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007457
Richard Smith57aae072016-12-28 02:37:25 +00007458 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007459 } else {
7460 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007461 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007462 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007463 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007464 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007465 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007466 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007467 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007468 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007469 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007470 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007471 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007472 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007473 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007474
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007475 if (!PrevDecl)
7476 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007477
David Majnemer678f50b2015-11-18 19:49:19 +00007478 if (CurContext->isDependentContext()) {
7479 // -fms-extensions permits specialization of nested classes without
7480 // fully specializing the outer class(es).
7481 assert(getLangOpts().MicrosoftExt &&
7482 "Only possible with -fms-extensions!");
7483 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7484 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007485 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007486 } else {
7487 CanonType = Context.getTypeDeclType(Specialization);
7488 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007489 }
7490
Douglas Gregor06db9f52009-10-12 20:18:28 +00007491 // C++ [temp.expl.spec]p6:
7492 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007493 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007494 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007495 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007496 // use occurs; no diagnostic is required.
7497 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007498 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007499 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007500 // Is there any previous explicit specialization declaration?
7501 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7502 Okay = true;
7503 break;
7504 }
7505 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007506
Douglas Gregorc854c662010-02-26 06:03:23 +00007507 if (!Okay) {
7508 SourceRange Range(TemplateNameLoc, RAngleLoc);
7509 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7510 << Context.getTypeDeclType(Specialization) << Range;
7511
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007512 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007513 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007514 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007515 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007516 return true;
7517 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007518 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007519
Douglas Gregor2208a292009-09-26 20:57:03 +00007520 // If this is not a friend, note that this is an explicit specialization.
7521 if (TUK != TUK_Friend)
7522 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007523
7524 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007525 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007526 RecordDecl *Def = Specialization->getDefinition();
7527 NamedDecl *Hidden = nullptr;
7528 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7529 SkipBody->ShouldSkip = true;
Richard Smith858e0e02017-05-11 23:11:16 +00007530 makeMergedDefinitionVisible(Hidden);
Richard Smithc7e6ff02015-05-18 20:36:47 +00007531 // From here on out, treat this as just a redeclaration.
7532 TUK = TUK_Declaration;
7533 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007534 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007535 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007536 Diag(Def->getLocation(), diag::note_previous_definition);
7537 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007538 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007539 }
7540 }
7541
John McCall659a3372010-12-18 03:30:47 +00007542 if (Attr)
7543 ProcessDeclAttributeList(S, Specialization, Attr);
7544
Richard Smith034b94a2012-08-17 03:20:55 +00007545 // Add alignment attributes if necessary; these attributes are checked when
7546 // the ASTContext lays out the structure.
7547 if (TUK == TUK_Definition) {
7548 AddAlignmentAttributesForRecord(Specialization);
7549 AddMsStructLayoutForRecord(Specialization);
7550 }
7551
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007552 if (ModulePrivateLoc.isValid())
7553 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7554 << (isPartialSpecialization? 1 : 0)
7555 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007556
Douglas Gregord56a91e2009-02-26 22:19:44 +00007557 // Build the fully-sugared type for this class template
7558 // specialization as the user wrote in the specialization
7559 // itself. This means that we'll pretty-print the type retrieved
7560 // from the specialization's declaration the way that the user
7561 // actually wrote the specialization, rather than formatting the
7562 // name based on the "canonical" representation used to store the
7563 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007564 TypeSourceInfo *WrittenTy
7565 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7566 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007567 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007568 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007569 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007570 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007571
Douglas Gregor1e249f82009-02-25 22:18:32 +00007572 // C++ [temp.expl.spec]p9:
7573 // A template explicit specialization is in the scope of the
7574 // namespace in which the template was defined.
7575 //
7576 // We actually implement this paragraph where we set the semantic
7577 // context (in the creation of the ClassTemplateSpecializationDecl),
7578 // but we also maintain the lexical context where the actual
7579 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007580 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007581
Douglas Gregor67a65642009-02-17 23:15:12 +00007582 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007583 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00007584 Specialization->startDefinition();
7585
Douglas Gregor2208a292009-09-26 20:57:03 +00007586 if (TUK == TUK_Friend) {
7587 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7588 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007589 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007590 /*FIXME:*/KWLoc);
7591 Friend->setAccess(AS_public);
7592 CurContext->addDecl(Friend);
7593 } else {
7594 // Add the specialization into its lexical context, so that it can
7595 // be seen when iterating through the list of declarations in that
7596 // context. However, specializations are not found by name lookup.
7597 CurContext->addDecl(Specialization);
7598 }
John McCall48871652010-08-21 09:40:31 +00007599 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007600}
Douglas Gregor333489b2009-03-27 23:10:48 +00007601
John McCall48871652010-08-21 09:40:31 +00007602Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007603 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007604 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007605 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007606 ActOnDocumentableDecl(NewDecl);
7607 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007608}
7609
John McCall4f7ced62010-02-11 01:33:53 +00007610/// \brief Strips various properties off an implicit instantiation
7611/// that has just been explicitly specialized.
7612static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007613 D->dropAttr<DLLImportAttr>();
7614 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007615
Nico Webere4974382014-12-19 23:52:45 +00007616 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007617 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007618}
7619
Nico Webera8f80b32012-01-09 19:52:25 +00007620/// \brief Compute the diagnostic location for an explicit instantiation
7621// declaration or definition.
7622static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007623 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007624 // Explicit instantiations following a specialization have no effect and
7625 // hence no PointOfInstantiation. In that case, walk decl backwards
7626 // until a valid name loc is found.
7627 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007628 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7629 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007630 PrevDiagLoc = Prev->getLocation();
7631 }
7632 assert(PrevDiagLoc.isValid() &&
7633 "Explicit instantiation without point of instantiation?");
7634 return PrevDiagLoc;
7635}
7636
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007637/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007638/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007639/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007640/// new specialization/instantiation will have any effect.
7641///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007642/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007643/// instantiation.
7644///
7645/// \param NewTSK the kind of the new explicit specialization or instantiation.
7646///
7647/// \param PrevDecl the previous declaration of the entity.
7648///
7649/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7650///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007651/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007652/// declaration was instantiated (either implicitly or explicitly).
7653///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007654/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007655/// specialization or instantiation has no effect and should be ignored.
7656///
7657/// \returns true if there was an error that should prevent the introduction of
7658/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007659bool
7660Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7661 TemplateSpecializationKind NewTSK,
7662 NamedDecl *PrevDecl,
7663 TemplateSpecializationKind PrevTSK,
7664 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007665 bool &HasNoEffect) {
7666 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007667
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007668 switch (NewTSK) {
7669 case TSK_Undeclared:
7670 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007671 assert(
7672 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7673 "previous declaration must be implicit!");
7674 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007675
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007676 case TSK_ExplicitSpecialization:
7677 switch (PrevTSK) {
7678 case TSK_Undeclared:
7679 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007680 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007681 // explicitly specialized or has merely been mentioned without any
7682 // instantiation.
7683 return false;
7684
7685 case TSK_ImplicitInstantiation:
7686 if (PrevPointOfInstantiation.isInvalid()) {
7687 // The declaration itself has not actually been instantiated, so it is
7688 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007689 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007690 return false;
7691 }
7692 // Fall through
Galina Kistanova3779cb32017-06-07 06:25:05 +00007693 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007694
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007695 case TSK_ExplicitInstantiationDeclaration:
7696 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007697 assert((PrevTSK == TSK_ImplicitInstantiation ||
7698 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007699 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007700
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007701 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007702 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007703 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007704 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007705 // implicit instantiation to take place, in every translation unit in
7706 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007707 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007708 // Is there any previous explicit specialization declaration?
7709 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7710 return false;
7711 }
7712
Douglas Gregor1d957a32009-10-27 18:42:08 +00007713 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007714 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007715 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007716 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007717
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007718 return true;
7719 }
Galina Kistanova1d36e832017-06-08 18:20:32 +00007720 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007721
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007722 case TSK_ExplicitInstantiationDeclaration:
7723 switch (PrevTSK) {
7724 case TSK_ExplicitInstantiationDeclaration:
7725 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007726 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007727 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007728
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007729 case TSK_Undeclared:
7730 case TSK_ImplicitInstantiation:
7731 // We're explicitly instantiating something that may have already been
7732 // implicitly instantiated; that's fine.
7733 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007734
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007735 case TSK_ExplicitSpecialization:
7736 // C++0x [temp.explicit]p4:
7737 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007738 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007739 // specialization for that template, the explicit instantiation has no
7740 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007741 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007742 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007743
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007744 case TSK_ExplicitInstantiationDefinition:
7745 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007746 // If an entity is the subject of both an explicit instantiation
7747 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007748 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007749 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007750 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007751
7752 // Explicit instantiations following a specialization have no effect and
7753 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7754 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007755 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7756 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007757 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007758 return false;
7759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007760
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007761 case TSK_ExplicitInstantiationDefinition:
7762 switch (PrevTSK) {
7763 case TSK_Undeclared:
7764 case TSK_ImplicitInstantiation:
7765 // We're explicitly instantiating something that may have already been
7766 // implicitly instantiated; that's fine.
7767 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007768
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007769 case TSK_ExplicitSpecialization:
7770 // C++ DR 259, C++0x [temp.explicit]p4:
7771 // For a given set of template parameters, if an explicit
7772 // instantiation of a template appears after a declaration of
7773 // an explicit specialization for that template, the explicit
7774 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00007775 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007776 << PrevDecl;
7777 Diag(PrevDecl->getLocation(),
7778 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007779 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007780 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007781
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007782 case TSK_ExplicitInstantiationDeclaration:
7783 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007784 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00007785
7786 // C++0x [temp.explicit]p4:
7787 // For a given set of template parameters, if an explicit instantiation
7788 // of a template appears after a declaration of an explicit
7789 // specialization for that template, the explicit instantiation has no
7790 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007791 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00007792 // Is there any previous explicit specialization declaration?
7793 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7794 HasNoEffect = true;
7795 break;
7796 }
7797 }
7798
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007799 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007800
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007801 case TSK_ExplicitInstantiationDefinition:
7802 // C++0x [temp.spec]p5:
7803 // For a given template and a given set of template-arguments,
7804 // - an explicit instantiation definition shall appear at most once
7805 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007806
7807 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7808 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00007809 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007810 : diag::err_explicit_instantiation_duplicate)
7811 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00007812 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00007813 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007814 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007815 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007816 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007818
David Blaikie83d382b2011-09-23 05:06:16 +00007819 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007820}
7821
John McCallb9c78482010-04-08 09:05:18 +00007822/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00007823/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00007824///
James Dennettf14a6e52012-06-15 22:23:43 +00007825/// The only possible way to get a dependent function template specialization
7826/// is with a friend declaration, like so:
7827///
7828/// \code
7829/// template \<class T> void foo(T);
7830/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00007831/// friend void foo<>(T);
7832/// };
James Dennettf14a6e52012-06-15 22:23:43 +00007833/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00007834///
7835/// There really isn't any useful analysis we can do here, so we
7836/// just store the information.
7837bool
7838Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7839 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7840 LookupResult &Previous) {
7841 // Remove anything from Previous that isn't a function template in
7842 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00007843 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00007844 LookupResult::Filter F = Previous.makeFilter();
7845 while (F.hasNext()) {
7846 NamedDecl *D = F.next()->getUnderlyingDecl();
7847 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00007848 !FDLookupContext->InEnclosingNamespaceSetOf(
7849 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00007850 F.erase();
7851 }
7852 F.done();
7853
7854 // Should this be diagnosed here?
7855 if (Previous.empty()) return true;
7856
7857 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7858 ExplicitTemplateArgs);
7859 return false;
7860}
7861
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007862/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007863/// specialization.
7864///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007865/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007866/// explicit function template specialization. On successful completion,
7867/// the function declaration \p FD will become a function template
7868/// specialization.
7869///
7870/// \param FD the function declaration, which will be updated to become a
7871/// function template specialization.
7872///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007873/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7874/// if any. Note that this may be valid info even when 0 arguments are
7875/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7876/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007877///
Francois Pichet3a44e432011-07-08 06:21:47 +00007878/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007879/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007880bool Sema::CheckFunctionTemplateSpecialization(
7881 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7882 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007883 // The set of function template specializations that could match this
7884 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00007885 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007886 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7887 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007888
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007889 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7890 ConvertedTemplateArgs;
7891
Sebastian Redl50c68252010-08-31 00:36:30 +00007892 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00007893 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7894 I != E; ++I) {
7895 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7896 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007897 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007898 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007899 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7900 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007901 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007902
Richard Smith574f4f62013-01-14 05:37:29 +00007903 // When matching a constexpr member function template specialization
7904 // against the primary template, we don't yet know whether the
7905 // specialization has an implicit 'const' (because we don't know whether
7906 // it will be a static member function until we know which template it
7907 // specializes), so adjust it now assuming it specializes this template.
7908 QualType FT = FD->getType();
7909 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007910 CXXMethodDecl *OldMD =
7911 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00007912 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007913 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00007914 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7915 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007916 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007917 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00007918 }
7919 }
7920
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007921 TemplateArgumentListInfo Args;
7922 if (ExplicitTemplateArgs)
7923 Args = *ExplicitTemplateArgs;
7924
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007925 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007926 // A trailing template-argument can be left unspecified in the
7927 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007928 // provided it can be deduced from the function argument type.
7929 // Perform template argument deduction to determine whether we may be
7930 // specializing this template.
7931 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00007932 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007933 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00007934 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7935 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00007936 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7937 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007938 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007939 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00007940 FailedCandidates.addCandidate().set(
7941 I.getPair(), FunTmpl->getTemplatedDecl(),
7942 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007943 (void)TDK;
7944 continue;
7945 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007946
Artem Belevich64135c32016-12-08 19:38:13 +00007947 // Target attributes are part of the cuda function signature, so
7948 // the deduced template's cuda target must match that of the
7949 // specialization. Given that C++ template deduction does not
7950 // take target attributes into account, we reject candidates
7951 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007952 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00007953 IdentifyCUDATarget(Specialization,
7954 /* IgnoreImplicitHDAttributes = */ true) !=
7955 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007956 FailedCandidates.addCandidate().set(
7957 I.getPair(), FunTmpl->getTemplatedDecl(),
7958 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7959 continue;
7960 }
7961
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007962 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007963 if (ExplicitTemplateArgs)
7964 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00007965 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007966 }
7967 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007968
Douglas Gregor5de279c2009-09-26 03:41:46 +00007969 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007970 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007971 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007972 FD->getLocation(),
7973 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7974 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00007975 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007976 PDiag(diag::note_function_template_spec_matched));
7977
John McCall58cc69d2010-01-27 01:50:18 +00007978 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007979 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007980
7981 // Ignore access information; it doesn't figure into redeclaration checking.
7982 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007983
Nathan Wilson83839122016-04-09 02:55:27 +00007984 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7985 // an explicit specialization (14.8.3) [...] of a concept definition.
7986 if (Specialization->getPrimaryTemplate()->isConcept()) {
7987 Diag(FD->getLocation(), diag::err_concept_specialized)
7988 << 0 /*function*/ << 1 /*explicitly specialized*/;
7989 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7990 return true;
7991 }
7992
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007993 FunctionTemplateSpecializationInfo *SpecInfo
7994 = Specialization->getTemplateSpecializationInfo();
7995 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007996
7997 // Note: do not overwrite location info if previous template
7998 // specialization kind was explicit.
7999 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00008000 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00008001 Specialization->setLocation(FD->getLocation());
Richard Smith54f04402017-05-18 02:29:20 +00008002 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
Richard Smith5b8b3db2012-02-20 23:28:05 +00008003 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8004 // function can differ from the template declaration with respect to
8005 // the constexpr specifier.
Richard Smith77e9e842017-05-09 23:02:10 +00008006 // FIXME: We need an update record for this AST mutation.
8007 // FIXME: What if there are multiple such prior declarations (for instance,
8008 // from different modules)?
Richard Smith5b8b3db2012-02-20 23:28:05 +00008009 Specialization->setConstexpr(FD->isConstexpr());
8010 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008011
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008012 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00008013 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00008014
8015 // If this is a friend declaration, then we're not really declaring
8016 // an explicit specialization.
8017 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008018
Douglas Gregor54888652009-10-07 00:13:32 +00008019 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00008020 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008021 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00008022 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008023 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008024 false))
Douglas Gregor54888652009-10-07 00:13:32 +00008025 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008026
8027 // C++ [temp.expl.spec]p6:
8028 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008029 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008030 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008031 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008032 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008033 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00008034 if (!isFriend &&
8035 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00008036 TSK_ExplicitSpecialization,
8037 Specialization,
8038 SpecInfo->getTemplateSpecializationKind(),
8039 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008040 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008041 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008042
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008043 // Mark the prior declaration as an explicit specialization, so that later
8044 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008045 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00008046 // Since explicit specializations do not inherit '=delete' from their
8047 // primary function template - check if the 'specialization' that was
8048 // implicitly generated (during template argument deduction for partial
8049 // ordering) from the most specialized of all the function templates that
8050 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8051 // first check that it was implicitly generated during template argument
8052 // deduction by making sure it wasn't referenced, and then reset the deleted
8053 // flag to not-deleted, so that we can inherit that information from 'FD'.
8054 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8055 !Specialization->getCanonicalDecl()->isReferenced()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008056 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali81a88be2016-06-14 03:23:15 +00008057 assert(
8058 Specialization->getCanonicalDecl() == Specialization &&
8059 "This must be the only existing declaration of this specialization");
Richard Smith77e9e842017-05-09 23:02:10 +00008060 // FIXME: We need an update record for this AST mutation.
Faisal Vali81a88be2016-06-14 03:23:15 +00008061 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008062 }
Richard Smith54f04402017-05-18 02:29:20 +00008063 // FIXME: We need an update record for this AST mutation.
John McCall816d75b2010-03-24 07:46:06 +00008064 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008065 MarkUnusedFileScopedDecl(Specialization);
8066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008067
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008068 // Turn the given function declaration into a function template
8069 // specialization, with the template arguments from the previous
8070 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008071 // Take copies of (semantic and syntactic) template argument lists.
8072 const TemplateArgumentList* TemplArgs = new (Context)
8073 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008074 FD->setFunctionTemplateSpecialization(
8075 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8076 SpecInfo->getTemplateSpecializationKind(),
8077 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008078
Artem Belevich64135c32016-12-08 19:38:13 +00008079 // A function template specialization inherits the target attributes
8080 // of its template. (We require the attributes explicitly in the
8081 // code to match, but a template may have implicit attributes by
8082 // virtue e.g. of being constexpr, and it passes these implicit
8083 // attributes on to its specializations.)
8084 if (LangOpts.CUDA)
8085 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8086
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008087 // The "previous declaration" for this function template specialization is
8088 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00008089 Previous.clear();
8090 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008091 return false;
8092}
8093
Douglas Gregor86d142a2009-10-08 07:24:58 +00008094/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008095/// specialization.
8096///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008097/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008098/// explicit member function specialization. On successful completion,
8099/// the function declaration \p FD will become a member function
8100/// specialization.
8101///
Douglas Gregor86d142a2009-10-08 07:24:58 +00008102/// \param Member the member declaration, which will be updated to become a
8103/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008104///
John McCall1f82f242009-11-18 22:49:29 +00008105/// \param Previous the set of declarations, one of which may be specialized
8106/// by this function specialization; the set will be modified to contain the
8107/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008108bool
John McCall1f82f242009-11-18 22:49:29 +00008109Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008110 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00008111
Douglas Gregor86d142a2009-10-08 07:24:58 +00008112 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00008113 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00008114 NamedDecl *Instantiation = nullptr;
8115 NamedDecl *InstantiatedFrom = nullptr;
8116 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008117
John McCall1f82f242009-11-18 22:49:29 +00008118 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008119 // Nowhere to look anyway.
8120 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008121 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8122 I != E; ++I) {
8123 NamedDecl *D = (*I)->getUnderlyingDecl();
8124 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00008125 QualType Adjusted = Function->getType();
8126 if (!hasExplicitCallingConv(Adjusted))
8127 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8128 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008129 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008130 Instantiation = Method;
8131 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008132 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008133 break;
8134 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008135 }
8136 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00008137 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008138 VarDecl *PrevVar;
8139 if (Previous.isSingleResult() &&
8140 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00008141 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008142 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008143 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008144 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008145 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008146 }
8147 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008148 CXXRecordDecl *PrevRecord;
8149 if (Previous.isSingleResult() &&
8150 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008151 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008152 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008153 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008154 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008155 }
Richard Smith7d137e32012-03-23 03:33:32 +00008156 } else if (isa<EnumDecl>(Member)) {
8157 EnumDecl *PrevEnum;
8158 if (Previous.isSingleResult() &&
8159 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008160 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00008161 Instantiation = PrevEnum;
8162 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8163 MSInfo = PrevEnum->getMemberSpecializationInfo();
8164 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008166
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008167 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008168 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008169 // specializations are always out-of-line, the caller will complain about
8170 // this mismatch later.
8171 return false;
8172 }
John McCalle820e5e2010-04-13 20:37:33 +00008173
Richard Smith77e9e842017-05-09 23:02:10 +00008174 // A member specialization in a friend declaration isn't really declaring
8175 // an explicit specialization, just identifying a specific (possibly implicit)
8176 // specialization. Don't change the template specialization kind.
8177 //
8178 // FIXME: Is this really valid? Other compilers reject.
John McCalle820e5e2010-04-13 20:37:33 +00008179 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8180 // Preserve instantiation information.
8181 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8182 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8183 cast<CXXMethodDecl>(InstantiatedFrom),
8184 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8185 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8186 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8187 cast<CXXRecordDecl>(InstantiatedFrom),
8188 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8189 }
8190
8191 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008192 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00008193 return false;
8194 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008195
Douglas Gregor86d142a2009-10-08 07:24:58 +00008196 // Make sure that this is a specialization of a member.
8197 if (!InstantiatedFrom) {
8198 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8199 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008200 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8201 return true;
8202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008203
Douglas Gregor06db9f52009-10-12 20:18:28 +00008204 // C++ [temp.expl.spec]p6:
8205 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00008206 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008207 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008208 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008209 // use occurs; no diagnostic is required.
8210 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00008211
Abramo Bagnara8075c852010-06-12 07:44:57 +00008212 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00008213 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8214 TSK_ExplicitSpecialization,
8215 Instantiation,
8216 MSInfo->getTemplateSpecializationKind(),
8217 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008218 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008219 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008220
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008221 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008222 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008223 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008224 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008225 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008226 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008227
Richard Smith77e9e842017-05-09 23:02:10 +00008228 // Note that this member specialization is an "instantiation of" the
8229 // corresponding member of the original template.
8230 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008231 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8232 if (InstantiationFunction->getTemplateSpecializationKind() ==
8233 TSK_ImplicitInstantiation) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008234 // Explicit specializations of member functions of class templates do not
8235 // inherit '=delete' from the member function they are specializing.
8236 if (InstantiationFunction->isDeleted()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008237 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008238 assert(InstantiationFunction->getCanonicalDecl() ==
8239 InstantiationFunction);
Richard Smith77e9e842017-05-09 23:02:10 +00008240 // FIXME: We need an update record for this AST mutation.
Richard Smith5f274382016-09-28 23:55:27 +00008241 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008242 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008243 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008244
Richard Smith77e9e842017-05-09 23:02:10 +00008245 MemberFunction->setInstantiationOfMemberFunction(
8246 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8247 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8248 MemberVar->setInstantiationOfStaticDataMember(
Larisse Voufo39a1e502013-08-06 01:03:05 +00008249 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008250 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8251 MemberClass->setInstantiationOfMemberClass(
8252 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8253 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8254 MemberEnum->setInstantiationOfMemberEnum(
Richard Smith7d137e32012-03-23 03:33:32 +00008255 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008256 } else {
8257 llvm_unreachable("unknown member specialization kind");
Douglas Gregor86d142a2009-10-08 07:24:58 +00008258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008259
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008260 // Save the caller the trouble of having to figure out which declaration
8261 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008262 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008263 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008264 return false;
8265}
8266
Richard Smith77e9e842017-05-09 23:02:10 +00008267/// Complete the explicit specialization of a member of a class template by
8268/// updating the instantiated member to be marked as an explicit specialization.
8269///
8270/// \param OrigD The member declaration instantiated from the template.
8271/// \param Loc The location of the explicit specialization of the member.
8272template<typename DeclT>
8273static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8274 SourceLocation Loc) {
8275 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8276 return;
8277
8278 // FIXME: Inform AST mutation listeners of this AST mutation.
8279 // FIXME: If there are multiple in-class declarations of the member (from
8280 // multiple modules, or a declaration and later definition of a member type),
8281 // should we update all of them?
8282 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8283 OrigD->setLocation(Loc);
8284}
8285
8286void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8287 LookupResult &Previous) {
8288 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8289 if (Instantiation == Member)
8290 return;
8291
8292 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8293 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8294 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8295 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8296 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8297 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8298 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8299 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8300 else
8301 llvm_unreachable("unknown member specialization kind");
8302}
8303
Douglas Gregore47f5a72009-10-14 23:41:34 +00008304/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008305///
8306/// \returns true if a serious error occurs, false otherwise.
8307static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008308 SourceLocation InstLoc,
8309 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008310 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8311 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008312
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008313 if (CurContext->isRecord()) {
8314 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8315 << D;
8316 return true;
8317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008318
Richard Smith050d2612011-10-18 02:28:33 +00008319 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008320 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008321 // template. If the name declared in the explicit instantiation is an
8322 // unqualified name, the explicit instantiation shall appear in the
8323 // namespace where its template is declared or, if that namespace is inline
8324 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008325 //
8326 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008327 if (WasQualifiedName) {
8328 if (CurContext->Encloses(OrigContext))
8329 return false;
8330 } else {
8331 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8332 return false;
8333 }
8334
8335 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8336 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008337 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008338 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008339 diag::err_explicit_instantiation_out_of_scope :
8340 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008341 << D << NS;
8342 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008343 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008344 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008345 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8346 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8347 << D << NS;
8348 } else
8349 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008350 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008351 diag::err_explicit_instantiation_must_be_global :
8352 diag::warn_explicit_instantiation_must_be_global_0x)
8353 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008354 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008355 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008356}
8357
8358/// \brief Determine whether the given scope specifier has a template-id in it.
8359static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8360 if (!SS.isSet())
8361 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008362
Richard Smith050d2612011-10-18 02:28:33 +00008363 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008364 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008365 // or a static data member of a class template specialization, the name of
8366 // the class template specialization in the qualified-id for the member
8367 // name shall be a simple-template-id.
8368 //
8369 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008370 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8371 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008372 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008373 if (isa<TemplateSpecializationType>(T))
8374 return true;
8375
8376 return false;
8377}
8378
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008379/// Make a dllexport or dllimport attr on a class template specialization take
8380/// effect.
8381static void dllExportImportClassTemplateSpecialization(
8382 Sema &S, ClassTemplateSpecializationDecl *Def) {
8383 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8384 assert(A && "dllExportImportClassTemplateSpecialization called "
8385 "on Def without dllexport or dllimport");
8386
8387 // We reject explicit instantiations in class scope, so there should
8388 // never be any delayed exported classes to worry about.
8389 assert(S.DelayedDllExportClasses.empty() &&
8390 "delayed exports present at explicit instantiation");
8391 S.checkClassLevelDLLAttribute(Def);
8392
8393 // Propagate attribute to base class templates.
8394 for (auto &B : Def->bases()) {
8395 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8396 B.getType()->getAsCXXRecordDecl()))
8397 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8398 }
8399
8400 S.referenceDLLExportedClassMethods();
8401}
8402
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008403// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00008404DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008405Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008406 SourceLocation ExternLoc,
8407 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008408 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00008409 SourceLocation KWLoc,
8410 const CXXScopeSpec &SS,
8411 TemplateTy TemplateD,
8412 SourceLocation TemplateNameLoc,
8413 SourceLocation LAngleLoc,
8414 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00008415 SourceLocation RAngleLoc,
8416 AttributeList *Attr) {
8417 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008418 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008419 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008420 // Check that the specialization uses the same tag kind as the
8421 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008422 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8423 assert(Kind != TTK_Enum &&
8424 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008425
Richard Trieu265c3442016-04-05 21:13:54 +00008426 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8427
8428 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008429 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8430 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008431 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008432 return true;
8433 }
8434
Douglas Gregord9034f02009-05-14 16:41:31 +00008435 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008436 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008437 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008438 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008439 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008440 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008441 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008442 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008443 diag::note_previous_use);
8444 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8445 }
8446
Douglas Gregore47f5a72009-10-14 23:41:34 +00008447 // C++0x [temp.explicit]p2:
8448 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008449 // definition and an explicit instantiation declaration. An explicit
8450 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008451 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8452 ? TSK_ExplicitInstantiationDefinition
8453 : TSK_ExplicitInstantiationDeclaration;
8454
8455 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8456 // Check for dllexport class template instantiation declarations.
8457 for (AttributeList *A = Attr; A; A = A->getNext()) {
8458 if (A->getKind() == AttributeList::AT_DLLExport) {
8459 Diag(ExternLoc,
8460 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8461 Diag(A->getLoc(), diag::note_attribute);
8462 break;
8463 }
8464 }
8465
8466 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8467 Diag(ExternLoc,
8468 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8469 Diag(A->getLocation(), diag::note_attribute);
8470 }
8471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008472
Hans Wennborga86a83b2016-05-26 19:42:56 +00008473 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8474 // instantiation declarations for most purposes.
8475 bool DLLImportExplicitInstantiationDef = false;
8476 if (TSK == TSK_ExplicitInstantiationDefinition &&
8477 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8478 // Check for dllimport class template instantiation definitions.
8479 bool DLLImport =
8480 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8481 for (AttributeList *A = Attr; A; A = A->getNext()) {
8482 if (A->getKind() == AttributeList::AT_DLLImport)
8483 DLLImport = true;
8484 if (A->getKind() == AttributeList::AT_DLLExport) {
8485 // dllexport trumps dllimport here.
8486 DLLImport = false;
8487 break;
8488 }
8489 }
8490 if (DLLImport) {
8491 TSK = TSK_ExplicitInstantiationDeclaration;
8492 DLLImportExplicitInstantiationDef = true;
8493 }
8494 }
8495
Douglas Gregora1f49972009-05-13 00:25:59 +00008496 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008497 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008498 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008499
8500 // Check that the template argument list is well-formed for this
8501 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008502 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008503 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8504 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008505 return true;
8506
Douglas Gregora1f49972009-05-13 00:25:59 +00008507 // Find the class template specialization declaration that
8508 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008509 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008510 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008511 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008512
Abramo Bagnara8075c852010-06-12 07:44:57 +00008513 TemplateSpecializationKind PrevDecl_TSK
8514 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8515
Douglas Gregor54888652009-10-07 00:13:32 +00008516 // C++0x [temp.explicit]p2:
8517 // [...] An explicit instantiation shall appear in an enclosing
8518 // namespace of its template. [...]
8519 //
8520 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008521 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8522 SS.isSet()))
8523 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008524
Craig Topperc3ec1492014-05-26 06:22:03 +00008525 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008526
Abramo Bagnara8075c852010-06-12 07:44:57 +00008527 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008528 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008529 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008530 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008531 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008532 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008533 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008534
Abramo Bagnara8075c852010-06-12 07:44:57 +00008535 // Even though HasNoEffect == true means that this explicit instantiation
8536 // has no effect on semantics, we go on to put its syntax in the AST.
8537
8538 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8539 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008540 // Since the only prior class template specialization with these
8541 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008542 // declaration node as our own, updating the source location
8543 // for the template name to reflect our new declaration.
8544 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008545 Specialization = PrevDecl;
8546 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008547 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008548 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008549
8550 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8551 DLLImportExplicitInstantiationDef) {
8552 // The new specialization might add a dllimport attribute.
8553 HasNoEffect = false;
8554 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008555 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008556
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008557 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008558 // Create a new class template specialization declaration node for
8559 // this explicit specialization.
8560 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008561 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008562 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008563 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008564 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008565 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008566 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00008567 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008568
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008569 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008570 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008571 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008572 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008573 }
8574
8575 // Build the fully-sugared type for this explicit instantiation as
8576 // the user wrote in the explicit instantiation itself. This means
8577 // that we'll pretty-print the type retrieved from the
8578 // specialization's declaration the way that the user actually wrote
8579 // the explicit instantiation, rather than formatting the name based
8580 // on the "canonical" representation used to store the template
8581 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008582 TypeSourceInfo *WrittenTy
8583 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8584 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008585 Context.getTypeDeclType(Specialization));
8586 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008587
Abramo Bagnara8075c852010-06-12 07:44:57 +00008588 // Set source locations for keywords.
8589 Specialization->setExternLoc(ExternLoc);
8590 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008591 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008592
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008593 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Rafael Espindola0b062072012-01-03 06:04:21 +00008594 if (Attr)
8595 ProcessDeclAttributeList(S, Specialization, Attr);
8596
Abramo Bagnara8075c852010-06-12 07:44:57 +00008597 // Add the explicit instantiation into its lexical context. However,
8598 // since explicit instantiations are never found by name lookup, we
8599 // just put it into the declaration context directly.
8600 Specialization->setLexicalDeclContext(CurContext);
8601 CurContext->addDecl(Specialization);
8602
8603 // Syntax is now OK, so return if it has no other effect on semantics.
8604 if (HasNoEffect) {
8605 // Set the template specialization kind.
8606 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008607 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008608 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008609
8610 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008611 // A definition of a class template or class member template
8612 // shall be in scope at the point of the explicit instantiation of
8613 // the class template or class member template.
8614 //
8615 // This check comes when we actually try to perform the
8616 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008617 ClassTemplateSpecializationDecl *Def
8618 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008619 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008620 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00008621 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008622 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008623 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008624 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8625 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008626
Douglas Gregor1d957a32009-10-27 18:42:08 +00008627 // Instantiate the members of this class template specialization.
8628 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008629 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00008630 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008631 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008632 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8633 // TSK_ExplicitInstantiationDefinition
8634 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00008635 (TSK == TSK_ExplicitInstantiationDefinition ||
8636 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00008637 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008638 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008639
Hans Wennborgc0875502015-06-09 00:39:05 +00008640 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00008641 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8642 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00008643 // In the MS ABI, an explicit instantiation definition can add a dll
8644 // attribute to a template with a previous instantiation declaration.
8645 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008646 auto *A = cast<InheritableAttr>(
8647 getDLLAttr(Specialization)->clone(getASTContext()));
8648 A->setInherited(true);
8649 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008650 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008651 }
8652 }
8653
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008654 // Fix a TSK_ImplicitInstantiation followed by a
8655 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008656 bool NewlyDLLExported =
8657 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8658 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008659 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8660 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8661 // In the MS ABI, an explicit instantiation definition can add a dll
8662 // attribute to a template with a previous implicit instantiation.
8663 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8664 // avoid potentially strange codegen behavior. For example, if we extend
8665 // this conditional to dllimport, and we have a source file calling a
8666 // method on an implicitly instantiated template class instance and then
8667 // declaring a dllimport explicit instantiation definition for the same
8668 // template class, the codegen for the method call will not respect the
8669 // dllimport, while it will with cl. The Def will already have the DLL
8670 // attribute, since the Def and Specialization will be the same in the
8671 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8672 // attribute to the Specialization; we just need to make it take effect.
8673 assert(Def == Specialization &&
8674 "Def and Specialization should match for implicit instantiation");
8675 dllExportImportClassTemplateSpecialization(*this, Def);
8676 }
8677
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008678 // Set the template specialization kind. Make sure it is set before
8679 // instantiating the members which will trigger ASTConsumer callbacks.
8680 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008681 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008682 } else {
8683
8684 // Set the template specialization kind.
8685 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008686 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008687
John McCall48871652010-08-21 09:40:31 +00008688 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008689}
8690
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008691// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008692DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008693Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008694 SourceLocation ExternLoc,
8695 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008696 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008697 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008698 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008699 IdentifierInfo *Name,
8700 SourceLocation NameLoc,
8701 AttributeList *Attr) {
8702
Douglas Gregord6ab8742009-05-28 23:31:59 +00008703 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008704 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008705 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008706 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008707 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008708 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008709 SourceLocation(), false, TypeResult(),
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00008710 /*IsTypeSpecifier*/false,
8711 /*IsTemplateParamOrArg*/false);
John McCall7f41d982009-09-11 04:59:25 +00008712 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8713
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008714 if (!TagD)
8715 return true;
8716
John McCall48871652010-08-21 09:40:31 +00008717 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00008718 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008719
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008720 if (Tag->isInvalidDecl())
8721 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008722
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008723 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8724 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8725 if (!Pattern) {
8726 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8727 << Context.getTypeDeclType(Record);
8728 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8729 return true;
8730 }
8731
Douglas Gregore47f5a72009-10-14 23:41:34 +00008732 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008733 // If the explicit instantiation is for a class or member class, the
8734 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00008735 // simple-template-id.
8736 //
8737 // C++98 has the same restriction, just worded differently.
8738 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00008739 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008740 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008741
Douglas Gregore47f5a72009-10-14 23:41:34 +00008742 // C++0x [temp.explicit]p2:
8743 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008744 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00008745 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00008746 TemplateSpecializationKind TSK
8747 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8748 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008749
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008750 // C++0x [temp.explicit]p2:
8751 // [...] An explicit instantiation shall appear in an enclosing
8752 // namespace of its template. [...]
8753 //
8754 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008755 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008756
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008757 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008758 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00008759 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008760 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00008761 PrevDecl = Record;
8762 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008763 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008764 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008765 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008766 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008767 PrevDecl,
8768 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008769 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008770 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008771 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00008772 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008773 return TagD;
8774 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008775
Douglas Gregor12e49d32009-10-15 22:53:21 +00008776 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008777 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008778 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00008779 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008780 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00008781 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008782 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008783 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00008784 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00008785 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8786 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00008787 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8788 << Pattern;
8789 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008790 } else {
8791 if (InstantiateClass(NameLoc, Record, Def,
8792 getTemplateInstantiationArgs(Record),
8793 TSK))
8794 return true;
8795
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008796 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00008797 if (!RecordDef)
8798 return true;
8799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008800 }
8801
Douglas Gregor1d957a32009-10-27 18:42:08 +00008802 // Instantiate all of the members of the class.
8803 InstantiateClassMembers(NameLoc, RecordDef,
8804 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008805
Douglas Gregor88d292c2010-05-13 16:44:06 +00008806 if (TSK == TSK_ExplicitInstantiationDefinition)
8807 MarkVTableUsed(NameLoc, RecordDef, true);
8808
Mike Stump87c57ac2009-05-16 07:39:55 +00008809 // FIXME: We don't have any representation for explicit instantiations of
8810 // member classes. Such a representation is not needed for compilation, but it
8811 // should be available for clients that want to see all of the declarations in
8812 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008813 return TagD;
8814}
8815
John McCallfaf5fb42010-08-26 23:41:50 +00008816DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8817 SourceLocation ExternLoc,
8818 SourceLocation TemplateLoc,
8819 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008820 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008821 // TODO: check if/when DNInfo should replace Name.
8822 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8823 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00008824 if (!Name) {
8825 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008826 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008827 diag::err_explicit_instantiation_requires_name)
8828 << D.getDeclSpec().getSourceRange()
8829 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008830
Douglas Gregor450f00842009-09-25 18:43:00 +00008831 return true;
8832 }
8833
8834 // The scope passed in may not be a decl scope. Zip up the scope tree until
8835 // we find one that is.
8836 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8837 (S->getFlags() & Scope::TemplateParamScope) != 0)
8838 S = S->getParent();
8839
8840 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00008841 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8842 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00008843 if (R.isNull())
8844 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008845
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008846 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00008847 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008848 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00008849 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008850 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8851 << Name;
8852 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008853 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008854 != DeclSpec::SCS_unspecified) {
8855 // Complain about then remove the storage class specifier.
8856 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8857 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008858
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008859 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00008860 }
8861
Douglas Gregor3c74d412009-10-14 20:14:33 +00008862 // C++0x [temp.explicit]p1:
8863 // [...] An explicit instantiation of a function template shall not use the
8864 // inline or constexpr specifiers.
8865 // Presumably, this also applies to member functions of class templates as
8866 // well.
Richard Smith83c19292011-10-18 03:44:03 +00008867 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008868 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008869 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00008870 diag::err_explicit_instantiation_inline :
8871 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00008872 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00008873 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00008874 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8875 // not already specified.
8876 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8877 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008878
Nathan Wilsonde498452016-02-08 05:34:00 +00008879 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8880 // applied only to the definition of a function template or variable template,
8881 // declared in namespace scope.
8882 if (D.getDeclSpec().isConceptSpecified()) {
8883 Diag(D.getDeclSpec().getConceptSpecLoc(),
8884 diag::err_concept_specified_specialization) << 0;
8885 return true;
8886 }
8887
Richard Smith19a311a2017-02-09 22:47:51 +00008888 // A deduction guide is not on the list of entities that can be explicitly
8889 // instantiated.
8890 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8891 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8892 << /*explicit instantiation*/ 0;
8893 return true;
8894 }
8895
Douglas Gregore47f5a72009-10-14 23:41:34 +00008896 // C++0x [temp.explicit]p2:
8897 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008898 // definition and an explicit instantiation declaration. An explicit
8899 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00008900 TemplateSpecializationKind TSK
8901 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8902 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008903
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008904 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00008905 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00008906
8907 if (!R->isFunctionType()) {
8908 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008909 // A [...] static data member of a class template can be explicitly
8910 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008911 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008912 // C++1y [temp.explicit]p1:
8913 // A [...] variable [...] template specialization can be explicitly
8914 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00008915 if (Previous.isAmbiguous())
8916 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008917
John McCall67c00872009-12-02 08:25:40 +00008918 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00008919 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008920
Larisse Voufo39a1e502013-08-06 01:03:05 +00008921 if (!PrevTemplate) {
8922 if (!Prev || !Prev->isStaticDataMember()) {
8923 // We expect to see a data data member here.
8924 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8925 << Name;
8926 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8927 P != PEnd; ++P)
8928 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8929 return true;
8930 }
8931
8932 if (!Prev->getInstantiatedFromStaticDataMember()) {
8933 // FIXME: Check for explicit specialization?
8934 Diag(D.getIdentifierLoc(),
8935 diag::err_explicit_instantiation_data_member_not_instantiated)
8936 << Prev;
8937 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8938 // FIXME: Can we provide a note showing where this was declared?
8939 return true;
8940 }
8941 } else {
8942 // Explicitly instantiate a variable template.
8943
8944 // C++1y [dcl.spec.auto]p6:
8945 // ... A program that uses auto or decltype(auto) in a context not
8946 // explicitly allowed in this section is ill-formed.
8947 //
8948 // This includes auto-typed variable template instantiations.
8949 if (R->isUndeducedType()) {
8950 Diag(T->getTypeLoc().getLocStart(),
8951 diag::err_auto_not_allowed_var_inst);
8952 return true;
8953 }
8954
Richard Smithef985ac2013-09-18 02:10:12 +00008955 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8956 // C++1y [temp.explicit]p3:
8957 // If the explicit instantiation is for a variable, the unqualified-id
8958 // in the declaration shall be a template-id.
8959 Diag(D.getIdentifierLoc(),
8960 diag::err_explicit_instantiation_without_template_id)
8961 << PrevTemplate;
8962 Diag(PrevTemplate->getLocation(),
8963 diag::note_explicit_instantiation_here);
8964 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00008965 }
8966
Nathan Wilson83839122016-04-09 02:55:27 +00008967 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8968 // explicit instantiation (14.8.2) [...] of a concept definition.
8969 if (PrevTemplate->isConcept()) {
8970 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8971 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8972 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8973 return true;
8974 }
8975
Richard Smithef985ac2013-09-18 02:10:12 +00008976 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00008977 TemplateArgumentListInfo TemplateArgs =
8978 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00008979
Larisse Voufo39a1e502013-08-06 01:03:05 +00008980 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8981 D.getIdentifierLoc(), TemplateArgs);
8982 if (Res.isInvalid())
8983 return true;
8984
8985 // Ignore access control bits, we don't need them for redeclaration
8986 // checking.
8987 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00008988 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008989
Douglas Gregore47f5a72009-10-14 23:41:34 +00008990 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008991 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008992 // or a static data member of a class template specialization, the name of
8993 // the class template specialization in the qualified-id for the member
8994 // name shall be a simple-template-id.
8995 //
8996 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008997 //
Richard Smith5977d872013-09-18 21:55:14 +00008998 // This does not apply to variable template specializations, where the
8999 // template-id is in the unqualified-id instead.
9000 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009001 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009002 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009003 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009004
Douglas Gregore47f5a72009-10-14 23:41:34 +00009005 // Check the scope of this explicit instantiation.
9006 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009007
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009008 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00009009 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9010 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009011 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009012 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00009013 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009014 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009015
Larisse Voufo39a1e502013-08-06 01:03:05 +00009016 if (!HasNoEffect) {
9017 // Instantiate static data member or variable template.
9018
9019 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9020 if (PrevTemplate) {
9021 // Merge attributes.
9022 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
9023 ProcessDeclAttributeList(S, Prev, Attr);
9024 }
9025 if (TSK == TSK_ExplicitInstantiationDefinition)
9026 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9027 }
9028
9029 // Check the new variable specialization against the parsed input.
9030 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9031 Diag(T->getTypeLoc().getLocStart(),
9032 diag::err_invalid_var_template_spec_type)
9033 << 0 << PrevTemplate << R << Prev->getType();
9034 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9035 << 2 << PrevTemplate->getDeclName();
9036 return true;
9037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009038
Douglas Gregor450f00842009-09-25 18:43:00 +00009039 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00009040 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009042
9043 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00009044 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00009045 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00009046 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00009047 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00009048 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00009049 HasExplicitTemplateArgs = true;
9050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009051
Douglas Gregor450f00842009-09-25 18:43:00 +00009052 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009053 // A [...] function [...] can be explicitly instantiated from its template.
9054 // A member function [...] of a class template can be explicitly
9055 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009056 // template.
John McCall27c11dd2017-06-07 23:00:05 +00009057 UnresolvedSet<8> TemplateMatches;
9058 FunctionDecl *NonTemplateMatch = nullptr;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009059 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009060 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00009061 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9062 P != PEnd; ++P) {
9063 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00009064 if (!HasExplicitTemplateArgs) {
9065 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00009066 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9067 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00009068 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
John McCall27c11dd2017-06-07 23:00:05 +00009069 if (Method->getPrimaryTemplate()) {
9070 TemplateMatches.addDecl(Method, P.getAccess());
9071 } else {
9072 // FIXME: Can this assert ever happen? Needs a test.
9073 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9074 NonTemplateMatch = Method;
9075 }
Douglas Gregord90fd522009-09-25 21:45:23 +00009076 }
Douglas Gregor450f00842009-09-25 18:43:00 +00009077 }
9078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009079
Douglas Gregor450f00842009-09-25 18:43:00 +00009080 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9081 if (!FunTmpl)
9082 continue;
9083
Larisse Voufo98b20f12013-07-19 23:00:19 +00009084 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00009085 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009086 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009087 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00009088 (HasExplicitTemplateArgs ? &TemplateArgs
9089 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00009090 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009091 // Keep track of almost-matches.
9092 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00009093 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009094 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00009095 (void)TDK;
9096 continue;
9097 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009098
Artem Belevich64135c32016-12-08 19:38:13 +00009099 // Target attributes are part of the cuda function signature, so
9100 // the cuda target of the instantiated function must match that of its
9101 // template. Given that C++ template deduction does not take
9102 // target attributes into account, we reject candidates here that
9103 // have a different target.
9104 if (LangOpts.CUDA &&
9105 IdentifyCUDATarget(Specialization,
9106 /* IgnoreImplicitHDAttributes = */ true) !=
9107 IdentifyCUDATarget(Attr)) {
9108 FailedCandidates.addCandidate().set(
9109 P.getPair(), FunTmpl->getTemplatedDecl(),
9110 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9111 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009112 }
9113
John McCall27c11dd2017-06-07 23:00:05 +00009114 TemplateMatches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00009115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009116
John McCall27c11dd2017-06-07 23:00:05 +00009117 FunctionDecl *Specialization = NonTemplateMatch;
9118 if (!Specialization) {
9119 // Find the most specialized function template specialization.
9120 UnresolvedSetIterator Result = getMostSpecialized(
9121 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9122 D.getIdentifierLoc(),
9123 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9124 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9125 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00009126
John McCall27c11dd2017-06-07 23:00:05 +00009127 if (Result == TemplateMatches.end())
9128 return true;
John McCall58cc69d2010-01-27 01:50:18 +00009129
John McCall27c11dd2017-06-07 23:00:05 +00009130 // Ignore access control bits, we don't need them for redeclaration checking.
9131 Specialization = cast<FunctionDecl>(*Result);
9132 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009133
Alexey Bataev73983912014-11-06 10:10:50 +00009134 // C++11 [except.spec]p4
9135 // In an explicit instantiation an exception-specification may be specified,
9136 // but is not required.
9137 // If an exception-specification is specified in an explicit instantiation
9138 // directive, it shall be compatible with the exception-specifications of
9139 // other declarations of that function.
9140 if (auto *FPT = R->getAs<FunctionProtoType>())
9141 if (FPT->hasExceptionSpec()) {
9142 unsigned DiagID =
9143 diag::err_mismatched_exception_spec_explicit_instantiation;
9144 if (getLangOpts().MicrosoftExt)
9145 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9146 bool Result = CheckEquivalentExceptionSpec(
9147 PDiag(DiagID) << Specialization->getType(),
9148 PDiag(diag::note_explicit_instantiation_here),
9149 Specialization->getType()->getAs<FunctionProtoType>(),
9150 Specialization->getLocation(), FPT, D.getLocStart());
9151 // In Microsoft mode, mismatching exception specifications just cause a
9152 // warning.
9153 if (!getLangOpts().MicrosoftExt && Result)
9154 return true;
9155 }
9156
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009157 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009158 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009159 diag::err_explicit_instantiation_member_function_not_instantiated)
9160 << Specialization
9161 << (Specialization->getTemplateSpecializationKind() ==
9162 TSK_ExplicitSpecialization);
9163 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9164 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009165 }
9166
Douglas Gregorec9fd132012-01-14 16:38:05 +00009167 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00009168 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9169 PrevDecl = Specialization;
9170
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009171 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00009172 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009173 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009174 PrevDecl,
9175 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009176 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009177 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009178 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009179
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009180 // FIXME: We may still want to build some representation of this
9181 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00009182 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00009183 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009184 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00009185
9186 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00009187 if (Attr)
9188 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009189
Richard Smitheb36ddf2014-04-24 22:45:46 +00009190 if (Specialization->isDefined()) {
9191 // Let the ASTConsumer know that this function has been explicitly
9192 // instantiated now, and its linkage might have changed.
9193 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9194 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00009195 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009196
Douglas Gregore47f5a72009-10-14 23:41:34 +00009197 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009198 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009199 // or a static data member of a class template specialization, the name of
9200 // the class template specialization in the qualified-id for the member
9201 // name shall be a simple-template-id.
9202 //
9203 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009204 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00009205 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009206 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00009207 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009208 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009209 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009210 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009211
Nathan Wilson83839122016-04-09 02:55:27 +00009212 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
9213 // explicit instantiation (14.8.2) [...] of a concept definition.
9214 if (FunTmpl && FunTmpl->isConcept() &&
9215 !D.getDeclSpec().isConceptSpecified()) {
9216 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
9217 << 0 /*function*/ << 0 /*explicitly instantiated*/;
9218 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
9219 return true;
9220 }
9221
Douglas Gregore47f5a72009-10-14 23:41:34 +00009222 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009223 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00009224 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009225 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00009226 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009227
Douglas Gregor450f00842009-09-25 18:43:00 +00009228 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00009229 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009230}
9231
John McCallfaf5fb42010-08-26 23:41:50 +00009232TypeResult
John McCall7f41d982009-09-11 04:59:25 +00009233Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9234 const CXXScopeSpec &SS, IdentifierInfo *Name,
9235 SourceLocation TagLoc, SourceLocation NameLoc) {
9236 // This has to hold, because SS is expected to be defined.
9237 assert(Name && "Expected a name in a dependent tag");
9238
Aaron Ballman4a979672014-01-03 13:56:08 +00009239 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009240 if (!NNS)
9241 return true;
9242
Abramo Bagnara6150c882010-05-11 21:36:43 +00009243 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009244
Douglas Gregorba41d012010-04-24 16:38:41 +00009245 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9246 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009247 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009248 return true;
9249 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009250
Douglas Gregore7c20652011-03-02 00:47:37 +00009251 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009252 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009253 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009254
Douglas Gregore7c20652011-03-02 00:47:37 +00009255 // Create type-source location information for this type.
9256 TypeLocBuilder TLB;
9257 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009258 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009259 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9260 TL.setNameLoc(NameLoc);
9261 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009262}
9263
John McCallfaf5fb42010-08-26 23:41:50 +00009264TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009265Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9266 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009267 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009268 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009269 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009270
Richard Smith0bf8a4922011-10-18 20:49:44 +00009271 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9272 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009273 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009274 diag::warn_cxx98_compat_typename_outside_of_template :
9275 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009276 << FixItHint::CreateRemoval(TypenameLoc);
9277
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009278 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009279 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9280 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009281 if (T.isNull())
9282 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009283
9284 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9285 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009286 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009287 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009288 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009289 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009290 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009291 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009292 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009293 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009294 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009295 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009296
John McCallba7bf592010-08-24 05:47:05 +00009297 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009298}
9299
John McCallfaf5fb42010-08-26 23:41:50 +00009300TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009301Sema::ActOnTypenameType(Scope *S,
9302 SourceLocation TypenameLoc,
9303 const CXXScopeSpec &SS,
9304 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009305 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009306 IdentifierInfo *TemplateII,
9307 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009308 SourceLocation LAngleLoc,
9309 ASTTemplateArgsPtr TemplateArgsIn,
9310 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009311 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9312 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009313 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009314 diag::warn_cxx98_compat_typename_outside_of_template :
9315 diag::ext_typename_outside_of_template)
9316 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009317
Richard Smith74f02342017-01-19 21:00:13 +00009318 // Strangely, non-type results are not ignored by this lookup, so the
9319 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009320 if (TypenameLoc.isValid()) {
9321 auto *LookupRD =
9322 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9323 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9324 Diag(TemplateIILoc,
9325 diag::ext_out_of_line_qualified_id_type_names_constructor)
9326 << TemplateII << 0 /*injected-class-name used as template name*/
9327 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9328 }
Richard Smith74f02342017-01-19 21:00:13 +00009329 }
9330
Douglas Gregorb09518c2011-02-27 22:46:49 +00009331 // Translate the parser's template argument list in our AST format.
9332 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9333 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009334
Douglas Gregorb09518c2011-02-27 22:46:49 +00009335 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009336 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9337 // Construct a dependent template specialization type.
9338 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009339 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009340 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9341 DTN->getQualifier(),
9342 DTN->getIdentifier(),
9343 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009344
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009345 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009346 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009347 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009348 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009349 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9350 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009351 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009352 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009353 SpecTL.setLAngleLoc(LAngleLoc);
9354 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009355 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9356 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009357 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009358 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009359
Richard Smith74f02342017-01-19 21:00:13 +00009360 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009361 if (T.isNull())
9362 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009363
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009364 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009365 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009366 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009367 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009368 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009369 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009370 SpecTL.setLAngleLoc(LAngleLoc);
9371 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009372 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9373 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009374
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009375 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9376 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009377 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009378 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009379
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009380 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9381 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009382}
9383
Douglas Gregorb09518c2011-02-27 22:46:49 +00009384
Richard Smith6f8d2c62012-05-09 05:17:00 +00009385/// Determine whether this failed name lookup should be treated as being
9386/// disabled by a usage of std::enable_if.
9387static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009388 SourceRange &CondRange, Expr *&Cond) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009389 // We must be looking for a ::type...
9390 if (!II.isStr("type"))
9391 return false;
9392
9393 // ... within an explicitly-written template specialization...
9394 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9395 return false;
9396 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009397 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9398 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9399 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009400 return false;
9401 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00009402 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00009403
9404 // ... which names a complete class template declaration...
9405 const TemplateDecl *EnableIfDecl =
9406 EnableIfTST->getTemplateName().getAsTemplateDecl();
9407 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9408 return false;
9409
9410 // ... called "enable_if".
9411 const IdentifierInfo *EnableIfII =
9412 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9413 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9414 return false;
9415
9416 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009417 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009418
9419 // Dig out the condition.
9420 Cond = nullptr;
9421 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9422 != TemplateArgument::Expression)
9423 return true;
9424
9425 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9426
9427 // Ignore Boolean literals; they add no value.
9428 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9429 Cond = nullptr;
9430
Richard Smith6f8d2c62012-05-09 05:17:00 +00009431 return true;
9432}
9433
Douglas Gregor333489b2009-03-27 23:10:48 +00009434/// \brief Build the type that describes a C++ typename specifier,
9435/// e.g., "typename T::type".
9436QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009437Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009438 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009439 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009440 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009441 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009442 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009443 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009444
John McCall0b66eb32010-05-01 00:40:08 +00009445 DeclContext *Ctx = computeDeclContext(SS);
9446 if (!Ctx) {
9447 // If the nested-name-specifier is dependent and couldn't be
9448 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009449 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009450 return Context.getDependentNameType(Keyword,
9451 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009452 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009453 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009454
John McCall0b66eb32010-05-01 00:40:08 +00009455 // If the nested-name-specifier refers to the current instantiation,
9456 // the "typename" keyword itself is superfluous. In C++03, the
9457 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9458 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009459 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009460
John McCall0b66eb32010-05-01 00:40:08 +00009461 if (RequireCompleteDeclContext(SS, Ctx))
9462 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009463
9464 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009465 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009466 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009467 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009468 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009469 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009470 case LookupResult::NotFound: {
9471 // If we're looking up 'type' within a template named 'enable_if', produce
9472 // a more specific diagnostic.
9473 SourceRange CondRange;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009474 Expr *Cond = nullptr;
9475 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9476 // If we have a condition, narrow it down to the specific failed
9477 // condition.
9478 if (Cond) {
9479 Expr *FailedCond;
9480 std::string FailedDescription;
9481 std::tie(FailedCond, FailedDescription) =
9482 findFailedEnableIfCondition(*this, Cond);
9483
9484 Diag(FailedCond->getExprLoc(),
9485 diag::err_typename_nested_not_found_requirement)
9486 << FailedDescription
9487 << FailedCond->getSourceRange();
9488 return QualType();
9489 }
9490
Richard Smith6f8d2c62012-05-09 05:17:00 +00009491 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009492 << Ctx << CondRange;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009493 return QualType();
9494 }
9495
Douglas Gregore40876a2009-10-13 21:16:44 +00009496 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009497 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009498 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009499
9500 case LookupResult::FoundUnresolvedValue: {
9501 // We found a using declaration that is a value. Most likely, the using
9502 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009503 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009504 IILoc);
9505 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9506 << Name << Ctx << FullRange;
9507 if (UnresolvedUsingValueDecl *Using
9508 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009509 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009510 Diag(Loc, diag::note_using_value_decl_missing_typename)
9511 << FixItHint::CreateInsertion(Loc, "typename ");
9512 }
9513 }
9514 // Fall through to create a dependent typename type, from which we can recover
9515 // better.
Galina Kistanova3779cb32017-06-07 06:25:05 +00009516 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009517
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009518 case LookupResult::NotFoundInCurrentInstantiation:
9519 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009520 return Context.getDependentNameType(Keyword,
9521 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009522 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009523
9524 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009525 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009526 // C++ [class.qual]p2:
9527 // In a lookup in which function names are not ignored and the
9528 // nested-name-specifier nominates a class C, if the name specified
9529 // after the nested-name-specifier, when looked up in C, is the
9530 // injected-class-name of C [...] then the name is instead considered
9531 // to name the constructor of class C.
9532 //
9533 // Unlike in an elaborated-type-specifier, function names are not ignored
9534 // in typename-specifier lookup. However, they are ignored in all the
9535 // contexts where we form a typename type with no keyword (that is, in
9536 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9537 //
9538 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9539 // ignore functions, but that appears to be an oversight.
9540 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9541 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9542 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9543 FoundRD->isInjectedClassName() &&
9544 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9545 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9546 << &II << 1 << 0 /*'typename' keyword used*/;
9547
Abramo Bagnara6150c882010-05-11 21:36:43 +00009548 // We found a type. Build an ElaboratedType, since the
9549 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009550 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009551 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009552 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009553 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009554 }
9555
Richard Smithee579842017-01-30 20:39:26 +00009556 // C++ [dcl.type.simple]p2:
9557 // A type-specifier of the form
9558 // typename[opt] nested-name-specifier[opt] template-name
9559 // is a placeholder for a deduced class type [...].
9560 if (getLangOpts().CPlusPlus1z) {
9561 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9562 return Context.getElaboratedType(
9563 Keyword, QualifierLoc.getNestedNameSpecifier(),
9564 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9565 QualType(), false));
9566 }
9567 }
Richard Smith600b5262017-01-26 20:40:47 +00009568
Douglas Gregor333489b2009-03-27 23:10:48 +00009569 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009570 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009571 break;
9572
9573 case LookupResult::FoundOverloaded:
9574 DiagID = diag::err_typename_nested_not_type;
9575 Referenced = *Result.begin();
9576 break;
9577
John McCall6538c932009-10-10 05:48:19 +00009578 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009579 return QualType();
9580 }
9581
9582 // If we get here, it's because name lookup did not find a
9583 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009584 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009585 IILoc);
9586 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009587 if (Referenced)
9588 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9589 << Name;
9590 return QualType();
9591}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009592
9593namespace {
9594 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009595 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009596 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009597 SourceLocation Loc;
9598 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009599
Douglas Gregor15acfb92009-08-06 16:20:37 +00009600 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009601 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009602
Mike Stump11289f42009-09-09 15:08:12 +00009603 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009604 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009605 DeclarationName Entity)
9606 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009607 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009608
9609 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009610 /// transformed.
9611 ///
9612 /// For the purposes of type reconstruction, a type has already been
9613 /// transformed if it is NULL or if it is not dependent.
9614 bool AlreadyTransformed(QualType T) {
9615 return T.isNull() || !T->isDependentType();
9616 }
Mike Stump11289f42009-09-09 15:08:12 +00009617
9618 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009619 /// rebuilt.
9620 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009621
Douglas Gregor15acfb92009-08-06 16:20:37 +00009622 /// \brief Returns the name of the entity whose type is being rebuilt.
9623 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009624
Douglas Gregoref6ab412009-10-27 06:26:26 +00009625 /// \brief Sets the "base" location and entity when that
9626 /// information is known based on another transformation.
9627 void setBase(SourceLocation Loc, DeclarationName Entity) {
9628 this->Loc = Loc;
9629 this->Entity = Entity;
9630 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009631
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00009632 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9633 // Lambdas never need to be transformed.
9634 return E;
9635 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00009636 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009637} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00009638
Douglas Gregor15acfb92009-08-06 16:20:37 +00009639/// \brief Rebuilds a type within the context of the current instantiation.
9640///
Mike Stump11289f42009-09-09 15:08:12 +00009641/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00009642/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00009643/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00009644/// partial specialization thereof). This routine will rebuild that type now
9645/// that we have entered the declarator's scope, which may produce different
9646/// canonical types, e.g.,
9647///
9648/// \code
9649/// template<typename T>
9650/// struct X {
9651/// typedef T* pointer;
9652/// pointer data();
9653/// };
9654///
9655/// template<typename T>
9656/// typename X<T>::pointer X<T>::data() { ... }
9657/// \endcode
9658///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00009659/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009660/// since we do not know that we can look into X<T> when we parsed the type.
9661/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00009662/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00009663/// as the canonical type of T*, allowing the return types of the out-of-line
9664/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00009665TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9666 SourceLocation Loc,
9667 DeclarationName Name) {
9668 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00009669 return T;
Mike Stump11289f42009-09-09 15:08:12 +00009670
Douglas Gregor15acfb92009-08-06 16:20:37 +00009671 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9672 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00009673}
Douglas Gregorbe999392009-09-15 16:23:51 +00009674
John McCalldadc5752010-08-24 06:29:42 +00009675ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00009676 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9677 DeclarationName());
9678 return Rebuilder.TransformExpr(E);
9679}
9680
John McCall99b2fe52010-04-29 23:50:39 +00009681bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00009682 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009683 return true;
John McCall2408e322010-04-27 00:57:59 +00009684
Douglas Gregor10176412011-02-25 16:07:42 +00009685 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009686 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9687 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009688 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009689 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009690 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009691 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009692
Douglas Gregor10176412011-02-25 16:07:42 +00009693 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009694 return false;
John McCall2408e322010-04-27 00:57:59 +00009695}
9696
Douglas Gregor041b0842011-10-14 15:31:12 +00009697/// \brief Rebuild the template parameters now that we know we're in a current
9698/// instantiation.
9699bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9700 TemplateParameterList *Params) {
9701 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9702 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009703
Douglas Gregor041b0842011-10-14 15:31:12 +00009704 // There is nothing to rebuild in a type parameter.
9705 if (isa<TemplateTypeParmDecl>(Param))
9706 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009707
Douglas Gregor041b0842011-10-14 15:31:12 +00009708 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009709 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009710 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9711 if (RebuildTemplateParamsInCurrentInstantiation(
9712 TTP->getTemplateParameters()))
9713 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009714
Douglas Gregor041b0842011-10-14 15:31:12 +00009715 continue;
9716 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009717
Douglas Gregor041b0842011-10-14 15:31:12 +00009718 // Rebuild the type of a non-type template parameter.
9719 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009720 TypeSourceInfo *NewTSI
9721 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9722 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009723 NTTP->getDeclName());
9724 if (!NewTSI)
9725 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009726
Douglas Gregor041b0842011-10-14 15:31:12 +00009727 if (NewTSI != NTTP->getTypeSourceInfo()) {
9728 NTTP->setTypeSourceInfo(NewTSI);
9729 NTTP->setType(NewTSI->getType());
9730 }
9731 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009732
Douglas Gregor041b0842011-10-14 15:31:12 +00009733 return false;
9734}
9735
Douglas Gregorbe999392009-09-15 16:23:51 +00009736/// \brief Produces a formatted string that describes the binding of
9737/// template parameters to template arguments.
9738std::string
9739Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9740 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009741 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00009742}
9743
9744std::string
9745Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9746 const TemplateArgument *Args,
9747 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009748 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00009749 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00009750
Douglas Gregore62e6a02009-11-11 19:13:48 +00009751 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009752 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009753
Douglas Gregorbe999392009-09-15 16:23:51 +00009754 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00009755 if (I >= NumArgs)
9756 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009757
Douglas Gregorbe999392009-09-15 16:23:51 +00009758 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009759 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00009760 else
Douglas Gregor0192c232010-12-20 16:52:59 +00009761 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009762
Douglas Gregorbe999392009-09-15 16:23:51 +00009763 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00009764 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00009765 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00009766 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00009767 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009768
Douglas Gregor0192c232010-12-20 16:52:59 +00009769 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00009770 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00009771 }
Douglas Gregor0192c232010-12-20 16:52:59 +00009772
9773 Out << ']';
9774 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00009775}
Francois Pichet1c229c02011-04-22 22:18:13 +00009776
Richard Smithe40f2ba2013-08-07 21:41:30 +00009777void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9778 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00009779 if (!FD)
9780 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00009781
Justin Lebar28f09c52016-10-10 16:26:08 +00009782 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00009783
9784 // Take tokens to avoid allocations
9785 LPT->Toks.swap(Toks);
9786 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00009787 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00009788
9789 FD->setLateTemplateParsed(true);
9790}
9791
9792void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9793 if (!FD)
9794 return;
9795 FD->setLateTemplateParsed(false);
9796}
Francois Pichet1c229c02011-04-22 22:18:13 +00009797
9798bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9799 DeclContext *DC = CurContext;
9800
9801 while (DC) {
9802 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9803 const FunctionDecl *FD = RD->isLocalClass();
9804 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9805 } else if (DC->isTranslationUnit() || DC->isNamespace())
9806 return false;
9807
9808 DC = DC->getParent();
9809 }
9810 return false;
9811}
Richard Smith6739a102016-05-05 00:56:12 +00009812
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009813namespace {
Richard Smith6739a102016-05-05 00:56:12 +00009814/// \brief Walk the path from which a declaration was instantiated, and check
9815/// that every explicit specialization along that path is visible. This enforces
9816/// C++ [temp.expl.spec]/6:
9817///
9818/// If a template, a member template or a member of a class template is
9819/// explicitly specialized then that specialization shall be declared before
9820/// the first use of that specialization that would cause an implicit
9821/// instantiation to take place, in every translation unit in which such a
9822/// use occurs; no diagnostic is required.
9823///
9824/// and also C++ [temp.class.spec]/1:
9825///
9826/// A partial specialization shall be declared before the first use of a
9827/// class template specialization that would make use of the partial
9828/// specialization as the result of an implicit or explicit instantiation
9829/// in every translation unit in which such a use occurs; no diagnostic is
9830/// required.
9831class ExplicitSpecializationVisibilityChecker {
9832 Sema &S;
9833 SourceLocation Loc;
9834 llvm::SmallVector<Module *, 8> Modules;
9835
9836public:
9837 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9838 : S(S), Loc(Loc) {}
9839
9840 void check(NamedDecl *ND) {
9841 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9842 return checkImpl(FD);
9843 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9844 return checkImpl(RD);
9845 if (auto *VD = dyn_cast<VarDecl>(ND))
9846 return checkImpl(VD);
9847 if (auto *ED = dyn_cast<EnumDecl>(ND))
9848 return checkImpl(ED);
9849 }
9850
9851private:
9852 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9853 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9854 : Sema::MissingImportKind::ExplicitSpecialization;
9855 const bool Recover = true;
9856
9857 // If we got a custom set of modules (because only a subset of the
9858 // declarations are interesting), use them, otherwise let
9859 // diagnoseMissingImport intelligently pick some.
9860 if (Modules.empty())
9861 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9862 else
9863 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9864 }
9865
9866 // Check a specific declaration. There are three problematic cases:
9867 //
9868 // 1) The declaration is an explicit specialization of a template
9869 // specialization.
9870 // 2) The declaration is an explicit specialization of a member of an
9871 // templated class.
9872 // 3) The declaration is an instantiation of a template, and that template
9873 // is an explicit specialization of a member of a templated class.
9874 //
9875 // We don't need to go any deeper than that, as the instantiation of the
9876 // surrounding class / etc is not triggered by whatever triggered this
9877 // instantiation, and thus should be checked elsewhere.
9878 template<typename SpecDecl>
9879 void checkImpl(SpecDecl *Spec) {
9880 bool IsHiddenExplicitSpecialization = false;
9881 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9882 IsHiddenExplicitSpecialization =
9883 Spec->getMemberSpecializationInfo()
9884 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
Richard Smith54f04402017-05-18 02:29:20 +00009885 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
Richard Smith6739a102016-05-05 00:56:12 +00009886 } else {
9887 checkInstantiated(Spec);
9888 }
9889
9890 if (IsHiddenExplicitSpecialization)
9891 diagnose(Spec->getMostRecentDecl(), false);
9892 }
9893
9894 void checkInstantiated(FunctionDecl *FD) {
9895 if (auto *TD = FD->getPrimaryTemplate())
9896 checkTemplate(TD);
9897 }
9898
9899 void checkInstantiated(CXXRecordDecl *RD) {
9900 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9901 if (!SD)
9902 return;
9903
9904 auto From = SD->getSpecializedTemplateOrPartial();
9905 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9906 checkTemplate(TD);
9907 else if (auto *TD =
9908 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9909 if (!S.hasVisibleDeclaration(TD))
9910 diagnose(TD, true);
9911 checkTemplate(TD);
9912 }
9913 }
9914
9915 void checkInstantiated(VarDecl *RD) {
9916 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9917 if (!SD)
9918 return;
9919
9920 auto From = SD->getSpecializedTemplateOrPartial();
9921 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9922 checkTemplate(TD);
9923 else if (auto *TD =
9924 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9925 if (!S.hasVisibleDeclaration(TD))
9926 diagnose(TD, true);
9927 checkTemplate(TD);
9928 }
9929 }
9930
9931 void checkInstantiated(EnumDecl *FD) {}
9932
9933 template<typename TemplDecl>
9934 void checkTemplate(TemplDecl *TD) {
9935 if (TD->isMemberSpecialization()) {
9936 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9937 diagnose(TD->getMostRecentDecl(), false);
9938 }
9939 }
9940};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009941} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00009942
9943void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
9944 if (!getLangOpts().Modules)
9945 return;
9946
9947 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9948}
9949
9950/// \brief Check whether a template partial specialization that we've discovered
9951/// is hidden, and produce suitable diagnostics if so.
9952void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
9953 NamedDecl *Spec) {
9954 llvm::SmallVector<Module *, 8> Modules;
9955 if (!hasVisibleDeclaration(Spec, &Modules))
9956 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9957 MissingImportKind::PartialSpecialization,
9958 /*Recover*/true);
9959}