blob: e05f3fe36d9330c8418e360e1a1435c8ee2cf226 [file] [log] [blame]
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +000011
Douglas Gregor15acfb92009-08-06 16:20:37 +000012#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000013#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000015#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000019#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000020#include "clang/AST/TypeVisitor.h"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000021#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedTemplate.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000032#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000034#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000035
Eric Fiselier6ad68552016-07-01 01:24:09 +000036#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000037using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000039
John McCall9b72f892010-11-10 02:40:36 +000040// Exported for use by Parser.
41SourceRange
42clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 unsigned N) {
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46}
47
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000048namespace clang {
49/// \brief [temp.constr.decl]p2: A template's associated constraints are
50/// defined as a single constraint-expression derived from the introduced
51/// constraint-expressions [ ... ].
52///
53/// \param Params The template parameter list and optional requires-clause.
54///
55/// \param FD The underlying templated function declaration for a function
56/// template.
57static Expr *formAssociatedConstraints(TemplateParameterList *Params,
58 FunctionDecl *FD);
59}
60
61static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
62 FunctionDecl *FD) {
63 // FIXME: Concepts: collect additional introduced constraint-expressions
64 assert(!FD && "Cannot collect constraints from function declaration yet.");
65 return Params->getRequiresClause();
66}
67
Douglas Gregorb7bfe792009-09-02 22:59:36 +000068/// \brief Determine whether the declaration found is acceptable as the name
69/// of a template and, if so, return that template declaration. Otherwise,
70/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000071static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000072 NamedDecl *Orig,
73 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000074 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000076 if (isa<TemplateDecl>(D)) {
77 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000078 return nullptr;
79
John McCalle9cccd82010-06-16 08:42:20 +000080 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000081 }
Mike Stump11289f42009-09-09 15:08:12 +000082
Douglas Gregorb7bfe792009-09-02 22:59:36 +000083 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
84 // C++ [temp.local]p1:
85 // Like normal (non-template) classes, class templates have an
86 // injected-class-name (Clause 9). The injected-class-name
87 // can be used with or without a template-argument-list. When
88 // it is used without a template-argument-list, it is
89 // equivalent to the injected-class-name followed by the
90 // template-parameters of the class template enclosed in
91 // <>. When it is used with a template-argument-list, it
92 // refers to the specified class template specialization,
93 // which could be the current specialization or another
94 // specialization.
95 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000096 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000097 if (Record->getDescribedClassTemplate())
98 return Record->getDescribedClassTemplate();
99
100 if (ClassTemplateSpecializationDecl *Spec
101 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
102 return Spec->getSpecializedTemplate();
103 }
Mike Stump11289f42009-09-09 15:08:12 +0000104
Craig Topperc3ec1492014-05-26 06:22:03 +0000105 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106 }
Mike Stump11289f42009-09-09 15:08:12 +0000107
Craig Topperc3ec1492014-05-26 06:22:03 +0000108 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000109}
110
Simon Pilgrim6905d222016-12-30 22:55:33 +0000111void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000112 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000113 // The set of class templates we've already seen.
114 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +0000115 LookupResult::Filter filter = R.makeFilter();
116 while (filter.hasNext()) {
117 NamedDecl *Orig = filter.next();
Simon Pilgrim6905d222016-12-30 22:55:33 +0000118 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000119 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +0000120 if (!Repl)
121 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000122 else if (Repl != Orig) {
123
124 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000125 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000126 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000127 // one base class). If all of the injected-class-names that are found
128 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000129 // is used as a template-name, the reference refers to the class
130 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000131 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000132 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000133 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000134 filter.erase();
135 continue;
136 }
John McCallbd8062d2010-08-13 07:02:08 +0000137
138 // FIXME: we promote access to public here as a workaround to
139 // the fact that LookupResult doesn't let us remember that we
140 // found this template through a particular injected class name,
141 // which means we end up doing nasty things to the invariants.
142 // Pretending that access is public is *much* safer.
143 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000144 }
John McCalle66edc12009-11-24 19:00:30 +0000145 }
146 filter.done();
147}
148
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000149bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
150 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000151 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000152 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000153 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +0000154
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000155 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000156}
157
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000159 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000160 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000161 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000162 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000163 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000164 TemplateTy &TemplateResult,
165 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000166 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000167
Douglas Gregor3cf81312009-11-03 23:16:33 +0000168 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000169 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000170
Douglas Gregor3cf81312009-11-03 23:16:33 +0000171 switch (Name.getKind()) {
172 case UnqualifiedId::IK_Identifier:
173 TName = DeclarationName(Name.Identifier);
174 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000175
Douglas Gregor3cf81312009-11-03 23:16:33 +0000176 case UnqualifiedId::IK_OperatorFunctionId:
177 TName = Context.DeclarationNames.getCXXOperatorName(
178 Name.OperatorFunctionId.Operator);
179 break;
180
Alexis Hunted0530f2009-11-28 08:58:14 +0000181 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000182 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
183 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000184
Douglas Gregor3cf81312009-11-03 23:16:33 +0000185 default:
186 return TNK_Non_template;
187 }
Mike Stump11289f42009-09-09 15:08:12 +0000188
John McCallba7bf592010-08-24 05:47:05 +0000189 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000190
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000191 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000192 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
193 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000194 if (R.empty()) return TNK_Non_template;
195 if (R.isAmbiguous()) {
196 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000197 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000198
199 // FIXME: we might have ambiguous templates, in which case we
200 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000201 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000202 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000203
John McCalld28ae272009-12-02 08:04:21 +0000204 TemplateName Template;
205 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000206
John McCalld28ae272009-12-02 08:04:21 +0000207 unsigned ResultCount = R.end() - R.begin();
208 if (ResultCount > 1) {
209 // We assume that we'll preserve the qualifier from a function
210 // template name in other ways.
211 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
212 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000213
214 // We'll do this lookup again later.
215 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000216 } else {
John McCalld28ae272009-12-02 08:04:21 +0000217 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
218
219 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000220 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000221 Template = Context.getQualifiedTemplateName(Qualifier,
222 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000223 } else {
224 Template = TemplateName(TD);
225 }
226
John McCalldcc71402010-08-13 02:23:42 +0000227 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000228 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000229
230 // We'll do this lookup again later.
231 R.suppressDiagnostics();
232 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000233 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000234 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
235 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000236 TemplateKind =
237 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000238 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000239 }
Mike Stump11289f42009-09-09 15:08:12 +0000240
John McCalld28ae272009-12-02 08:04:21 +0000241 TemplateResult = TemplateTy::make(Template);
242 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000243}
244
Richard Smith278890f2017-02-10 20:39:58 +0000245bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
246 SourceLocation NameLoc,
247 ParsedTemplateTy *Template) {
248 CXXScopeSpec SS;
249 bool MemberOfUnknownSpecialization = false;
250
251 // We could use redeclaration lookup here, but we don't need to: the
252 // syntactic form of a deduction guide is enough to identify it even
253 // if we can't look up the template name at all.
254 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
255 LookupTemplateName(R, S, SS, /*ObjectType*/QualType(),
256 /*EnteringContext*/false, MemberOfUnknownSpecialization);
257
258 if (R.empty()) return false;
259 if (R.isAmbiguous()) {
260 // FIXME: Diagnose an ambiguity if we find at least one template.
261 R.suppressDiagnostics();
262 return false;
263 }
264
265 // We only treat template-names that name type templates as valid deduction
266 // guide names.
267 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
268 if (!TD || !getAsTypeTemplateDecl(TD))
269 return false;
270
271 if (Template)
272 *Template = TemplateTy::make(TemplateName(TD));
273 return true;
274}
275
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000277 SourceLocation IILoc,
278 Scope *S,
279 const CXXScopeSpec *SS,
280 TemplateTy &SuggestedTemplate,
281 TemplateNameKind &SuggestedKind) {
282 // We can't recover unless there's a dependent scope specifier preceding the
283 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000284 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000285 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
286 computeDeclContext(*SS))
287 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000288
Douglas Gregor18473f32010-01-12 21:28:44 +0000289 // The code is missing a 'template' keyword prior to the dependent template
290 // name.
291 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
292 Diag(IILoc, diag::err_template_kw_missing)
293 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000294 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000295 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000296 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
297 SuggestedKind = TNK_Dependent_template_name;
298 return true;
299}
300
John McCalle66edc12009-11-24 19:00:30 +0000301void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000302 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000303 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000304 bool EnteringContext,
305 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000306 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000307 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000308 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000309 bool isDependent = false;
310 if (!ObjectType.isNull()) {
311 // This nested-name-specifier occurs in a member access expression, e.g.,
312 // x->B::f, and we are looking into the type of the object.
313 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
314 LookupCtx = computeDeclContext(ObjectType);
315 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000316 assert((isDependent || !ObjectType->isIncompleteType() ||
317 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000318 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000319
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000320 // Template names cannot appear inside an Objective-C class or object type.
321 if (ObjectType->isObjCObjectOrInterfaceType()) {
322 Found.clear();
323 return;
324 }
John McCalle66edc12009-11-24 19:00:30 +0000325 } else if (SS.isSet()) {
326 // This nested-name-specifier occurs after another nested-name-specifier,
327 // so long into the context associated with the prior nested-name-specifier.
328 LookupCtx = computeDeclContext(SS, EnteringContext);
329 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000330
John McCalle66edc12009-11-24 19:00:30 +0000331 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000332 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000333 return;
334 }
335
336 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000337 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000338 if (LookupCtx) {
339 // Perform "qualified" name lookup into the declaration context we
340 // computed, which is either the type of the base of a member access
341 // expression or the declaration context associated with a prior
342 // nested-name-specifier.
343 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000344 if (!ObjectType.isNull() && Found.empty()) {
345 // C++ [basic.lookup.classref]p1:
346 // In a class member access expression (5.2.5), if the . or -> token is
347 // immediately followed by an identifier followed by a <, the
348 // identifier must be looked up to determine whether the < is the
349 // beginning of a template argument list (14.2) or a less-than operator.
350 // The identifier is first looked up in the class of the object
351 // expression. If the identifier is not found, it is then looked up in
352 // the context of the entire postfix-expression and shall name a class
353 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000354 if (S) LookupName(Found, S);
355 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000356 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000357 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000358 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000359 // We cannot look into a dependent object type or nested nme
360 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000361 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000362 return;
363 } else {
364 // Perform unqualified name lookup in the current scope.
365 LookupName(Found, S);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000366
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000367 if (!ObjectType.isNull())
368 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000369 }
370
Douglas Gregorc119dd52010-01-12 17:06:20 +0000371 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000372 // If we did not find any names, attempt to correct any typos.
373 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000374 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000375 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000376 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
377 FilterCCC->WantTypeSpecifiers = false;
378 FilterCCC->WantExpressionKeywords = false;
379 FilterCCC->WantRemainingKeywords = false;
380 FilterCCC->WantCXXNamedCasts = true;
381 if (TypoCorrection Corrected = CorrectTypo(
382 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
383 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000384 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000385 if (auto *ND = Corrected.getFoundDecl())
386 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000387 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000388 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000389 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000390 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
391 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000392 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000393 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
394 << Name << LookupCtx << DroppedSpecifier
395 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000396 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000397 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000398 }
John McCalle9cccd82010-06-16 08:42:20 +0000399 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000400 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000401 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000402 }
403 }
404
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000405 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000406 if (Found.empty()) {
407 if (isDependent)
408 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000409 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000410 }
John McCalle66edc12009-11-24 19:00:30 +0000411
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000412 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000413 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000414 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000415 // [...] If the lookup in the class of the object expression finds a
416 // template, the name is also looked up in the context of the entire
417 // postfix-expression and [...]
418 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000419 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000420 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
421 LookupOrdinaryName);
422 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000423 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000424
John McCalle66edc12009-11-24 19:00:30 +0000425 if (FoundOuter.empty()) {
426 // - if the name is not found, the name found in the class of the
427 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000428 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
429 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000430 // - if the name is found in the context of the entire
431 // postfix-expression and does not name a class template, the name
432 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000433 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000434 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000435 // - if the name found is a class template, it must refer to the same
436 // entity as the one found in the class of the object expression,
437 // otherwise the program is ill-formed.
438 if (!Found.isSingleResult() ||
439 Found.getFoundDecl()->getCanonicalDecl()
440 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000442 diag::ext_nested_name_member_ref_lookup_ambiguous)
443 << Found.getLookupName()
444 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000445 Diag(Found.getRepresentativeDecl()->getLocation(),
446 diag::note_ambig_member_ref_object_type)
447 << ObjectType;
448 Diag(FoundOuter.getFoundDecl()->getLocation(),
449 diag::note_ambig_member_ref_scope);
450
451 // Recover by taking the template that we found in the object
452 // expression's type.
453 }
454 }
455 }
456}
457
John McCallcd4b4772009-12-02 03:53:29 +0000458/// ActOnDependentIdExpression - Handle a dependent id-expression that
459/// was just parsed. This is only possible with an explicit scope
460/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000461ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000462Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000463 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000464 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000465 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000466 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000467 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000468
Reid Kleckner1af391df2016-03-11 18:59:12 +0000469 // C++11 [expr.prim.general]p12:
470 // An id-expression that denotes a non-static data member or non-static
471 // member function of a class can only be used:
472 // (...)
473 // - if that id-expression denotes a non-static data member and it
474 // appears in an unevaluated operand.
475 //
476 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
477 // CXXDependentScopeMemberExpr. The former can instantiate to either
478 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
479 // always a MemberExpr.
480 bool MightBeCxx11UnevalField =
481 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
482
Akira Hatanakad644e022016-12-16 03:19:41 +0000483 // Check if the nested name specifier is an enum type.
484 bool IsEnum = false;
485 if (NestedNameSpecifier *NNS = SS.getScopeRep())
486 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
487
488 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000489 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000490 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000491
John McCalle66edc12009-11-24 19:00:30 +0000492 // Since the 'this' expression is synthesized, we don't need to
493 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000494 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000495
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000496 return CXXDependentScopeMemberExpr::Create(
497 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
498 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
499 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000500 }
501
Abramo Bagnara7945c982012-01-27 09:46:47 +0000502 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000503}
504
John McCalldadc5752010-08-24 06:29:42 +0000505ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000506Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000507 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000508 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000509 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000510 return DependentScopeDeclRefExpr::Create(
511 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
512 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000513}
514
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000515
516/// Determine whether we would be unable to instantiate this template (because
517/// it either has no definition, or is in the process of being instantiated).
518bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
519 NamedDecl *Instantiation,
520 bool InstantiatedFromMember,
521 const NamedDecl *Pattern,
522 const NamedDecl *PatternDef,
523 TemplateSpecializationKind TSK,
524 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000525 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
526 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000527
Richard Smithedbc6e92016-10-14 21:41:24 +0000528 bool IsEntityBeingDefined = false;
529 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
530 IsEntityBeingDefined = TD->isBeingDefined();
531
532 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000533 NamedDecl *SuggestedDef = nullptr;
534 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
535 /*OnlyNeedComplete*/false)) {
536 // If we're allowed to diagnose this and recover, do so.
537 bool Recover = Complain && !isSFINAEContext();
538 if (Complain)
539 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
540 Sema::MissingImportKind::Definition, Recover);
541 return !Recover;
542 }
543 return false;
544 }
545
Richard Smith6f4e2e02016-08-23 19:41:39 +0000546 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
547 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000548
Richard Smithedbc6e92016-10-14 21:41:24 +0000549 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000550 QualType InstantiationTy;
551 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
552 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000553 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000554 Diag(PointOfInstantiation,
555 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000556 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000557 << InstantiationTy;
558 // Not much point in noting the template declaration here, since
559 // we're lexically inside it.
560 Instantiation->setInvalidDecl();
561 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000562 if (isa<FunctionDecl>(Instantiation)) {
563 Diag(PointOfInstantiation,
564 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000565 << /*member function*/ 1 << Instantiation->getDeclName()
566 << Instantiation->getDeclContext();
567 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000568 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000569 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000570 Diag(PointOfInstantiation,
571 diag::err_implicit_instantiate_member_undefined)
572 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000573 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000574 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000575 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000576 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000577 Diag(PointOfInstantiation,
578 diag::err_explicit_instantiation_undefined_func_template)
579 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000580 Note = diag::note_explicit_instantiation_here;
581 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000582 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
583 << (TSK != TSK_ImplicitInstantiation)
584 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000585 Note = diag::note_template_decl_here;
586 } else {
587 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
588 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
589 Diag(PointOfInstantiation,
590 diag::err_explicit_instantiation_undefined_var_template)
591 << Instantiation;
592 Instantiation->setInvalidDecl();
593 } else
594 Diag(PointOfInstantiation,
595 diag::err_explicit_instantiation_undefined_member)
596 << /*static data member*/ 2 << Instantiation->getDeclName()
597 << Instantiation->getDeclContext();
598 Note = diag::note_explicit_instantiation_here;
599 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000600 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000601 if (Note) // Diagnostics were emitted.
602 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000603
604 // In general, Instantiation isn't marked invalid to get more than one
605 // error for multiple undefined instantiations. But the code that does
606 // explicit declaration -> explicit definition conversion can't handle
607 // invalid declarations, so mark as invalid in that case.
608 if (TSK == TSK_ExplicitInstantiationDeclaration)
609 Instantiation->setInvalidDecl();
610 return true;
611}
612
Douglas Gregor5101c242008-12-05 18:15:24 +0000613/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
614/// that the template parameter 'PrevDecl' is being shadowed by a new
615/// declaration at location Loc. Returns true to indicate that this is
616/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000617void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000618 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000619
620 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000621 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000622 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000623
624 // C++ [temp.local]p4:
625 // A template-parameter shall not be redeclared within its
626 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000627 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000628 << cast<NamedDecl>(PrevDecl)->getDeclName();
629 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000630}
631
Douglas Gregor463421d2009-03-03 04:44:36 +0000632/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000633/// the parameter D to reference the templated declaration and return a pointer
634/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000635TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
636 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
637 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000638 return Temp;
639 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000640 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000641}
642
Douglas Gregoreb29d182011-01-05 17:40:24 +0000643ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
644 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000646 "Only template template arguments can be pack expansions here");
647 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
648 "Template template argument pack expansion without packs");
649 ParsedTemplateArgument Result(*this);
650 Result.EllipsisLoc = EllipsisLoc;
651 return Result;
652}
653
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000654static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
655 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000657 switch (Arg.getKind()) {
658 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000659 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000660 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000662 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000663 return TemplateArgumentLoc(TemplateArgument(T), DI);
664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000666 case ParsedTemplateArgument::NonType: {
667 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
668 return TemplateArgumentLoc(TemplateArgument(E), E);
669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000671 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000672 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000673 TemplateArgument TArg;
674 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000675 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000676 else
677 TArg = Template;
678 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000679 Arg.getScopeSpec().getWithLocInContext(
680 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000681 Arg.getLocation(),
682 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000683 }
684 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000686 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000687}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000689/// \brief Translates template arguments as provided by the parser
690/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000691void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
692 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000693 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000694 TemplateArgs.addArgument(translateTemplateArgument(*this,
695 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000696}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Richard Smithb80d5402013-06-25 22:21:36 +0000698static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
699 SourceLocation Loc,
700 IdentifierInfo *Name) {
701 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
702 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
703 if (PrevDecl && PrevDecl->isTemplateParameter())
704 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
705}
706
Douglas Gregor5101c242008-12-05 18:15:24 +0000707/// ActOnTypeParameter - Called when a C++ template type parameter
708/// (e.g., "typename T") has been parsed. Typename specifies whether
709/// the keyword "typename" was used to declare the type parameter
710/// (otherwise, "class" was used), and KeyLoc is the location of the
711/// "class" or "typename" keyword. ParamName is the name of the
712/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000713/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000714/// If the type parameter has a default argument, it will be added
715/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000716Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000717 SourceLocation EllipsisLoc,
718 SourceLocation KeyLoc,
719 IdentifierInfo *ParamName,
720 SourceLocation ParamNameLoc,
721 unsigned Depth, unsigned Position,
722 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000723 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000724 assert(S->isTemplateParamScope() &&
725 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000726
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000727 SourceLocation Loc = ParamNameLoc;
728 if (!ParamName)
729 Loc = KeyLoc;
730
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000731 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000732 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000733 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000734 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000735 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000736 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000737
738 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000739 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
740
Douglas Gregor5101c242008-12-05 18:15:24 +0000741 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000742 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000743 IdResolver.AddDecl(Param);
744 }
745
Douglas Gregorf5500772011-01-05 15:48:55 +0000746 // C++0x [temp.param]p9:
747 // A default template-argument may be specified for any kind of
748 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000749 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000750 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000751 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000752 }
753
Douglas Gregordc13ded2010-07-01 00:00:45 +0000754 // Handle the default argument, if provided.
755 if (DefaultArg) {
756 TypeSourceInfo *DefaultTInfo;
757 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000758
Douglas Gregordc13ded2010-07-01 00:00:45 +0000759 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000760
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000761 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000763 UPPC_DefaultArgument))
764 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000765
Douglas Gregordc13ded2010-07-01 00:00:45 +0000766 // Check the template argument itself.
767 if (CheckTemplateArgument(Param, DefaultTInfo)) {
768 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000769 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000771
Richard Smith1469b912015-06-10 00:29:03 +0000772 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774
John McCall48871652010-08-21 09:40:31 +0000775 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000776}
777
Douglas Gregor463421d2009-03-03 04:44:36 +0000778/// \brief Check that the type of a non-type template parameter is
779/// well-formed.
780///
781/// \returns the (possibly-promoted) parameter type if valid;
782/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000783QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
784 SourceLocation Loc) {
785 if (TSI->getType()->isUndeducedType()) {
786 // C++1z [temp.dep.expr]p3:
787 // An id-expression is type-dependent if it contains
788 // - an identifier associated by name lookup with a non-type
789 // template-parameter declared with a type that contains a
790 // placeholder type (7.1.7.4),
791 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
792 }
793
794 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
795}
796
797QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
798 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000799 // We don't allow variably-modified types as the type of non-type template
800 // parameters.
801 if (T->isVariablyModifiedType()) {
802 Diag(Loc, diag::err_variably_modified_nontype_template_param)
803 << T;
804 return QualType();
805 }
806
Douglas Gregor463421d2009-03-03 04:44:36 +0000807 // C++ [temp.param]p4:
808 //
809 // A non-type template-parameter shall have one of the following
810 // (optionally cv-qualified) types:
811 //
812 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000813 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000814 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000815 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000816 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000817 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000818 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000819 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000820 // -- std::nullptr_t.
821 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000822 // If T is a dependent type, we can't do the check now, so we
823 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +0000824 T->isDependentType() ||
825 // Allow use of auto in template parameter declarations.
826 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +0000827 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
828 // are ignored when determining its type.
829 return T.getUnqualifiedType();
830 }
831
Douglas Gregor463421d2009-03-03 04:44:36 +0000832 // C++ [temp.param]p8:
833 //
834 // A non-type template-parameter of type "array of T" or
835 // "function returning T" is adjusted to be of type "pointer to
836 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000837 else if (T->isArrayType() || T->isFunctionType())
838 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839
Douglas Gregor463421d2009-03-03 04:44:36 +0000840 Diag(Loc, diag::err_template_nontype_parm_bad_type)
841 << T;
842
843 return QualType();
844}
845
John McCall48871652010-08-21 09:40:31 +0000846Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
847 unsigned Depth,
848 unsigned Position,
849 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000850 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000851 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +0000852
853 if (TInfo->getType()->isUndeducedType()) {
854 Diag(D.getIdentifierLoc(),
855 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
856 << QualType(TInfo->getType()->getContainedAutoType(), 0);
857 }
Douglas Gregor5101c242008-12-05 18:15:24 +0000858
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000859 assert(S->isTemplateParamScope() &&
860 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000861 bool Invalid = false;
862
Richard Smith15361a22016-12-28 06:27:18 +0000863 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000864 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000865 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000866 Invalid = true;
867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868
Richard Smithb80d5402013-06-25 22:21:36 +0000869 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000870 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000871 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000872 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000873 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000874 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000875 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000876 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000877 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000878
Douglas Gregor5101c242008-12-05 18:15:24 +0000879 if (Invalid)
880 Param->setInvalidDecl();
881
Richard Smithb80d5402013-06-25 22:21:36 +0000882 if (ParamName) {
883 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
884 ParamName);
885
Douglas Gregor5101c242008-12-05 18:15:24 +0000886 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000887 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000888 IdResolver.AddDecl(Param);
889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000890
Douglas Gregorf5500772011-01-05 15:48:55 +0000891 // C++0x [temp.param]p9:
892 // A default template-argument may be specified for any kind of
893 // template-parameter that is not a template parameter pack.
894 if (Default && IsParameterPack) {
895 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000896 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000897 }
898
Douglas Gregordc13ded2010-07-01 00:00:45 +0000899 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000900 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000901 // Check for unexpanded parameter packs.
902 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
903 return Param;
904
Douglas Gregordc13ded2010-07-01 00:00:45 +0000905 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000906 ExprResult DefaultRes =
907 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000908 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000909 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000910 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000911 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000912 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000913
Richard Smith1469b912015-06-10 00:29:03 +0000914 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916
John McCall48871652010-08-21 09:40:31 +0000917 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000918}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000919
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000920/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000921/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000922/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000923Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
924 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000925 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000926 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000927 IdentifierInfo *Name,
928 SourceLocation NameLoc,
929 unsigned Depth,
930 unsigned Position,
931 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000932 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000933 assert(S->isTemplateParamScope() &&
934 "Template template parameter not in template parameter scope!");
935
936 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000937 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000938 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000939 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000940 NameLoc.isInvalid()? TmpLoc : NameLoc,
941 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000942 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000943 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000944
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000945 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000946 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000947 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000948 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
949
John McCall48871652010-08-21 09:40:31 +0000950 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000951 IdResolver.AddDecl(Param);
952 }
953
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000954 if (Params->size() == 0) {
955 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
956 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
957 Param->setInvalidDecl();
958 }
959
Douglas Gregorf5500772011-01-05 15:48:55 +0000960 // C++0x [temp.param]p9:
961 // A default template-argument may be specified for any kind of
962 // template-parameter that is not a template parameter pack.
963 if (IsParameterPack && !Default.isInvalid()) {
964 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
965 Default = ParsedTemplateArgument();
966 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967
Douglas Gregordc13ded2010-07-01 00:00:45 +0000968 if (!Default.isInvalid()) {
969 // Check only that we have a template template argument. We don't want to
970 // try to check well-formedness now, because our template template parameter
971 // might have dependent types in its template parameters, which we wouldn't
972 // be able to match now.
973 //
974 // If none of the template template parameter's template arguments mention
975 // other template parameters, we could actually perform more checking here.
976 // However, it isn't worth doing.
977 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
978 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000979 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000980 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000981 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000984 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000986 DefaultArg.getArgument().getAsTemplate(),
987 UPPC_DefaultArgument))
988 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000989
Richard Smith1469b912015-06-10 00:29:03 +0000990 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000992
John McCall48871652010-08-21 09:40:31 +0000993 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000994}
995
Hubert Tongf608c052016-04-29 18:05:37 +0000996/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
997/// constrained by RequiresClause, that contains the template parameters in
998/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000999TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001000Sema::ActOnTemplateParameterList(unsigned Depth,
1001 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001002 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001003 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +00001004 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001005 SourceLocation RAngleLoc,
1006 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001007 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001008 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001009
David Majnemer902f8c62015-12-27 07:16:27 +00001010 return TemplateParameterList::Create(
1011 Context, TemplateLoc, LAngleLoc,
1012 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001013 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001014}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001015
John McCall3e11ebe2010-03-15 10:12:16 +00001016static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1017 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +00001018 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00001019}
1020
John McCallfaf5fb42010-08-26 23:41:50 +00001021DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00001022Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001023 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001024 IdentifierInfo *Name, SourceLocation NameLoc,
1025 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001026 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00001027 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001028 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001029 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +00001030 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +00001031 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001032 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001033 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001034 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001035 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001036
1037 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001038 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001039 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001040
Abramo Bagnara6150c882010-05-11 21:36:43 +00001041 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1042 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001043
1044 // There is no such thing as an unnamed class template.
1045 if (!Name) {
1046 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001047 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001048 }
1049
Richard Smith6483d222012-04-21 01:27:54 +00001050 // Find any previous declaration with this name. For a friend with no
1051 // scope explicitly specified, we only look for tag declarations (per
1052 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001053 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001054 LookupResult Previous(*this, Name, NameLoc,
1055 (SS.isEmpty() && TUK == TUK_Friend)
1056 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00001057 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001058 if (SS.isNotEmpty() && !SS.isInvalid()) {
1059 SemanticContext = computeDeclContext(SS, true);
1060 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001061 // FIXME: Horrible, horrible hack! We can't currently represent this
1062 // in the AST, and historically we have just ignored such friend
1063 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001064 Diag(NameLoc, TUK == TUK_Friend
1065 ? diag::warn_template_qualified_friend_ignored
1066 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001067 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001068 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001069 }
Mike Stump11289f42009-09-09 15:08:12 +00001070
John McCall0b66eb32010-05-01 00:40:08 +00001071 if (RequireCompleteDeclContext(SS, SemanticContext))
1072 return true;
1073
Simon Pilgrim6905d222016-12-30 22:55:33 +00001074 // If we're adding a template to a dependent context, we may need to
1075 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001076 // now that we know what the current instantiation is.
1077 if (SemanticContext->isDependentContext()) {
1078 ContextRAII SavedContext(*this, SemanticContext);
1079 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1080 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001081 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1082 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +00001083
John McCall27b18f82009-11-17 02:14:36 +00001084 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001085 } else {
1086 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001087
1088 // C++14 [class.mem]p14:
1089 // If T is the name of a class, then each of the following shall have a
1090 // name different from T:
1091 // -- every member template of class T
1092 if (TUK != TUK_Friend &&
1093 DiagnoseClassNameShadow(SemanticContext,
1094 DeclarationNameInfo(Name, NameLoc)))
1095 return true;
1096
John McCall27b18f82009-11-17 02:14:36 +00001097 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001098 }
Mike Stump11289f42009-09-09 15:08:12 +00001099
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001100 if (Previous.isAmbiguous())
1101 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001102
Craig Topperc3ec1492014-05-26 06:22:03 +00001103 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001104 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001105 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001106
Serge Pavlove50bf752016-06-10 04:39:07 +00001107 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1108 // Maybe we will complain about the shadowed template parameter.
1109 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1110 // Just pretend that we didn't see the previous declaration.
1111 PrevDecl = nullptr;
1112 }
1113
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001114 // If there is a previous declaration with the same name, check
1115 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +00001116 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001117 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001118
1119 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001121 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001123 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1124 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001125 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001126 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1127 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1128 PrevClassTemplate
1129 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1130 ->getSpecializedTemplate();
1131 }
1132 }
1133
John McCalld43784f2009-12-18 11:25:59 +00001134 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001135 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136 // [...] When looking for a prior declaration of a class or a function
1137 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001138 // function is neither a qualified name nor a template-id, scopes outside
1139 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001140 if (!SS.isSet()) {
1141 DeclContext *OutermostContext = CurContext;
1142 while (!OutermostContext->isFileContext())
1143 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001144
Richard Smith61e582f2012-04-20 07:12:26 +00001145 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001146 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1147 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1148 SemanticContext = PrevDecl->getDeclContext();
1149 } else {
1150 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001152 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001153 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001154 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001155
1156 // Check that the chosen semantic context doesn't already contain a
1157 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001158 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001159 DeclContext *LookupContext = SemanticContext;
1160 while (LookupContext->isTransparentContext())
1161 LookupContext = LookupContext->getLookupParent();
1162 LookupQualifiedName(Previous, LookupContext);
1163
1164 if (Previous.isAmbiguous())
1165 return true;
1166
1167 if (Previous.begin() != Previous.end())
1168 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001169 }
John McCall90d3bb92009-12-17 23:21:11 +00001170 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001171 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001172 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1173 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001174 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001175
Richard Smithfc805ca2015-07-06 04:43:58 +00001176 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1177 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1178 if (SS.isEmpty() &&
1179 !(PrevClassTemplate &&
1180 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1181 SemanticContext->getRedeclContext()))) {
1182 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1183 Diag(Shadow->getTargetDecl()->getLocation(),
1184 diag::note_using_decl_target);
1185 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1186 // Recover by ignoring the old declaration.
1187 PrevDecl = PrevClassTemplate = nullptr;
1188 }
1189 }
1190
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001191 // TODO Memory management; associated constraints are not always stored.
1192 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1193
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001194 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001195 // Ensure that the template parameter lists are compatible. Skip this check
1196 // for a friend in a dependent context: the template parameter list itself
1197 // could be dependent.
1198 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1199 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001200 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001201 /*Complain=*/true,
1202 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001203 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001204
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001205 // Check for matching associated constraints on redeclarations.
1206 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1207 const bool RedeclACMismatch = [&] {
1208 if (!(CurAC || PrevAC))
1209 return false; // Nothing to check; no mismatch.
1210 if (CurAC && PrevAC) {
1211 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1212 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1213 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1214 if (CurACInfo == PrevACInfo)
1215 return false; // All good; no mismatch.
1216 }
1217 return true;
1218 }();
1219
1220 if (RedeclACMismatch) {
1221 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1222 diag::err_template_different_associated_constraints);
1223 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1224 diag::note_template_prev_declaration) << /*declaration*/0;
1225 return true;
1226 }
1227
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001228 // C++ [temp.class]p4:
1229 // In a redeclaration, partial specialization, explicit
1230 // specialization or explicit instantiation of a class template,
1231 // the class-key shall agree in kind with the original class
1232 // template declaration (7.1.5.3).
1233 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001234 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001235 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001236 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001237 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001238 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001239 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001240 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001241 }
1242
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001243 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001244 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001245 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001246 // If we have a prior definition that is not visible, treat this as
1247 // simply making that previous definition visible.
1248 NamedDecl *Hidden = nullptr;
1249 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001250 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001251 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1252 assert(Tmpl && "original definition of a class template is not a "
1253 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001254 makeMergedDefinitionVisible(Hidden, KWLoc);
1255 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001256 return Def;
1257 }
1258
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001259 Diag(NameLoc, diag::err_redefinition) << Name;
1260 Diag(Def->getLocation(), diag::note_previous_definition);
1261 // FIXME: Would it make sense to try to "forget" the previous
1262 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001263 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001264 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001265 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001266 } else if (PrevDecl) {
1267 // C++ [temp]p5:
1268 // A class template shall not have the same name as any other
1269 // template, class, function, object, enumeration, enumerator,
1270 // namespace, or type in the same scope (3.3), except as specified
1271 // in (14.5.4).
1272 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1273 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001274 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001275 }
1276
Douglas Gregordba32632009-02-10 19:49:53 +00001277 // Check the template parameter list of this declaration, possibly
1278 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001279 // template declaration. Skip this check for a friend in a dependent
1280 // context, because the template parameter list might be dependent.
1281 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001282 CheckTemplateParameterList(
1283 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001284 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1285 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001286 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1287 SemanticContext->isDependentContext())
1288 ? TPC_ClassTemplateMember
1289 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1290 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001291 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001292
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001293 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001294 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001295 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001296 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1297 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001298 : diag::err_member_decl_does_not_match)
1299 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001300 Invalid = true;
1301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001302 }
1303
Vassil Vassilev352e4412017-01-12 09:16:26 +00001304 // If this is a templated friend in a dependent context we should not put it
1305 // on the redecl chain. In some cases, the templated friend can be the most
1306 // recent declaration tricking the template instantiator to make substitutions
1307 // there.
1308 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1309 bool ShouldAddRedecl
1310 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1311
Mike Stump11289f42009-09-09 15:08:12 +00001312 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001313 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001314 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001315 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001316 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001317 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001318 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001319 NewClass->setTemplateParameterListsInfo(
1320 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1321 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001322
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001323 // Add alignment attributes if necessary; these attributes are checked when
1324 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001325 if (TUK == TUK_Definition) {
1326 AddAlignmentAttributesForRecord(NewClass);
1327 AddMsStructLayoutForRecord(NewClass);
1328 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001329
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001330 // Attach the associated constraints when the declaration will not be part of
1331 // a decl chain.
1332 Expr *const ACtoAttach =
1333 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1334
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001335 ClassTemplateDecl *NewTemplate
1336 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1337 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001338 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001339
1340 if (ShouldAddRedecl)
1341 NewTemplate->setPreviousDecl(PrevClassTemplate);
1342
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001343 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001344
Douglas Gregor21823bf2011-12-20 18:11:52 +00001345 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001346 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001347
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001348 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001349 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001350 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001351 assert(T->isDependentType() && "Class template type is not dependent?");
1352 (void)T;
1353
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001354 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001355 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001356 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001357 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1358 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359
Anders Carlsson137108d2009-03-26 01:24:28 +00001360 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001361 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001362 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001363
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001364 // Set the lexical context of these templates
1365 NewClass->setLexicalDeclContext(CurContext);
1366 NewTemplate->setLexicalDeclContext(CurContext);
1367
John McCall9bb74a52009-07-31 02:45:11 +00001368 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001369 NewClass->startDefinition();
1370
1371 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001372 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001373
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001374 if (PrevClassTemplate)
1375 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1376
Rafael Espindola385c0422012-07-13 18:04:45 +00001377 AddPushedVisibilityAttribute(NewClass);
1378
Richard Smith234ff472014-08-23 00:49:01 +00001379 if (TUK != TUK_Friend) {
1380 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1381 Scope *Outer = S;
1382 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1383 Outer = Outer->getParent();
1384 PushOnScopeChains(NewTemplate, Outer);
1385 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001386 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001387 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001388 NewClass->setAccess(PrevClassTemplate->getAccess());
1389 }
John McCall27b5c252009-09-14 21:59:20 +00001390
Richard Smith64017682013-07-17 23:53:16 +00001391 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001392
John McCall27b5c252009-09-14 21:59:20 +00001393 // Friend templates are visible in fairly strange ways.
1394 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001395 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001396 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001397 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1398 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001401
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001402 FriendDecl *Friend = FriendDecl::Create(
1403 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001404 Friend->setAccess(AS_public);
1405 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001406 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001407
Douglas Gregordba32632009-02-10 19:49:53 +00001408 if (Invalid) {
1409 NewTemplate->setInvalidDecl();
1410 NewClass->setInvalidDecl();
1411 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001412
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001413 ActOnDocumentableDecl(NewTemplate);
1414
John McCall48871652010-08-21 09:40:31 +00001415 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001416}
1417
Richard Smith32918772017-02-14 00:25:28 +00001418namespace {
1419/// Transform to convert portions of a constructor declaration into the
1420/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1421struct ConvertConstructorToDeductionGuideTransform {
1422 ConvertConstructorToDeductionGuideTransform(Sema &S,
1423 ClassTemplateDecl *Template)
1424 : SemaRef(S), Template(Template) {}
1425
1426 Sema &SemaRef;
1427 ClassTemplateDecl *Template;
1428
1429 DeclContext *DC = Template->getDeclContext();
1430 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1431 DeclarationName DeductionGuideName =
1432 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1433
1434 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1435
1436 // Index adjustment to apply to convert depth-1 template parameters into
1437 // depth-0 template parameters.
1438 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1439
1440 /// Transform a constructor declaration into a deduction guide.
Richard Smithbc491202017-02-17 20:05:37 +00001441 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1442 CXXConstructorDecl *CD) {
Richard Smith32918772017-02-14 00:25:28 +00001443 SmallVector<TemplateArgument, 16> SubstArgs;
1444
1445 // C++ [over.match.class.deduct]p1:
1446 // -- For each constructor of the class template designated by the
1447 // template-name, a function template with the following properties:
1448
1449 // -- The template parameters are the template parameters of the class
1450 // template followed by the template parameters (including default
1451 // template arguments) of the constructor, if any.
1452 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1453 if (FTD) {
1454 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1455 SmallVector<NamedDecl *, 16> AllParams;
1456 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1457 AllParams.insert(AllParams.begin(),
1458 TemplateParams->begin(), TemplateParams->end());
1459 SubstArgs.reserve(InnerParams->size());
1460
1461 // Later template parameters could refer to earlier ones, so build up
1462 // a list of substituted template arguments as we go.
1463 for (NamedDecl *Param : *InnerParams) {
1464 MultiLevelTemplateArgumentList Args;
1465 Args.addOuterTemplateArguments(SubstArgs);
1466 Args.addOuterTemplateArguments(None);
1467 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1468 if (!NewParam)
1469 return nullptr;
1470 AllParams.push_back(NewParam);
1471 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1472 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1473 }
1474 TemplateParams = TemplateParameterList::Create(
1475 SemaRef.Context, InnerParams->getTemplateLoc(),
1476 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1477 /*FIXME: RequiresClause*/ nullptr);
1478 }
1479
1480 // If we built a new template-parameter-list, track that we need to
1481 // substitute references to the old parameters into references to the
1482 // new ones.
1483 MultiLevelTemplateArgumentList Args;
1484 if (FTD) {
1485 Args.addOuterTemplateArguments(SubstArgs);
1486 Args.addOuterTemplateArguments(None);
1487 }
1488
Richard Smithbc491202017-02-17 20:05:37 +00001489 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
Richard Smith32918772017-02-14 00:25:28 +00001490 .getAsAdjusted<FunctionProtoTypeLoc>();
1491 assert(FPTL && "no prototype for constructor declaration");
1492
1493 // Transform the type of the function, adjusting the return type and
1494 // replacing references to the old parameters with references to the
1495 // new ones.
1496 TypeLocBuilder TLB;
1497 SmallVector<ParmVarDecl*, 8> Params;
1498 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1499 if (NewType.isNull())
1500 return nullptr;
1501 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1502
Richard Smithbc491202017-02-17 20:05:37 +00001503 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1504 CD->getLocStart(), CD->getLocation(),
1505 CD->getLocEnd());
Richard Smith32918772017-02-14 00:25:28 +00001506 }
1507
1508 /// Build a deduction guide with the specified parameter types.
1509 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1510 SourceLocation Loc = Template->getLocation();
1511
1512 // Build the requested type.
1513 FunctionProtoType::ExtProtoInfo EPI;
1514 EPI.HasTrailingReturn = true;
1515 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1516 DeductionGuideName, EPI);
1517 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1518
1519 FunctionProtoTypeLoc FPTL =
1520 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1521
1522 // Build the parameters, needed during deduction / substitution.
1523 SmallVector<ParmVarDecl*, 4> Params;
1524 for (auto T : ParamTypes) {
1525 ParmVarDecl *NewParam = ParmVarDecl::Create(
1526 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1527 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1528 NewParam->setScopeInfo(0, Params.size());
1529 FPTL.setParam(Params.size(), NewParam);
1530 Params.push_back(NewParam);
1531 }
1532
1533 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1534 Loc, Loc, Loc);
1535 }
1536
1537private:
1538 /// Transform a constructor template parameter into a deduction guide template
1539 /// parameter, rebuilding any internal references to earlier parameters and
1540 /// renumbering as we go.
1541 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1542 MultiLevelTemplateArgumentList &Args) {
1543 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1544 // TemplateTypeParmDecl's index cannot be changed after creation, so
1545 // substitute it directly.
1546 auto *NewTTP = TemplateTypeParmDecl::Create(
1547 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1548 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1549 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1550 TTP->isParameterPack());
1551 if (TTP->hasDefaultArgument()) {
1552 TypeSourceInfo *InstantiatedDefaultArg =
1553 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1554 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1555 if (InstantiatedDefaultArg)
1556 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1557 }
1558 return NewTTP;
1559 }
1560
1561 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1562 return transformTemplateParameterImpl(TTP, Args);
1563
1564 return transformTemplateParameterImpl(
1565 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1566 }
1567 template<typename TemplateParmDecl>
1568 TemplateParmDecl *
1569 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1570 MultiLevelTemplateArgumentList &Args) {
1571 // Ask the template instantiator to do the heavy lifting for us, then adjust
1572 // the index of the parameter once it's done.
1573 auto *NewParam =
1574 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1575 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1576 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1577 return NewParam;
1578 }
1579
1580 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1581 FunctionProtoTypeLoc TL,
1582 SmallVectorImpl<ParmVarDecl*> &Params,
1583 MultiLevelTemplateArgumentList &Args) {
1584 SmallVector<QualType, 4> ParamTypes;
1585 const FunctionProtoType *T = TL.getTypePtr();
1586
1587 // -- The types of the function parameters are those of the constructor.
1588 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001589 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001590 if (!NewParam)
1591 return QualType();
1592 ParamTypes.push_back(NewParam->getType());
1593 Params.push_back(NewParam);
1594 }
1595
1596 // -- The return type is the class template specialization designated by
1597 // the template-name and template arguments corresponding to the
1598 // template parameters obtained from the class template.
1599 //
1600 // We use the injected-class-name type of the primary template instead.
1601 // This has the convenient property that it is different from any type that
1602 // the user can write in a deduction-guide (because they cannot enter the
1603 // context of the template), so implicit deduction guides can never collide
1604 // with explicit ones.
1605 QualType ReturnType = DeducedType;
1606 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1607
1608 // Resolving a wording defect, we also inherit the variadicness of the
1609 // constructor.
1610 FunctionProtoType::ExtProtoInfo EPI;
1611 EPI.Variadic = T->isVariadic();
1612 EPI.HasTrailingReturn = true;
1613
1614 QualType Result = SemaRef.BuildFunctionType(
1615 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1616 if (Result.isNull())
1617 return QualType();
1618
1619 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1620 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1621 NewTL.setLParenLoc(TL.getLParenLoc());
1622 NewTL.setRParenLoc(TL.getRParenLoc());
1623 NewTL.setExceptionSpecRange(SourceRange());
1624 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1625 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1626 NewTL.setParam(I, Params[I]);
1627
1628 return Result;
1629 }
1630
1631 ParmVarDecl *
1632 transformFunctionTypeParam(ParmVarDecl *OldParam,
1633 MultiLevelTemplateArgumentList &Args) {
1634 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smithc27b3d72017-02-14 01:49:59 +00001635 TypeSourceInfo *NewDI =
1636 Args.getNumLevels()
1637 ? SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1638 OldParam->getDeclName())
1639 : OldDI;
Richard Smith32918772017-02-14 00:25:28 +00001640 if (!NewDI)
1641 return nullptr;
1642
Richard Smithc27b3d72017-02-14 01:49:59 +00001643 // Canonicalize the type. This (for instance) replaces references to
1644 // typedef members of the current instantiations with the definitions of
1645 // those typedefs, avoiding triggering instantiation of the deduced type
1646 // during deduction.
1647 // FIXME: It would be preferable to retain type sugar and source
1648 // information here (and handle this in substitution instead).
1649 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1650 SemaRef.Context.getCanonicalType(NewDI->getType()),
1651 OldParam->getLocation());
1652
Richard Smith32918772017-02-14 00:25:28 +00001653 // Resolving a wording defect, we also inherit default arguments from the
1654 // constructor.
1655 ExprResult NewDefArg;
1656 if (OldParam->hasDefaultArg()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001657 NewDefArg = Args.getNumLevels()
1658 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1659 : OldParam->getDefaultArg();
Richard Smith32918772017-02-14 00:25:28 +00001660 if (NewDefArg.isInvalid())
1661 return nullptr;
1662 }
1663
1664 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1665 OldParam->getInnerLocStart(),
1666 OldParam->getLocation(),
1667 OldParam->getIdentifier(),
1668 NewDI->getType(),
1669 NewDI,
1670 OldParam->getStorageClass(),
1671 NewDefArg.get());
1672 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1673 OldParam->getFunctionScopeIndex());
1674 return NewParam;
1675 }
1676
1677 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1678 bool Explicit, TypeSourceInfo *TInfo,
1679 SourceLocation LocStart, SourceLocation Loc,
1680 SourceLocation LocEnd) {
Richard Smithbc491202017-02-17 20:05:37 +00001681 DeclarationNameInfo Name(DeductionGuideName, Loc);
Richard Smithefa919a2017-02-16 21:29:21 +00001682 ArrayRef<ParmVarDecl *> Params =
1683 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1684
Richard Smith32918772017-02-14 00:25:28 +00001685 // Build the implicit deduction guide template.
Richard Smithbc491202017-02-17 20:05:37 +00001686 auto *Guide =
1687 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1688 Name, TInfo->getType(), TInfo, LocEnd);
Richard Smith32918772017-02-14 00:25:28 +00001689 Guide->setImplicit();
Richard Smithefa919a2017-02-16 21:29:21 +00001690 Guide->setParams(Params);
1691
1692 for (auto *Param : Params)
1693 Param->setDeclContext(Guide);
Richard Smith32918772017-02-14 00:25:28 +00001694
1695 auto *GuideTemplate = FunctionTemplateDecl::Create(
1696 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1697 GuideTemplate->setImplicit();
1698 Guide->setDescribedFunctionTemplate(GuideTemplate);
1699
1700 if (isa<CXXRecordDecl>(DC)) {
1701 Guide->setAccess(AS_public);
1702 GuideTemplate->setAccess(AS_public);
1703 }
1704
1705 DC->addDecl(GuideTemplate);
1706 return GuideTemplate;
1707 }
1708};
1709}
1710
1711void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1712 SourceLocation Loc) {
1713 DeclContext *DC = Template->getDeclContext();
1714 if (DC->isDependentContext())
1715 return;
1716
1717 ConvertConstructorToDeductionGuideTransform Transform(
1718 *this, cast<ClassTemplateDecl>(Template));
1719 if (!isCompleteType(Loc, Transform.DeducedType))
1720 return;
1721
1722 // Check whether we've already declared deduction guides for this template.
1723 // FIXME: Consider storing a flag on the template to indicate this.
1724 auto Existing = DC->lookup(Transform.DeductionGuideName);
1725 for (auto *D : Existing)
1726 if (D->isImplicit())
1727 return;
1728
1729 // In case we were expanding a pack when we attempted to declare deduction
1730 // guides, turn off pack expansion for everything we're about to do.
1731 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1732 // Create a template instantiation record to track the "instantiation" of
1733 // constructors into deduction guides.
1734 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1735 // this substitution process actually fail?
1736 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1737
1738 // Convert declared constructors into deduction guide templates.
1739 // FIXME: Skip constructors for which deduction must necessarily fail (those
1740 // for which some class template parameter without a default argument never
1741 // appears in a deduced context).
1742 bool AddedAny = false;
1743 bool AddedCopyOrMove = false;
1744 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1745 D = D->getUnderlyingDecl();
1746 if (D->isInvalidDecl() || D->isImplicit())
1747 continue;
1748 D = cast<NamedDecl>(D->getCanonicalDecl());
1749
1750 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00001751 auto *CD =
1752 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00001753 // Class-scope explicit specializations (MS extension) do not result in
1754 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00001755 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00001756 continue;
1757
Richard Smithbc491202017-02-17 20:05:37 +00001758 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00001759 AddedAny = true;
1760
Richard Smith32918772017-02-14 00:25:28 +00001761 AddedCopyOrMove |= CD->isCopyOrMoveConstructor();
1762 }
1763
1764 // Synthesize an X() -> X<...> guide if there were no declared constructors.
1765 // FIXME: The standard doesn't say (how) to do this.
1766 if (!AddedAny)
1767 Transform.buildSimpleDeductionGuide(None);
1768
1769 // Synthesize an X(X<...>) -> X<...> guide if there was no declared constructor
1770 // resembling a copy or move constructor.
1771 // FIXME: The standard doesn't say (how) to do this.
1772 if (!AddedCopyOrMove)
1773 Transform.buildSimpleDeductionGuide(Transform.DeducedType);
1774}
1775
Douglas Gregored5731f2009-11-25 17:50:39 +00001776/// \brief Diagnose the presence of a default template argument on a
1777/// template parameter, which is ill-formed in certain contexts.
1778///
1779/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001780static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001781 Sema::TemplateParamListContext TPC,
1782 SourceLocation ParamLoc,
1783 SourceRange DefArgRange) {
1784 switch (TPC) {
1785 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001786 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001787 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001788 return false;
1789
1790 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001791 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001792 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001793 // A default template-argument shall not be specified in a
1794 // function template declaration or a function template
1795 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00001796 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001797 // template-argument, that declaration shall be a definition and shall be
1798 // the only declaration of the function template in the translation unit.
1799 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001800 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001801 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1802 : diag::ext_template_parameter_default_in_function_template)
1803 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001804 return false;
1805
1806 case Sema::TPC_ClassTemplateMember:
1807 // C++0x [temp.param]p9:
1808 // A default template-argument shall not be specified in the
1809 // template-parameter-lists of the definition of a member of a
1810 // class template that appears outside of the member's class.
1811 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1812 << DefArgRange;
1813 return true;
1814
David Majnemerba8f17a2013-06-25 22:08:55 +00001815 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001816 case Sema::TPC_FriendFunctionTemplate:
1817 // C++ [temp.param]p9:
1818 // A default template-argument shall not be specified in a
1819 // friend template declaration.
1820 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1821 << DefArgRange;
1822 return true;
1823
1824 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1825 // for friend function templates if there is only a single
1826 // declaration (and it is a definition). Strange!
1827 }
1828
David Blaikie8a40f702012-01-17 06:56:22 +00001829 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001830}
1831
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001832/// \brief Check for unexpanded parameter packs within the template parameters
1833/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001834static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1835 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001836 // A template template parameter which is a parameter pack is also a pack
1837 // expansion.
1838 if (TTP->isParameterPack())
1839 return false;
1840
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001841 TemplateParameterList *Params = TTP->getTemplateParameters();
1842 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1843 NamedDecl *P = Params->getParam(I);
1844 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001845 if (!NTTP->isParameterPack() &&
1846 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001847 NTTP->getTypeSourceInfo(),
1848 Sema::UPPC_NonTypeTemplateParameterType))
1849 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001850
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001851 continue;
1852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001853
1854 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001855 = dyn_cast<TemplateTemplateParmDecl>(P))
1856 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1857 return true;
1858 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001859
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001860 return false;
1861}
1862
Douglas Gregordba32632009-02-10 19:49:53 +00001863/// \brief Checks the validity of a template parameter list, possibly
1864/// considering the template parameter list from a previous
1865/// declaration.
1866///
1867/// If an "old" template parameter list is provided, it must be
1868/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1869/// template parameter list.
1870///
1871/// \param NewParams Template parameter list for a new template
1872/// declaration. This template parameter list will be updated with any
1873/// default arguments that are carried through from the previous
1874/// template parameter list.
1875///
1876/// \param OldParams If provided, template parameter list from a
1877/// previous declaration of the same template. Default template
1878/// arguments will be merged from the old template parameter list to
1879/// the new template parameter list.
1880///
Douglas Gregored5731f2009-11-25 17:50:39 +00001881/// \param TPC Describes the context in which we are checking the given
1882/// template parameter list.
1883///
Douglas Gregordba32632009-02-10 19:49:53 +00001884/// \returns true if an error occurred, false otherwise.
1885bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001886 TemplateParameterList *OldParams,
1887 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001888 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001889
Douglas Gregordba32632009-02-10 19:49:53 +00001890 // C++ [temp.param]p10:
1891 // The set of default template-arguments available for use with a
1892 // template declaration or definition is obtained by merging the
1893 // default arguments from the definition (if in scope) and all
1894 // declarations in scope in the same way default function
1895 // arguments are (8.3.6).
1896 bool SawDefaultArgument = false;
1897 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001898
Mike Stumpc89c8e32009-02-11 23:03:27 +00001899 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001900 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001901 if (OldParams)
1902 OldParam = OldParams->begin();
1903
Douglas Gregor0693def2011-01-27 01:40:17 +00001904 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001905 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1906 NewParamEnd = NewParams->end();
1907 NewParam != NewParamEnd; ++NewParam) {
1908 // Variables used to diagnose redundant default arguments
1909 bool RedundantDefaultArg = false;
1910 SourceLocation OldDefaultLoc;
1911 SourceLocation NewDefaultLoc;
1912
David Blaikie651c73c2011-10-19 05:19:50 +00001913 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001914 bool MissingDefaultArg = false;
1915
David Blaikie651c73c2011-10-19 05:19:50 +00001916 // Variable used to diagnose non-final parameter packs
1917 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001918
Douglas Gregordba32632009-02-10 19:49:53 +00001919 if (TemplateTypeParmDecl *NewTypeParm
1920 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001921 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001922 if (NewTypeParm->hasDefaultArgument() &&
1923 DiagnoseDefaultTemplateArgument(*this, TPC,
1924 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001925 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001926 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001927 NewTypeParm->removeDefaultArgument();
1928
1929 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001930 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001931 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001932 if (NewTypeParm->isParameterPack()) {
1933 assert(!NewTypeParm->hasDefaultArgument() &&
1934 "Parameter packs can't have a default argument!");
1935 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001936 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001937 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001938 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1939 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1940 SawDefaultArgument = true;
1941 RedundantDefaultArg = true;
1942 PreviousDefaultArgLoc = NewDefaultLoc;
1943 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1944 // Merge the default argument from the old declaration to the
1945 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001946 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001947 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1948 } else if (NewTypeParm->hasDefaultArgument()) {
1949 SawDefaultArgument = true;
1950 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1951 } else if (SawDefaultArgument)
1952 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001953 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001954 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001955 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001956 if (!NewNonTypeParm->isParameterPack() &&
1957 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001958 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001959 UPPC_NonTypeTemplateParameterType)) {
1960 Invalid = true;
1961 continue;
1962 }
1963
Douglas Gregored5731f2009-11-25 17:50:39 +00001964 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001965 if (NewNonTypeParm->hasDefaultArgument() &&
1966 DiagnoseDefaultTemplateArgument(*this, TPC,
1967 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001968 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001969 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001970 }
1971
Mike Stump12b8ce12009-08-04 21:02:39 +00001972 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001973 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001974 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001975 if (NewNonTypeParm->isParameterPack()) {
1976 assert(!NewNonTypeParm->hasDefaultArgument() &&
1977 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001978 if (!NewNonTypeParm->isPackExpansion())
1979 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001980 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001981 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001982 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1983 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1984 SawDefaultArgument = true;
1985 RedundantDefaultArg = true;
1986 PreviousDefaultArgLoc = NewDefaultLoc;
1987 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1988 // Merge the default argument from the old declaration to the
1989 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001990 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001991 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1992 } else if (NewNonTypeParm->hasDefaultArgument()) {
1993 SawDefaultArgument = true;
1994 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1995 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001996 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001997 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001998 TemplateTemplateParmDecl *NewTemplateParm
1999 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002001 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002002 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002003 Invalid = true;
2004 continue;
2005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006
David Blaikie651c73c2011-10-19 05:19:50 +00002007 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008 if (NewTemplateParm->hasDefaultArgument() &&
2009 DiagnoseDefaultTemplateArgument(*this, TPC,
2010 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002011 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002012 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002013
2014 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002015 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002016 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002017 if (NewTemplateParm->isParameterPack()) {
2018 assert(!NewTemplateParm->hasDefaultArgument() &&
2019 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002020 if (!NewTemplateParm->isPackExpansion())
2021 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002022 } else if (OldTemplateParm &&
2023 hasVisibleDefaultArgument(OldTemplateParm) &&
2024 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002025 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2026 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002027 SawDefaultArgument = true;
2028 RedundantDefaultArg = true;
2029 PreviousDefaultArgLoc = NewDefaultLoc;
2030 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2031 // Merge the default argument from the old declaration to the
2032 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002033 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002034 PreviousDefaultArgLoc
2035 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002036 } else if (NewTemplateParm->hasDefaultArgument()) {
2037 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002038 PreviousDefaultArgLoc
2039 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002040 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002041 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002042 }
2043
Richard Smith1fde8ec2012-09-07 02:06:42 +00002044 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002045 // If a template parameter of a primary class template or alias template
2046 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002047 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002048 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2049 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002050 Diag((*NewParam)->getLocation(),
2051 diag::err_template_param_pack_must_be_last_template_parameter);
2052 Invalid = true;
2053 }
2054
Douglas Gregordba32632009-02-10 19:49:53 +00002055 if (RedundantDefaultArg) {
2056 // C++ [temp.param]p12:
2057 // A template-parameter shall not be given default arguments
2058 // by two different declarations in the same scope.
2059 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2060 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2061 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002062 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002063 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002064 // If a template-parameter of a class template has a default
2065 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002066 // have a default template-argument supplied or be a template parameter
2067 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002068 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002069 diag::err_template_param_default_arg_missing);
2070 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2071 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002072 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002073 }
2074
2075 // If we have an old template parameter list that we're merging
2076 // in, move on to the next parameter.
2077 if (OldParams)
2078 ++OldParam;
2079 }
2080
Douglas Gregor0693def2011-01-27 01:40:17 +00002081 // We were missing some default arguments at the end of the list, so remove
2082 // all of the default arguments.
2083 if (RemoveDefaultArguments) {
2084 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2085 NewParamEnd = NewParams->end();
2086 NewParam != NewParamEnd; ++NewParam) {
2087 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2088 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002089 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002090 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2091 NTTP->removeDefaultArgument();
2092 else
2093 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2094 }
2095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002096
Douglas Gregordba32632009-02-10 19:49:53 +00002097 return Invalid;
2098}
Douglas Gregord32e0282009-02-09 23:23:08 +00002099
John McCalla020a012010-10-20 05:44:58 +00002100namespace {
2101
2102/// A class which looks for a use of a certain level of template
2103/// parameter.
2104struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2105 typedef RecursiveASTVisitor<DependencyChecker> super;
2106
2107 unsigned Depth;
Richard Smith43a833b2017-01-09 23:54:33 +00002108 bool FindLessThanDepth;
Richard Smith57aae072016-12-28 02:37:25 +00002109
2110 // Whether we're looking for a use of a template parameter that makes the
2111 // overall construct type-dependent / a dependent type. This is strictly
2112 // best-effort for now; we may fail to match at all for a dependent type
2113 // in some cases if this is set.
2114 bool IgnoreNonTypeDependent;
2115
John McCalla020a012010-10-20 05:44:58 +00002116 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002117 SourceLocation MatchLoc;
2118
Richard Smith43a833b2017-01-09 23:54:33 +00002119 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent,
2120 bool FindLessThanDepth = false)
2121 : Depth(Depth), FindLessThanDepth(FindLessThanDepth),
2122 IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002123
Richard Smith57aae072016-12-28 02:37:25 +00002124 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith43a833b2017-01-09 23:54:33 +00002125 : DependencyChecker(Params->getDepth(), IgnoreNonTypeDependent) {}
John McCalla020a012010-10-20 05:44:58 +00002126
Richard Smith6056d5e2014-02-09 00:54:43 +00002127 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith43a833b2017-01-09 23:54:33 +00002128 if (FindLessThanDepth ^ (ParmDepth >= Depth)) {
John McCalla020a012010-10-20 05:44:58 +00002129 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002130 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002131 return true;
2132 }
2133 return false;
2134 }
2135
Richard Smith57aae072016-12-28 02:37:25 +00002136 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2137 // Prune out non-type-dependent expressions if requested. This can
2138 // sometimes result in us failing to find a template parameter reference
2139 // (if a value-dependent expression creates a dependent type), but this
2140 // mode is best-effort only.
2141 if (auto *E = dyn_cast_or_null<Expr>(S))
2142 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2143 return true;
2144 return super::TraverseStmt(S, Q);
2145 }
2146
2147 bool TraverseTypeLoc(TypeLoc TL) {
2148 if (IgnoreNonTypeDependent && !TL.isNull() &&
2149 !TL.getType()->isDependentType())
2150 return true;
2151 return super::TraverseTypeLoc(TL);
2152 }
2153
Richard Smith6056d5e2014-02-09 00:54:43 +00002154 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2155 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2156 }
2157
John McCalla020a012010-10-20 05:44:58 +00002158 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002159 // For a best-effort search, keep looking until we find a location.
2160 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002161 }
2162
2163 bool TraverseTemplateName(TemplateName N) {
2164 if (TemplateTemplateParmDecl *PD =
2165 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002166 if (Matches(PD->getDepth()))
2167 return false;
John McCalla020a012010-10-20 05:44:58 +00002168 return super::TraverseTemplateName(N);
2169 }
2170
2171 bool VisitDeclRefExpr(DeclRefExpr *E) {
2172 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002173 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2174 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002175 return false;
John McCalla020a012010-10-20 05:44:58 +00002176 return super::VisitDeclRefExpr(E);
2177 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002178
2179 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2180 return TraverseType(T->getReplacementType());
2181 }
2182
2183 bool
2184 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2185 return TraverseTemplateArgument(T->getArgumentPack());
2186 }
2187
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002188 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2189 return TraverseType(T->getInjectedSpecializationType());
2190 }
John McCalla020a012010-10-20 05:44:58 +00002191};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002192} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002193
Douglas Gregor972fe532011-05-10 18:27:06 +00002194/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002195/// list.
2196static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002197DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002198 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002199 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002200 return Checker.Match;
2201}
2202
Douglas Gregor972fe532011-05-10 18:27:06 +00002203// Find the source range corresponding to the named type in the given
2204// nested-name-specifier, if any.
2205static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2206 QualType T,
2207 const CXXScopeSpec &SS) {
2208 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2209 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2210 if (const Type *CurType = NNS->getAsType()) {
2211 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2212 return NNSLoc.getTypeLoc().getSourceRange();
2213 } else
2214 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002215
Douglas Gregor972fe532011-05-10 18:27:06 +00002216 NNSLoc = NNSLoc.getPrefix();
2217 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002218
Douglas Gregor972fe532011-05-10 18:27:06 +00002219 return SourceRange();
2220}
2221
Mike Stump11289f42009-09-09 15:08:12 +00002222/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002223/// specifier, returning the template parameter list that applies to the
2224/// name.
2225///
2226/// \param DeclStartLoc the start of the declaration that has a scope
2227/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002228///
Douglas Gregor972fe532011-05-10 18:27:06 +00002229/// \param DeclLoc The location of the declaration itself.
2230///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002231/// \param SS the scope specifier that will be matched to the given template
2232/// parameter lists. This scope specifier precedes a qualified name that is
2233/// being declared.
2234///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002235/// \param TemplateId The template-id following the scope specifier, if there
2236/// is one. Used to check for a missing 'template<>'.
2237///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002238/// \param ParamLists the template parameter lists, from the outermost to the
2239/// innermost template parameter lists.
2240///
John McCalle820e5e2010-04-13 20:37:33 +00002241/// \param IsFriend Whether to apply the slightly different rules for
2242/// matching template parameters to scope specifiers in friend
2243/// declarations.
2244///
Richard Smithf445f192017-02-09 21:04:43 +00002245/// \param IsMemberSpecialization will be set true if the scope specifier
2246/// denotes a fully-specialized type, and therefore this is a declaration of
2247/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002248///
Mike Stump11289f42009-09-09 15:08:12 +00002249/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002250/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002251/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002252/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002253/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002254/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002255TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2256 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002257 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002258 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002259 bool &IsMemberSpecialization, bool &Invalid) {
2260 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002261 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002262
Douglas Gregor972fe532011-05-10 18:27:06 +00002263 // The sequence of nested types to which we will match up the template
2264 // parameter lists. We first build this list by starting with the type named
2265 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002266 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002267 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002268 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002269 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002270 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2271 T = Context.getTypeDeclType(Record);
2272 else
2273 T = QualType(SS.getScopeRep()->getAsType(), 0);
2274 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002275
Douglas Gregor972fe532011-05-10 18:27:06 +00002276 // If we found an explicit specialization that prevents us from needing
2277 // 'template<>' headers, this will be set to the location of that
2278 // explicit specialization.
2279 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002280
Douglas Gregor972fe532011-05-10 18:27:06 +00002281 while (!T.isNull()) {
2282 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002283
Douglas Gregor972fe532011-05-10 18:27:06 +00002284 // Retrieve the parent of a record type.
2285 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2286 // If this type is an explicit specialization, we're done.
2287 if (ClassTemplateSpecializationDecl *Spec
2288 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002289 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002290 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2291 ExplicitSpecLoc = Spec->getLocation();
2292 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002293 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002294 } else if (Record->getTemplateSpecializationKind()
2295 == TSK_ExplicitSpecialization) {
2296 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002297 break;
2298 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002299
Douglas Gregor972fe532011-05-10 18:27:06 +00002300 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2301 T = Context.getTypeDeclType(Parent);
2302 else
2303 T = QualType();
2304 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002305 }
2306
Douglas Gregor972fe532011-05-10 18:27:06 +00002307 if (const TemplateSpecializationType *TST
2308 = T->getAs<TemplateSpecializationType>()) {
2309 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2310 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2311 T = Context.getTypeDeclType(Parent);
2312 else
2313 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002314 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002315 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002316 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002317
Douglas Gregor972fe532011-05-10 18:27:06 +00002318 // Look one step prior in a dependent template specialization type.
2319 if (const DependentTemplateSpecializationType *DependentTST
2320 = T->getAs<DependentTemplateSpecializationType>()) {
2321 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2322 T = QualType(NNS->getAsType(), 0);
2323 else
2324 T = QualType();
2325 continue;
2326 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002327
Douglas Gregor972fe532011-05-10 18:27:06 +00002328 // Look one step prior in a dependent name type.
2329 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2330 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2331 T = QualType(NNS->getAsType(), 0);
2332 else
2333 T = QualType();
2334 continue;
2335 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002336
Douglas Gregor972fe532011-05-10 18:27:06 +00002337 // Retrieve the parent of an enumeration type.
2338 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2339 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2340 // check here.
2341 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002342
Douglas Gregor972fe532011-05-10 18:27:06 +00002343 // Get to the parent type.
2344 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2345 T = Context.getTypeDeclType(Parent);
2346 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002347 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002348 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002349 }
Mike Stump11289f42009-09-09 15:08:12 +00002350
Douglas Gregor972fe532011-05-10 18:27:06 +00002351 T = QualType();
2352 }
2353 // Reverse the nested types list, since we want to traverse from the outermost
2354 // to the innermost while checking template-parameter-lists.
2355 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002356
Douglas Gregor972fe532011-05-10 18:27:06 +00002357 // C++0x [temp.expl.spec]p17:
2358 // A member or a member template may be nested within many
2359 // enclosing class templates. In an explicit specialization for
2360 // such a member, the member declaration shall be preceded by a
2361 // template<> for each enclosing class template that is
2362 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002363 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002364
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002365 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002366 if (SawNonEmptyTemplateParameterList) {
2367 Diag(DeclLoc, diag::err_specialize_member_of_template)
2368 << !Recovery << Range;
2369 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002370 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002371 return true;
2372 }
2373
2374 return false;
2375 };
2376
2377 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2378 // Check that we can have an explicit specialization here.
2379 if (CheckExplicitSpecialization(Range, true))
2380 return true;
2381
2382 // We don't have a template header, but we should.
2383 SourceLocation ExpectedTemplateLoc;
2384 if (!ParamLists.empty())
2385 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2386 else
2387 ExpectedTemplateLoc = DeclStartLoc;
2388
2389 Diag(DeclLoc, diag::err_template_spec_needs_header)
2390 << Range
2391 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2392 return false;
2393 };
2394
Douglas Gregor972fe532011-05-10 18:27:06 +00002395 unsigned ParamIdx = 0;
2396 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2397 ++TypeIdx) {
2398 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002399
Douglas Gregor972fe532011-05-10 18:27:06 +00002400 // Whether we expect a 'template<>' header.
2401 bool NeedEmptyTemplateHeader = false;
2402
2403 // Whether we expect a template header with parameters.
2404 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002405
Douglas Gregor972fe532011-05-10 18:27:06 +00002406 // For a dependent type, the set of template parameters that we
2407 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002408 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002409
Douglas Gregor373af9b2011-05-11 23:26:17 +00002410 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002411 // A member or a member template may be nested within many enclosing
2412 // class templates. In an explicit specialization for such a member, the
2413 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002414 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002415 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2416 if (ClassTemplatePartialSpecializationDecl *Partial
2417 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2418 ExpectedTemplateParams = Partial->getTemplateParameters();
2419 NeedNonemptyTemplateHeader = true;
2420 } else if (Record->isDependentType()) {
2421 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002422 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002423 ->getTemplateParameters();
2424 NeedNonemptyTemplateHeader = true;
2425 }
2426 } else if (ClassTemplateSpecializationDecl *Spec
2427 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2428 // C++0x [temp.expl.spec]p4:
2429 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002430 // in the same manner as members of normal classes, and not using
2431 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002432 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2433 NeedEmptyTemplateHeader = true;
2434 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002435 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002436 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002437 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002438 != TSK_ExplicitSpecialization &&
2439 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002440 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002441
Douglas Gregor373af9b2011-05-11 23:26:17 +00002442 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002443 }
2444 } else if (const TemplateSpecializationType *TST
2445 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002446 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002447 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002448 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002449 }
2450 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2451 // FIXME: We actually could/should check the template arguments here
2452 // against the corresponding template parameter list.
2453 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002454 }
2455
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002456 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002457 // In an explicit specialization declaration for a member of a class
2458 // template or a member template that ap- pears in namespace scope, the
2459 // member template and some of its enclosing class templates may remain
2460 // unspecialized, except that the declaration shall not explicitly
2461 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002462 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002463 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002464 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002465 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2466 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002467 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002468 } else
2469 SawNonEmptyTemplateParameterList = true;
2470 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002471
Douglas Gregor972fe532011-05-10 18:27:06 +00002472 if (NeedEmptyTemplateHeader) {
2473 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002474 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002475 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002476 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002477
2478 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002479 if (ParamLists[ParamIdx]->size() > 0) {
2480 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002481 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002482 diag::err_template_param_list_matches_nontemplate)
2483 << T
2484 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2485 ParamLists[ParamIdx]->getRAngleLoc())
2486 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2487 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002488 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002489 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002490
Douglas Gregor972fe532011-05-10 18:27:06 +00002491 // Consume this template header.
2492 ++ParamIdx;
2493 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002494 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002495
2496 if (!IsFriend)
2497 if (DiagnoseMissingExplicitSpecialization(
2498 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002499 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002500
Douglas Gregor972fe532011-05-10 18:27:06 +00002501 continue;
2502 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002503
Douglas Gregor972fe532011-05-10 18:27:06 +00002504 if (NeedNonemptyTemplateHeader) {
2505 // In friend declarations we can have template-ids which don't
2506 // depend on the corresponding template parameter lists. But
2507 // assume that empty parameter lists are supposed to match this
2508 // template-id.
2509 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002510 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002511 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002512 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002513 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002514 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002515 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002516
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002517 if (ParamIdx < ParamLists.size()) {
2518 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002519 if (ExpectedTemplateParams &&
2520 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2521 ExpectedTemplateParams,
2522 true, TPL_TemplateMatch))
2523 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002524
Douglas Gregor972fe532011-05-10 18:27:06 +00002525 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002526 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002527 TPC_ClassTemplateMember))
2528 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002529
Douglas Gregor972fe532011-05-10 18:27:06 +00002530 ++ParamIdx;
2531 continue;
2532 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002533
Douglas Gregor972fe532011-05-10 18:27:06 +00002534 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2535 << T
2536 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2537 Invalid = true;
2538 continue;
2539 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002540 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002541
Douglas Gregord8d297c2009-07-21 23:53:31 +00002542 // If there were at least as many template-ids as there were template
2543 // parameter lists, then there are no template parameter lists remaining for
2544 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002545 if (ParamIdx >= ParamLists.size()) {
2546 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002547 // We don't have a template header for the declaration itself, but we
2548 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002549 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2550 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002551
2552 // Fabricate an empty template parameter list for the invented header.
2553 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002554 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002555 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002556 }
2557
Craig Topperc3ec1492014-05-26 06:22:03 +00002558 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002559 }
Mike Stump11289f42009-09-09 15:08:12 +00002560
Douglas Gregord8d297c2009-07-21 23:53:31 +00002561 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002562 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002563 bool HasAnyExplicitSpecHeader = false;
2564 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002565 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002566 if (ParamLists[I]->size() == 0)
2567 HasAnyExplicitSpecHeader = true;
2568 else
2569 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002570 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002571
Douglas Gregor972fe532011-05-10 18:27:06 +00002572 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002573 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2574 : diag::err_template_spec_extra_headers)
2575 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2576 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002577
2578 // If there was a specialization somewhere, such that 'template<>' is
2579 // not required, and there were any 'template<>' headers, note where the
2580 // specialization occurred.
2581 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002582 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002583 diag::note_explicit_template_spec_does_not_need_header)
2584 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002585
Douglas Gregor972fe532011-05-10 18:27:06 +00002586 // We have a template parameter list with no corresponding scope, which
2587 // means that the resulting template declaration can't be instantiated
2588 // properly (we'll end up with dependent nodes when we shouldn't).
2589 if (!AllExplicitSpecHeaders)
2590 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002591 }
Mike Stump11289f42009-09-09 15:08:12 +00002592
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002593 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002594 // In an explicit specialization declaration for a member of a class
2595 // template or a member template that ap- pears in namespace scope, the
2596 // member template and some of its enclosing class templates may remain
2597 // unspecialized, except that the declaration shall not explicitly
2598 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002599 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002600 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002601 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2602 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002603 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002604
Douglas Gregord8d297c2009-07-21 23:53:31 +00002605 // Return the last template parameter list, which corresponds to the
2606 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002607 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002608}
2609
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002610void Sema::NoteAllFoundTemplates(TemplateName Name) {
2611 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2612 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002613 << (isa<FunctionTemplateDecl>(Template)
2614 ? 0
2615 : isa<ClassTemplateDecl>(Template)
2616 ? 1
2617 : isa<VarTemplateDecl>(Template)
2618 ? 2
2619 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2620 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002621 return;
2622 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002623
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002624 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002625 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002626 IEnd = OST->end();
2627 I != IEnd; ++I)
2628 Diag((*I)->getLocation(), diag::note_template_declared_here)
2629 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002630
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002631 return;
2632 }
2633}
2634
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002635static QualType
2636checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2637 const SmallVectorImpl<TemplateArgument> &Converted,
2638 SourceLocation TemplateLoc,
2639 TemplateArgumentListInfo &TemplateArgs) {
2640 ASTContext &Context = SemaRef.getASTContext();
2641 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002642 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002643 // Specializations of __make_integer_seq<S, T, N> are treated like
2644 // S<T, 0, ..., N-1>.
2645
2646 // C++14 [inteseq.intseq]p1:
2647 // T shall be an integer type.
2648 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2649 SemaRef.Diag(TemplateArgs[1].getLocation(),
2650 diag::err_integer_sequence_integral_element_type);
2651 return QualType();
2652 }
2653
2654 // C++14 [inteseq.make]p1:
2655 // If N is negative the program is ill-formed.
2656 TemplateArgument NumArgsArg = Converted[2];
2657 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2658 if (NumArgs < 0) {
2659 SemaRef.Diag(TemplateArgs[2].getLocation(),
2660 diag::err_integer_sequence_negative_length);
2661 return QualType();
2662 }
2663
2664 QualType ArgTy = NumArgsArg.getIntegralType();
2665 TemplateArgumentListInfo SyntheticTemplateArgs;
2666 // The type argument gets reused as the first template argument in the
2667 // synthetic template argument list.
2668 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2669 // Expand N into 0 ... N-1.
2670 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2671 I < NumArgs; ++I) {
2672 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002673 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2674 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002675 }
2676 // The first template argument will be reused as the template decl that
2677 // our synthetic template arguments will be applied to.
2678 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2679 TemplateLoc, SyntheticTemplateArgs);
2680 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002681
2682 case BTK__type_pack_element:
2683 // Specializations of
2684 // __type_pack_element<Index, T_1, ..., T_N>
2685 // are treated like T_Index.
2686 assert(Converted.size() == 2 &&
2687 "__type_pack_element should be given an index and a parameter pack");
2688
2689 // If the Index is out of bounds, the program is ill-formed.
2690 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2691 llvm::APSInt Index = IndexArg.getAsIntegral();
2692 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2693 "type std::size_t, and hence be non-negative");
2694 if (Index >= Ts.pack_size()) {
2695 SemaRef.Diag(TemplateArgs[0].getLocation(),
2696 diag::err_type_pack_element_out_of_bounds);
2697 return QualType();
2698 }
2699
2700 // We simply return the type at index `Index`.
2701 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2702 return Nth->getAsType();
2703 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002704 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2705}
2706
Douglas Gregordc572a32009-03-30 22:58:21 +00002707QualType Sema::CheckTemplateIdType(TemplateName Name,
2708 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002709 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002710 DependentTemplateName *DTN
2711 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002712 if (DTN && DTN->isIdentifier())
2713 // When building a template-id where the template-name is dependent,
2714 // assume the template is a type template. Either our assumption is
2715 // correct, or the code is ill-formed and will be diagnosed when the
2716 // dependent name is substituted.
2717 return Context.getDependentTemplateSpecializationType(ETK_None,
2718 DTN->getQualifier(),
2719 DTN->getIdentifier(),
2720 TemplateArgs);
2721
Douglas Gregordc572a32009-03-30 22:58:21 +00002722 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002723 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2724 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002725 // We might have a substituted template template parameter pack. If so,
2726 // build a template specialization type for it.
2727 if (Name.getAsSubstTemplateTemplateParmPack())
2728 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002729
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002730 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2731 << Name;
2732 NoteAllFoundTemplates(Name);
2733 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002734 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002735
Douglas Gregorc40290e2009-03-09 23:48:35 +00002736 // Check that the template argument list is well-formed for this
2737 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002738 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002739 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002740 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002741 return QualType();
2742
Douglas Gregorc40290e2009-03-09 23:48:35 +00002743 QualType CanonType;
2744
Douglas Gregor678d76c2011-07-01 01:22:09 +00002745 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002746 if (TypeAliasTemplateDecl *AliasTemplate =
2747 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002748 // Find the canonical type for this type alias template specialization.
2749 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2750 if (Pattern->isInvalidDecl())
2751 return QualType();
2752
2753 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002754 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002755
2756 // Only substitute for the innermost template argument list.
2757 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002758 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002759 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2760 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002761 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002762
Richard Smith802c4b72012-08-23 06:16:52 +00002763 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002764 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002765 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002766 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002767
Richard Smith3f1b5d02011-05-05 21:57:07 +00002768 CanonType = SubstType(Pattern->getUnderlyingType(),
2769 TemplateArgLists, AliasTemplate->getLocation(),
2770 AliasTemplate->getDeclName());
2771 if (CanonType.isNull())
2772 return QualType();
2773 } else if (Name.isDependent() ||
2774 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002775 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002776 // This class template specialization is a dependent
2777 // type. Therefore, its canonical type is another class template
2778 // specialization type that contains all of the converted
2779 // arguments in canonical form. This ensures that, e.g., A<T> and
2780 // A<T, T> have identical types when A is declared as:
2781 //
2782 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00002783 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00002784
2785 // This might work out to be a current instantiation, in which
2786 // case the canonical type needs to be the InjectedClassNameType.
2787 //
2788 // TODO: in theory this could be a simple hashtable lookup; most
2789 // changes to CurContext don't change the set of current
2790 // instantiations.
2791 if (isa<ClassTemplateDecl>(Template)) {
2792 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2793 // If we get out to a namespace, we're done.
2794 if (Ctx->isFileContext()) break;
2795
2796 // If this isn't a record, keep looking.
2797 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2798 if (!Record) continue;
2799
2800 // Look for one of the two cases with InjectedClassNameTypes
2801 // and check whether it's the same template.
2802 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2803 !Record->getDescribedClassTemplate())
2804 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002805
John McCall2408e322010-04-27 00:57:59 +00002806 // Fetch the injected class name type and check whether its
2807 // injected type is equal to the type we just built.
2808 QualType ICNT = Context.getTypeDeclType(Record);
2809 QualType Injected = cast<InjectedClassNameType>(ICNT)
2810 ->getInjectedSpecializationType();
2811
2812 if (CanonType != Injected->getCanonicalTypeInternal())
2813 continue;
2814
2815 // If so, the canonical type of this TST is the injected
2816 // class name type of the record we just found.
2817 assert(ICNT.isCanonical());
2818 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002819 break;
2820 }
2821 }
Mike Stump11289f42009-09-09 15:08:12 +00002822 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002823 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002824 // Find the class template specialization declaration that
2825 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002826 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002827 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002828 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002829 if (!Decl) {
2830 // This is the first time we have referenced this class template
2831 // specialization. Create the canonical declaration and add it to
2832 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002833 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002834 ClassTemplate->getTemplatedDecl()->getTagKind(),
2835 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002836 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002837 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002838 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00002839 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002840 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002841 if (ClassTemplate->isOutOfLine())
2842 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002843 }
2844
Chandler Carruth2acfb222013-09-27 22:14:40 +00002845 // Diagnose uses of this specialization.
2846 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2847
Douglas Gregorc40290e2009-03-09 23:48:35 +00002848 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002849 assert(isa<RecordType>(CanonType) &&
2850 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002851 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2852 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2853 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002854 }
Mike Stump11289f42009-09-09 15:08:12 +00002855
Douglas Gregorc40290e2009-03-09 23:48:35 +00002856 // Build the fully-sugared type for this class template
2857 // specialization, which refers back to the class template
2858 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002859 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002860}
2861
John McCallfaf5fb42010-08-26 23:41:50 +00002862TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002863Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00002864 TemplateTy TemplateD, IdentifierInfo *TemplateII,
2865 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00002866 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002867 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002868 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00002869 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002870 if (SS.isInvalid())
2871 return true;
2872
Richard Smith62559bd2017-02-01 21:36:38 +00002873 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
2874 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
2875
2876 // C++ [temp.res]p3:
2877 // A qualified-id that refers to a type and in which the
2878 // nested-name-specifier depends on a template-parameter (14.6.2)
2879 // shall be prefixed by the keyword typename to indicate that the
2880 // qualified-id denotes a type, forming an
2881 // elaborated-type-specifier (7.1.5.3).
2882 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00002883 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00002884 << SS.getScopeRep() << TemplateII->getName();
2885 // Recover as if 'typename' were specified.
2886 // FIXME: This is not quite correct recovery as we don't transform SS
2887 // into the corresponding dependent form (and we don't diagnose missing
2888 // 'template' keywords within SS as a result).
2889 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
2890 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
2891 TemplateArgsIn, RAngleLoc);
2892 }
2893
2894 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
2895 // it's not actually allowed to be used as a type in most cases. Because
2896 // we annotate it before we know whether it's valid, we have to check for
2897 // this case here.
2898 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00002899 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
2900 Diag(TemplateIILoc,
2901 TemplateKWLoc.isInvalid()
2902 ? diag::err_out_of_line_qualified_id_type_names_constructor
2903 : diag::ext_out_of_line_qualified_id_type_names_constructor)
2904 << TemplateII << 0 /*injected-class-name used as template name*/
2905 << 1 /*if any keyword was present, it was 'template'*/;
2906 }
2907 }
2908
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002909 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002910
Douglas Gregorc40290e2009-03-09 23:48:35 +00002911 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002912 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002913 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002914
Douglas Gregor5a064722011-02-28 17:23:35 +00002915 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002916 QualType T
2917 = Context.getDependentTemplateSpecializationType(ETK_None,
2918 DTN->getQualifier(),
2919 DTN->getIdentifier(),
2920 TemplateArgs);
2921 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002922 TypeLocBuilder TLB;
2923 DependentTemplateSpecializationTypeLoc SpecTL
2924 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002925 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2926 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002927 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00002928 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002929 SpecTL.setLAngleLoc(LAngleLoc);
2930 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002931 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2932 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2933 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2934 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002935
Richard Smith74f02342017-01-19 21:00:13 +00002936 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002937 if (Result.isNull())
2938 return true;
2939
Douglas Gregore7c20652011-03-02 00:47:37 +00002940 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002941 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002942 TemplateSpecializationTypeLoc SpecTL
2943 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002944 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00002945 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002946 SpecTL.setLAngleLoc(LAngleLoc);
2947 SpecTL.setRAngleLoc(RAngleLoc);
2948 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2949 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002950
Abramo Bagnara4244b432012-01-27 08:46:19 +00002951 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2952 // constructor or destructor name (in such a case, the scope specifier
2953 // will be attached to the enclosing Decl or Expr node).
2954 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002955 // Create an elaborated-type-specifier containing the nested-name-specifier.
2956 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2957 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002958 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002959 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2960 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002961
Douglas Gregore7c20652011-03-02 00:47:37 +00002962 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002963}
John McCall06f6fe8d2009-09-04 01:14:41 +00002964
Douglas Gregore7c20652011-03-02 00:47:37 +00002965TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002966 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002967 SourceLocation TagLoc,
2968 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002969 SourceLocation TemplateKWLoc,
2970 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002971 SourceLocation TemplateLoc,
2972 SourceLocation LAngleLoc,
2973 ASTTemplateArgsPtr TemplateArgsIn,
2974 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002975 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002976
Douglas Gregore7c20652011-03-02 00:47:37 +00002977 // Translate the parser's template argument list in our AST format.
2978 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2979 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002980
Douglas Gregore7c20652011-03-02 00:47:37 +00002981 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002982 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002983 ElaboratedTypeKeyword Keyword
2984 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002985
Douglas Gregore7c20652011-03-02 00:47:37 +00002986 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2987 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00002988 DTN->getQualifier(),
2989 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00002990 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002991
2992 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00002993 TypeLocBuilder TLB;
2994 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002995 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2996 SpecTL.setElaboratedKeywordLoc(TagLoc);
2997 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002998 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002999 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003000 SpecTL.setLAngleLoc(LAngleLoc);
3001 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003002 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3003 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3004 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3005 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003006
3007 if (TypeAliasTemplateDecl *TAT =
3008 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3009 // C++0x [dcl.type.elab]p2:
3010 // If the identifier resolves to a typedef-name or the simple-template-id
3011 // resolves to an alias template specialization, the
3012 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003013 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3014 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003015 Diag(TAT->getLocation(), diag::note_declared_at);
3016 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003017
Douglas Gregore7c20652011-03-02 00:47:37 +00003018 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3019 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003020 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003021
Douglas Gregore7c20652011-03-02 00:47:37 +00003022 // Check the tag kind
3023 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003024 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003025
John McCalld8fe9af2009-09-08 17:47:29 +00003026 IdentifierInfo *Id = D->getIdentifier();
3027 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003028
Richard Trieucaa33d32011-06-10 03:11:26 +00003029 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003030 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003031 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003032 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003033 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003034 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003035 }
3036 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003037
Douglas Gregore7c20652011-03-02 00:47:37 +00003038 // Provide source-location information for the template specialization.
3039 TypeLocBuilder TLB;
3040 TemplateSpecializationTypeLoc SpecTL
3041 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003042 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003043 SpecTL.setTemplateNameLoc(TemplateLoc);
3044 SpecTL.setLAngleLoc(LAngleLoc);
3045 SpecTL.setRAngleLoc(RAngleLoc);
3046 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3047 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003048
Douglas Gregore7c20652011-03-02 00:47:37 +00003049 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003050 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003051 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3052 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003053 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003054 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3055 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003056}
3057
Larisse Voufo39a1e502013-08-06 01:03:05 +00003058static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3059 NamedDecl *PrevDecl,
3060 SourceLocation Loc,
3061 bool IsPartialSpecialization);
3062
3063static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003064
Richard Smith300e0c32013-09-24 04:49:23 +00003065static bool isTemplateArgumentTemplateParameter(
3066 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3067 switch (Arg.getKind()) {
3068 case TemplateArgument::Null:
3069 case TemplateArgument::NullPtr:
3070 case TemplateArgument::Integral:
3071 case TemplateArgument::Declaration:
3072 case TemplateArgument::Pack:
3073 case TemplateArgument::TemplateExpansion:
3074 return false;
3075
3076 case TemplateArgument::Type: {
3077 QualType Type = Arg.getAsType();
3078 const TemplateTypeParmType *TPT =
3079 Arg.getAsType()->getAs<TemplateTypeParmType>();
3080 return TPT && !Type.hasQualifiers() &&
3081 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3082 }
3083
3084 case TemplateArgument::Expression: {
3085 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3086 if (!DRE || !DRE->getDecl())
3087 return false;
3088 const NonTypeTemplateParmDecl *NTTP =
3089 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3090 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3091 }
3092
3093 case TemplateArgument::Template:
3094 const TemplateTemplateParmDecl *TTP =
3095 dyn_cast_or_null<TemplateTemplateParmDecl>(
3096 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3097 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3098 }
3099 llvm_unreachable("unexpected kind of template argument");
3100}
3101
3102static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3103 ArrayRef<TemplateArgument> Args) {
3104 if (Params->size() != Args.size())
3105 return false;
3106
3107 unsigned Depth = Params->getDepth();
3108
3109 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3110 TemplateArgument Arg = Args[I];
3111
3112 // If the parameter is a pack expansion, the argument must be a pack
3113 // whose only element is a pack expansion.
3114 if (Params->getParam(I)->isParameterPack()) {
3115 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3116 !Arg.pack_begin()->isPackExpansion())
3117 return false;
3118 Arg = Arg.pack_begin()->getPackExpansionPattern();
3119 }
3120
3121 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3122 return false;
3123 }
3124
3125 return true;
3126}
3127
Richard Smith4b55a9c2014-04-17 03:29:33 +00003128/// Convert the parser's template argument list representation into our form.
3129static TemplateArgumentListInfo
3130makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3131 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3132 TemplateId.RAngleLoc);
3133 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3134 TemplateId.NumArgs);
3135 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3136 return TemplateArgs;
3137}
3138
Richard Smith0e617ec2016-12-27 07:56:27 +00003139template<typename PartialSpecDecl>
3140static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3141 if (Partial->getDeclContext()->isDependentContext())
3142 return;
3143
3144 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3145 // for non-substitution-failure issues?
3146 TemplateDeductionInfo Info(Partial->getLocation());
3147 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3148 return;
3149
3150 auto *Template = Partial->getSpecializedTemplate();
3151 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003152 diag::ext_partial_spec_not_more_specialized_than_primary)
3153 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003154
3155 if (Info.hasSFINAEDiagnostic()) {
3156 PartialDiagnosticAt Diag = {SourceLocation(),
3157 PartialDiagnostic::NullDiagnostic()};
3158 Info.takeSFINAEDiagnostic(Diag);
3159 SmallString<128> SFINAEArgString;
3160 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3161 S.Diag(Diag.first,
3162 diag::note_partial_spec_not_more_specialized_than_primary)
3163 << SFINAEArgString;
3164 }
3165
3166 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3167}
3168
Richard Smith4e05eaa2017-02-16 00:36:47 +00003169static void
3170noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3171 const llvm::SmallBitVector &DeducibleParams) {
3172 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3173 if (!DeducibleParams[I]) {
3174 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3175 if (Param->getDeclName())
3176 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3177 << Param->getDeclName();
3178 else
3179 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3180 << "(anonymous)";
3181 }
3182 }
3183}
3184
3185
Richard Smith57aae072016-12-28 02:37:25 +00003186template<typename PartialSpecDecl>
3187static void checkTemplatePartialSpecialization(Sema &S,
3188 PartialSpecDecl *Partial) {
3189 // C++1z [temp.class.spec]p8: (DR1495)
3190 // - The specialization shall be more specialized than the primary
3191 // template (14.5.5.2).
3192 checkMoreSpecializedThanPrimary(S, Partial);
3193
3194 // C++ [temp.class.spec]p8: (DR1315)
3195 // - Each template-parameter shall appear at least once in the
3196 // template-id outside a non-deduced context.
3197 // C++1z [temp.class.spec.match]p3 (P0127R2)
3198 // If the template arguments of a partial specialization cannot be
3199 // deduced because of the structure of its template-parameter-list
3200 // and the template-id, the program is ill-formed.
3201 auto *TemplateParams = Partial->getTemplateParameters();
3202 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3203 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3204 TemplateParams->getDepth(), DeducibleParams);
3205
3206 if (!DeducibleParams.all()) {
3207 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3208 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3209 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3210 << (NumNonDeducible > 1)
3211 << SourceRange(Partial->getLocation(),
3212 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003213 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003214 }
3215}
3216
3217void Sema::CheckTemplatePartialSpecialization(
3218 ClassTemplatePartialSpecializationDecl *Partial) {
3219 checkTemplatePartialSpecialization(*this, Partial);
3220}
3221
3222void Sema::CheckTemplatePartialSpecialization(
3223 VarTemplatePartialSpecializationDecl *Partial) {
3224 checkTemplatePartialSpecialization(*this, Partial);
3225}
3226
Richard Smith4e05eaa2017-02-16 00:36:47 +00003227void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3228 // C++1z [temp.param]p11:
3229 // A template parameter of a deduction guide template that does not have a
3230 // default-argument shall be deducible from the parameter-type-list of the
3231 // deduction guide template.
3232 auto *TemplateParams = TD->getTemplateParameters();
3233 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3234 MarkDeducedTemplateParameters(TD, DeducibleParams);
3235 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3236 // A parameter pack is deducible (to an empty pack).
3237 auto *Param = TemplateParams->getParam(I);
3238 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3239 DeducibleParams[I] = true;
3240 }
3241
3242 if (!DeducibleParams.all()) {
3243 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3244 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3245 << (NumNonDeducible > 1);
3246 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3247 }
3248}
3249
Larisse Voufo39a1e502013-08-06 01:03:05 +00003250DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003251 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003252 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003253 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003254 // D must be variable template id.
3255 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
3256 "Variable template specialization is declared with a template it.");
3257
3258 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003259 TemplateArgumentListInfo TemplateArgs =
3260 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003261 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3262 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3263 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003264
Richard Smithbeef3452014-01-16 23:39:20 +00003265 TemplateName Name = TemplateId->Template.get();
3266
3267 // The template-id must name a variable template.
3268 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003269 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3270 if (!VarTemplate) {
3271 NamedDecl *FnTemplate;
3272 if (auto *OTS = Name.getAsOverloadedTemplate())
3273 FnTemplate = *OTS->begin();
3274 else
3275 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3276 if (FnTemplate)
3277 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3278 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003279 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3280 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003281 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003282
3283 // Check for unexpanded parameter packs in any of the template arguments.
3284 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3285 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3286 UPPC_PartialSpecialization))
3287 return true;
3288
3289 // Check that the template argument list is well-formed for this
3290 // template.
3291 SmallVector<TemplateArgument, 4> Converted;
3292 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3293 false, Converted))
3294 return true;
3295
Larisse Voufo39a1e502013-08-06 01:03:05 +00003296 // Find the variable template (partial) specialization declaration that
3297 // corresponds to these arguments.
3298 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003299 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3300 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003301 return true;
3302
Richard Smith57aae072016-12-28 02:37:25 +00003303 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3304 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003305 bool InstantiationDependent;
3306 if (!Name.isDependent() &&
3307 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003308 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003309 InstantiationDependent)) {
3310 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3311 << VarTemplate->getDeclName();
3312 IsPartialSpecialization = false;
3313 }
Richard Smith300e0c32013-09-24 04:49:23 +00003314
3315 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3316 Converted)) {
3317 // C++ [temp.class.spec]p9b3:
3318 //
3319 // -- The argument list of the specialization shall not be identical
3320 // to the implicit argument list of the primary template.
3321 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3322 << /*variable template*/ 1
3323 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3324 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3325 // FIXME: Recover from this by treating the declaration as a redeclaration
3326 // of the primary template.
3327 return true;
3328 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003329 }
3330
Craig Topperc3ec1492014-05-26 06:22:03 +00003331 void *InsertPos = nullptr;
3332 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003333
3334 if (IsPartialSpecialization)
3335 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003336 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003337 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003338 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003339
Craig Topperc3ec1492014-05-26 06:22:03 +00003340 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003341
3342 // Check whether we can declare a variable template specialization in
3343 // the current scope.
3344 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3345 TemplateNameLoc,
3346 IsPartialSpecialization))
3347 return true;
3348
3349 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3350 // Since the only prior variable template specialization with these
3351 // arguments was referenced but not declared, reuse that
3352 // declaration node as our own, updating its source location and
3353 // the list of outer template parameters to reflect our new declaration.
3354 Specialization = PrevDecl;
3355 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003356 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003357 } else if (IsPartialSpecialization) {
3358 // Create a new class template partial specialization declaration node.
3359 VarTemplatePartialSpecializationDecl *PrevPartial =
3360 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003361 VarTemplatePartialSpecializationDecl *Partial =
3362 VarTemplatePartialSpecializationDecl::Create(
3363 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3364 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003365 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003366
3367 if (!PrevPartial)
3368 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3369 Specialization = Partial;
3370
3371 // If we are providing an explicit specialization of a member variable
3372 // template specialization, make a note of that.
3373 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003374 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003375
Richard Smith57aae072016-12-28 02:37:25 +00003376 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003377 } else {
3378 // Create a new class template specialization declaration node for
3379 // this explicit specialization or friend declaration.
3380 Specialization = VarTemplateSpecializationDecl::Create(
3381 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003382 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003383 Specialization->setTemplateArgsInfo(TemplateArgs);
3384
3385 if (!PrevDecl)
3386 VarTemplate->AddSpecialization(Specialization, InsertPos);
3387 }
3388
3389 // C++ [temp.expl.spec]p6:
3390 // If a template, a member template or the member of a class template is
3391 // explicitly specialized then that specialization shall be declared
3392 // before the first use of that specialization that would cause an implicit
3393 // instantiation to take place, in every translation unit in which such a
3394 // use occurs; no diagnostic is required.
3395 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3396 bool Okay = false;
3397 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3398 // Is there any previous explicit specialization declaration?
3399 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3400 Okay = true;
3401 break;
3402 }
3403 }
3404
3405 if (!Okay) {
3406 SourceRange Range(TemplateNameLoc, RAngleLoc);
3407 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3408 << Name << Range;
3409
3410 Diag(PrevDecl->getPointOfInstantiation(),
3411 diag::note_instantiation_required_here)
3412 << (PrevDecl->getTemplateSpecializationKind() !=
3413 TSK_ImplicitInstantiation);
3414 return true;
3415 }
3416 }
3417
3418 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3419 Specialization->setLexicalDeclContext(CurContext);
3420
3421 // Add the specialization into its lexical context, so that it can
3422 // be seen when iterating through the list of declarations in that
3423 // context. However, specializations are not found by name lookup.
3424 CurContext->addDecl(Specialization);
3425
3426 // Note that this is an explicit specialization.
3427 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3428
3429 if (PrevDecl) {
3430 // Check that this isn't a redefinition of this specialization,
3431 // merging with previous declarations.
3432 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3433 ForRedeclaration);
3434 PrevSpec.addDecl(PrevDecl);
3435 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003436 } else if (Specialization->isStaticDataMember() &&
3437 Specialization->isOutOfLine()) {
3438 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003439 }
3440
3441 // Link instantiations of static data members back to the template from
3442 // which they were instantiated.
3443 if (Specialization->isStaticDataMember())
3444 Specialization->setInstantiationOfStaticDataMember(
3445 VarTemplate->getTemplatedDecl(),
3446 Specialization->getSpecializationKind());
3447
3448 return Specialization;
3449}
3450
3451namespace {
3452/// \brief A partial specialization whose template arguments have matched
3453/// a given template-id.
3454struct PartialSpecMatchResult {
3455 VarTemplatePartialSpecializationDecl *Partial;
3456 TemplateArgumentList *Args;
3457};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003458} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003459
3460DeclResult
3461Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3462 SourceLocation TemplateNameLoc,
3463 const TemplateArgumentListInfo &TemplateArgs) {
3464 assert(Template && "A variable template id without template?");
3465
3466 // Check that the template argument list is well-formed for this template.
3467 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003468 if (CheckTemplateArgumentList(
3469 Template, TemplateNameLoc,
3470 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003471 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003472 return true;
3473
3474 // Find the variable template specialization declaration that
3475 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003476 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003477 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003478 Converted, InsertPos)) {
3479 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003480 // If we already have a variable template specialization, return it.
3481 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003482 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003483
3484 // This is the first time we have referenced this variable template
3485 // specialization. Create the canonical declaration and add it to
3486 // the set of specializations, based on the closest partial specialization
3487 // that it represents. That is,
3488 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3489 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003490 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003491 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3492 bool AmbiguousPartialSpec = false;
3493 typedef PartialSpecMatchResult MatchResult;
3494 SmallVector<MatchResult, 4> Matched;
3495 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003496 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3497 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003498
3499 // 1. Attempt to find the closest partial specialization that this
3500 // specializes, if any.
3501 // If any of the template arguments is dependent, then this is probably
3502 // a placeholder for an incomplete declarative context; which must be
3503 // complete by instantiation time. Thus, do not search through the partial
3504 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003505 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3506 // Perhaps better after unification of DeduceTemplateArguments() and
3507 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003508 bool InstantiationDependent = false;
3509 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3510 TemplateArgs, InstantiationDependent)) {
3511
3512 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3513 Template->getPartialSpecializations(PartialSpecs);
3514
3515 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3516 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3517 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3518
3519 if (TemplateDeductionResult Result =
3520 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3521 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003522 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003523 FailedCandidates.addCandidate().set(
3524 DeclAccessPair::make(Template, AS_public), Partial,
3525 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003526 (void)Result;
3527 } else {
3528 Matched.push_back(PartialSpecMatchResult());
3529 Matched.back().Partial = Partial;
3530 Matched.back().Args = Info.take();
3531 }
3532 }
3533
Larisse Voufo39a1e502013-08-06 01:03:05 +00003534 if (Matched.size() >= 1) {
3535 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3536 if (Matched.size() == 1) {
3537 // -- If exactly one matching specialization is found, the
3538 // instantiation is generated from that specialization.
3539 // We don't need to do anything for this.
3540 } else {
3541 // -- If more than one matching specialization is found, the
3542 // partial order rules (14.5.4.2) are used to determine
3543 // whether one of the specializations is more specialized
3544 // than the others. If none of the specializations is more
3545 // specialized than all of the other matching
3546 // specializations, then the use of the variable template is
3547 // ambiguous and the program is ill-formed.
3548 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3549 PEnd = Matched.end();
3550 P != PEnd; ++P) {
3551 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3552 PointOfInstantiation) ==
3553 P->Partial)
3554 Best = P;
3555 }
3556
3557 // Determine if the best partial specialization is more specialized than
3558 // the others.
3559 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3560 PEnd = Matched.end();
3561 P != PEnd; ++P) {
3562 if (P != Best && getMoreSpecializedPartialSpecialization(
3563 P->Partial, Best->Partial,
3564 PointOfInstantiation) != Best->Partial) {
3565 AmbiguousPartialSpec = true;
3566 break;
3567 }
3568 }
3569 }
3570
3571 // Instantiate using the best variable template partial specialization.
3572 InstantiationPattern = Best->Partial;
3573 InstantiationArgs = Best->Args;
3574 } else {
3575 // -- If no match is found, the instantiation is generated
3576 // from the primary template.
3577 // InstantiationPattern = Template->getTemplatedDecl();
3578 }
3579 }
3580
Larisse Voufo39a1e502013-08-06 01:03:05 +00003581 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00003582 // Note that we do not instantiate a definition until we see an odr-use
3583 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003584 // FIXME: LateAttrs et al.?
3585 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3586 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3587 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3588 if (!Decl)
3589 return true;
3590
3591 if (AmbiguousPartialSpec) {
3592 // Partial ordering did not produce a clear winner. Complain.
3593 Decl->setInvalidDecl();
3594 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3595 << Decl;
3596
3597 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00003598 for (MatchResult P : Matched)
3599 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3600 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3601 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003602 return true;
3603 }
3604
3605 if (VarTemplatePartialSpecializationDecl *D =
3606 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3607 Decl->setInstantiationOf(D, InstantiationArgs);
3608
Richard Smith6739a102016-05-05 00:56:12 +00003609 checkSpecializationVisibility(TemplateNameLoc, Decl);
3610
Larisse Voufo39a1e502013-08-06 01:03:05 +00003611 assert(Decl && "No variable template specialization?");
3612 return Decl;
3613}
3614
3615ExprResult
3616Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3617 const DeclarationNameInfo &NameInfo,
3618 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3619 const TemplateArgumentListInfo *TemplateArgs) {
3620
3621 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3622 *TemplateArgs);
3623 if (Decl.isInvalid())
3624 return ExprError();
3625
3626 VarDecl *Var = cast<VarDecl>(Decl.get());
3627 if (!Var->getTemplateSpecializationKind())
3628 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3629 NameInfo.getLoc());
3630
3631 // Build an ordinary singleton decl ref.
3632 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003633 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003634}
3635
John McCalldadc5752010-08-24 06:29:42 +00003636ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003637 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003638 LookupResult &R,
3639 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003640 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003641 // FIXME: Can we do any checking at this point? I guess we could check the
3642 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003643 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003644 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003645 // foo<int> could identify a single function unambiguously
3646 // This approach does NOT work, since f<int>(1);
3647 // gets resolved prior to resorting to overload resolution
3648 // i.e., template<class T> void f(double);
3649 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003650
3651 // These should be filtered out by our callers.
3652 assert(!R.empty() && "empty lookup results when building templateid");
3653 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3654
Larisse Voufo39a1e502013-08-06 01:03:05 +00003655 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003656 bool InstantiationDependent;
3657 if (R.getAsSingle<VarTemplateDecl>() &&
3658 !TemplateSpecializationType::anyDependentTemplateArguments(
3659 *TemplateArgs, InstantiationDependent)) {
3660 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3661 R.getAsSingle<VarTemplateDecl>(),
3662 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003663 }
3664
John McCall58cc69d2010-01-27 01:50:18 +00003665 // We don't want lookup warnings at this point.
3666 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667
John McCalle66edc12009-11-24 19:00:30 +00003668 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003669 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003670 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003671 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003672 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003673 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003674 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003675
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003676 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003677}
3678
John McCalle66edc12009-11-24 19:00:30 +00003679// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003680ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003681Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003682 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003683 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003684 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003685
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003686 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003687 DeclContext *DC;
3688 if (!(DC = computeDeclContext(SS, false)) ||
3689 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003690 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003691 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003692
Douglas Gregor786123d2010-05-21 23:18:07 +00003693 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003694 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003695 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003696 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003697
John McCalle66edc12009-11-24 19:00:30 +00003698 if (R.isAmbiguous())
3699 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003700
John McCalle66edc12009-11-24 19:00:30 +00003701 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003702 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3703 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003704 return ExprError();
3705 }
3706
3707 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003708 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003709 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003710 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003711 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3712 return ExprError();
3713 }
3714
Abramo Bagnara7945c982012-01-27 09:46:47 +00003715 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003716}
3717
Douglas Gregorb67535d2009-03-31 00:43:58 +00003718/// \brief Form a dependent template name.
3719///
3720/// This action forms a dependent template name given the template
3721/// name and its (presumably dependent) scope specifier. For
3722/// example, given "MetaFun::template apply", the scope specifier \p
3723/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3724/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003725TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003726 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003727 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003728 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003729 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003730 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00003731 TemplateTy &Result,
3732 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003733 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3734 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003735 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003736 diag::warn_cxx98_compat_template_outside_of_template :
3737 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003738 << FixItHint::CreateRemoval(TemplateKWLoc);
3739
Craig Topperc3ec1492014-05-26 06:22:03 +00003740 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003741 if (SS.isSet())
3742 LookupCtx = computeDeclContext(SS, EnteringContext);
3743 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003744 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003745 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003746 // C++0x [temp.names]p5:
3747 // If a name prefixed by the keyword template is not the name of
3748 // a template, the program is ill-formed. [Note: the keyword
3749 // template may not be applied to non-template members of class
3750 // templates. -end note ] [ Note: as is the case with the
3751 // typename prefix, the template prefix is allowed in cases
3752 // where it is not strictly necessary; i.e., when the
3753 // nested-name-specifier or the expression on the left of the ->
3754 // or . is not dependent on a template-parameter, or the use
3755 // does not appear in the scope of a template. -end note]
3756 //
3757 // Note: C++03 was more strict here, because it banned the use of
3758 // the "template" keyword prior to a template-name that was not a
3759 // dependent name. C++ DR468 relaxed this requirement (the
3760 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003761 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003762 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003763 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003764 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003765 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003766 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3767 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003768 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3769 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003770 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003771 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003772 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003773 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003774 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003775 << Name.getSourceRange()
3776 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003777 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003778 } else {
3779 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00003780 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
3781 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
3782 Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
3783 LookupRD->getIdentifier() == Name.Identifier) {
3784 // C++14 [class.qual]p2:
3785 // In a lookup in which function names are not ignored and the
3786 // nested-name-specifier nominates a class C, if the name specified
3787 // [...] is the injected-class-name of C, [...] the name is instead
3788 // considered to name the constructor
3789 //
3790 // We don't get here if naming the constructor would be valid, so we
3791 // just reject immediately and recover by treating the
3792 // injected-class-name as naming the template.
3793 Diag(Name.getLocStart(),
3794 diag::ext_out_of_line_qualified_id_type_names_constructor)
3795 << Name.Identifier << 0 /*injected-class-name used as template name*/
3796 << 1 /*'template' keyword was used*/;
3797 }
Douglas Gregorbb119652010-06-16 23:00:59 +00003798 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003799 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003800 }
3801
Aaron Ballman4a979672014-01-03 13:56:08 +00003802 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003803
Douglas Gregor3cf81312009-11-03 23:16:33 +00003804 switch (Name.getKind()) {
3805 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003806 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003807 Name.Identifier));
3808 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003809
Douglas Gregor71395fa2009-11-04 00:56:37 +00003810 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003811 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003812 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003813 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003814
3815 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003816 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003817
Douglas Gregor3cf81312009-11-03 23:16:33 +00003818 default:
3819 break;
3820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003821
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003822 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003823 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003824 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003825 << Name.getSourceRange()
3826 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003827 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003828}
3829
Mike Stump11289f42009-09-09 15:08:12 +00003830bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003831 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003832 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003833 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003834 QualType ArgType;
3835 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003836
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003837 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003838 switch(Arg.getKind()) {
3839 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003840 // C++ [temp.arg.type]p1:
3841 // A template-argument for a template-parameter which is a
3842 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003843 ArgType = Arg.getAsType();
3844 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003845 break;
3846 case TemplateArgument::Template: {
3847 // We have a template type parameter but the template argument
3848 // is a template without any arguments.
3849 SourceRange SR = AL.getSourceRange();
3850 TemplateName Name = Arg.getAsTemplate();
3851 Diag(SR.getBegin(), diag::err_template_missing_args)
Richard Smith0c062b42017-01-14 02:19:59 +00003852 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003853 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3854 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003855
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003856 return true;
3857 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003858 case TemplateArgument::Expression: {
3859 // We have a template type parameter but the template argument is an
3860 // expression; see if maybe it is missing the "typename" keyword.
3861 CXXScopeSpec SS;
3862 DeclarationNameInfo NameInfo;
3863
3864 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3865 SS.Adopt(ArgExpr->getQualifierLoc());
3866 NameInfo = ArgExpr->getNameInfo();
3867 } else if (DependentScopeDeclRefExpr *ArgExpr =
3868 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3869 SS.Adopt(ArgExpr->getQualifierLoc());
3870 NameInfo = ArgExpr->getNameInfo();
3871 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3872 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003873 if (ArgExpr->isImplicitAccess()) {
3874 SS.Adopt(ArgExpr->getQualifierLoc());
3875 NameInfo = ArgExpr->getMemberNameInfo();
3876 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003877 }
3878
Reid Kleckner377c1592014-06-10 23:29:48 +00003879 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003880 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3881 LookupParsedName(Result, CurScope, &SS);
3882
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003883 if (Result.getAsSingle<TypeDecl>() ||
3884 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003885 LookupResult::NotFoundInCurrentInstantiation) {
3886 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003887 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003888 Diag(Loc, getLangOpts().MSVCCompat
3889 ? diag::ext_ms_template_type_arg_missing_typename
3890 : diag::err_template_arg_must_be_type_suggest)
3891 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003892 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003893
3894 // Recover by synthesizing a type using the location information that we
3895 // already have.
3896 ArgType =
3897 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3898 TypeLocBuilder TLB;
3899 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3900 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3901 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3902 TL.setNameLoc(NameInfo.getLoc());
3903 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3904
3905 // Overwrite our input TemplateArgumentLoc so that we can recover
3906 // properly.
3907 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3908 TemplateArgumentLocInfo(TSI));
3909
3910 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003911 }
3912 }
3913 // fallthrough
3914 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003915 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003916 // We have a template type parameter but the template argument
3917 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003918 SourceRange SR = AL.getSourceRange();
3919 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003920 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003921
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003922 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003923 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003924 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003925
Reid Kleckner377c1592014-06-10 23:29:48 +00003926 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003927 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003928
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003929 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003930 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003931
Douglas Gregore46db902011-06-17 22:11:49 +00003932 // Objective-C ARC:
3933 // If an explicitly-specified template argument type is a lifetime type
3934 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003935 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003936 ArgType->isObjCLifetimeType() &&
3937 !ArgType.getObjCLifetime()) {
3938 Qualifiers Qs;
3939 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3940 ArgType = Context.getQualifiedType(ArgType, Qs);
3941 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003942
Douglas Gregore46db902011-06-17 22:11:49 +00003943 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003944 return false;
3945}
3946
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003947/// \brief Substitute template arguments into the default template argument for
3948/// the given template type parameter.
3949///
3950/// \param SemaRef the semantic analysis object for which we are performing
3951/// the substitution.
3952///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003953/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003954/// for.
3955///
3956/// \param TemplateLoc the location of the template name that started the
3957/// template-id we are checking.
3958///
3959/// \param RAngleLoc the location of the right angle bracket ('>') that
3960/// terminates the template-id.
3961///
3962/// \param Param the template template parameter whose default we are
3963/// substituting into.
3964///
3965/// \param Converted the list of template arguments provided for template
3966/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003967/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003968static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003969SubstDefaultTemplateArgument(Sema &SemaRef,
3970 TemplateDecl *Template,
3971 SourceLocation TemplateLoc,
3972 SourceLocation RAngleLoc,
3973 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003974 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003975 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003976
3977 // If the argument type is dependent, instantiate it now based
3978 // on the previously-computed template arguments.
3979 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003980 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003981 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003982 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003983 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003984 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003985
David Majnemer8b622692016-07-03 21:17:51 +00003986 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003987
3988 // Only substitute for the innermost template argument list.
3989 MultiLevelTemplateArgumentList TemplateArgLists;
3990 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3991 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3992 TemplateArgLists.addOuterTemplateArguments(None);
3993
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003994 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003995 ArgType =
3996 SemaRef.SubstType(ArgType, TemplateArgLists,
3997 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003998 }
3999
4000 return ArgType;
4001}
4002
4003/// \brief Substitute template arguments into the default template argument for
4004/// the given non-type template parameter.
4005///
4006/// \param SemaRef the semantic analysis object for which we are performing
4007/// the substitution.
4008///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004009/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004010/// for.
4011///
4012/// \param TemplateLoc the location of the template name that started the
4013/// template-id we are checking.
4014///
4015/// \param RAngleLoc the location of the right angle bracket ('>') that
4016/// terminates the template-id.
4017///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004018/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004019/// substituting into.
4020///
4021/// \param Converted the list of template arguments provided for template
4022/// parameters that precede \p Param in the template parameter list.
4023///
4024/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004025static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004026SubstDefaultTemplateArgument(Sema &SemaRef,
4027 TemplateDecl *Template,
4028 SourceLocation TemplateLoc,
4029 SourceLocation RAngleLoc,
4030 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004031 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004032 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004033 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004034 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004035 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004036 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004037
David Majnemer8b622692016-07-03 21:17:51 +00004038 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004039
4040 // Only substitute for the innermost template argument list.
4041 MultiLevelTemplateArgumentList TemplateArgLists;
4042 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4043 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4044 TemplateArgLists.addOuterTemplateArguments(None);
4045
Faisal Vali48401eb2015-11-19 19:20:17 +00004046 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
4047 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004048 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004049}
4050
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004051/// \brief Substitute template arguments into the default template argument for
4052/// the given template template parameter.
4053///
4054/// \param SemaRef the semantic analysis object for which we are performing
4055/// the substitution.
4056///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004058/// for.
4059///
4060/// \param TemplateLoc the location of the template name that started the
4061/// template-id we are checking.
4062///
4063/// \param RAngleLoc the location of the right angle bracket ('>') that
4064/// terminates the template-id.
4065///
4066/// \param Param the template template parameter whose default we are
4067/// substituting into.
4068///
4069/// \param Converted the list of template arguments provided for template
4070/// parameters that precede \p Param in the template parameter list.
4071///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004072/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004073/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004074///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004075/// \returns the substituted template argument, or NULL if an error occurred.
4076static TemplateName
4077SubstDefaultTemplateArgument(Sema &SemaRef,
4078 TemplateDecl *Template,
4079 SourceLocation TemplateLoc,
4080 SourceLocation RAngleLoc,
4081 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004082 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004083 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004084 Sema::InstantiatingTemplate Inst(
4085 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4086 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004087 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004088 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004089
David Majnemer8b622692016-07-03 21:17:51 +00004090 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004091
4092 // Only substitute for the innermost template argument list.
4093 MultiLevelTemplateArgumentList TemplateArgLists;
4094 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4095 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4096 TemplateArgLists.addOuterTemplateArguments(None);
4097
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004098 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004099 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004100 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004101 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004102 QualifierLoc =
4103 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004104 if (!QualifierLoc)
4105 return TemplateName();
4106 }
David Majnemer89189202013-08-28 23:48:32 +00004107
4108 return SemaRef.SubstTemplateName(
4109 QualifierLoc,
4110 Param->getDefaultArgument().getArgument().getAsTemplate(),
4111 Param->getDefaultArgument().getTemplateNameLoc(),
4112 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004113}
4114
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004115/// \brief If the given template parameter has a default template
4116/// argument, substitute into that default template argument and
4117/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004118TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004119Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4120 SourceLocation TemplateLoc,
4121 SourceLocation RAngleLoc,
4122 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004123 SmallVectorImpl<TemplateArgument>
4124 &Converted,
4125 bool &HasDefaultArg) {
4126 HasDefaultArg = false;
4127
4128 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004129 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004130 return TemplateArgumentLoc();
4131
Richard Smithc87b9382013-07-04 01:01:24 +00004132 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004133 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004134 TemplateLoc,
4135 RAngleLoc,
4136 TypeParm,
4137 Converted);
4138 if (DI)
4139 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4140
4141 return TemplateArgumentLoc();
4142 }
4143
4144 if (NonTypeTemplateParmDecl *NonTypeParm
4145 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004146 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004147 return TemplateArgumentLoc();
4148
Richard Smithc87b9382013-07-04 01:01:24 +00004149 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004150 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004151 TemplateLoc,
4152 RAngleLoc,
4153 NonTypeParm,
4154 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004155 if (Arg.isInvalid())
4156 return TemplateArgumentLoc();
4157
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004158 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004159 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4160 }
4161
4162 TemplateTemplateParmDecl *TempTempParm
4163 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004164 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004165 return TemplateArgumentLoc();
4166
Richard Smithc87b9382013-07-04 01:01:24 +00004167 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004168 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004169 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004170 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004171 RAngleLoc,
4172 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004173 Converted,
4174 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004175 if (TName.isNull())
4176 return TemplateArgumentLoc();
4177
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004178 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004179 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004180 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4181}
4182
Richard Smith11255ec2017-01-18 19:19:22 +00004183/// Convert a template-argument that we parsed as a type into a template, if
4184/// possible. C++ permits injected-class-names to perform dual service as
4185/// template template arguments and as template type arguments.
4186static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4187 // Extract and step over any surrounding nested-name-specifier.
4188 NestedNameSpecifierLoc QualLoc;
4189 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4190 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4191 return TemplateArgumentLoc();
4192
4193 QualLoc = ETLoc.getQualifierLoc();
4194 TLoc = ETLoc.getNamedTypeLoc();
4195 }
4196
4197 // If this type was written as an injected-class-name, it can be used as a
4198 // template template argument.
4199 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4200 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4201 QualLoc, InjLoc.getNameLoc());
4202
4203 // If this type was written as an injected-class-name, it may have been
4204 // converted to a RecordType during instantiation. If the RecordType is
4205 // *not* wrapped in a TemplateSpecializationType and denotes a class
4206 // template specialization, it must have come from an injected-class-name.
4207 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4208 if (auto *CTSD =
4209 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4210 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4211 QualLoc, RecLoc.getNameLoc());
4212
4213 return TemplateArgumentLoc();
4214}
4215
Douglas Gregorda0fb532009-11-11 19:31:23 +00004216/// \brief Check that the given template argument corresponds to the given
4217/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004218///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004219/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004220/// checked.
4221///
Richard Trieu15b66532015-01-24 02:48:32 +00004222/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004223///
4224/// \param Template The template in which the template argument resides.
4225///
4226/// \param TemplateLoc The location of the template name for the template
4227/// whose argument list we're matching.
4228///
4229/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4230/// the template argument list.
4231///
4232/// \param ArgumentPackIndex The index into the argument pack where this
4233/// argument will be placed. Only valid if the parameter is a parameter pack.
4234///
4235/// \param Converted The checked, converted argument will be added to the
4236/// end of this small vector.
4237///
4238/// \param CTAK Describes how we arrived at this particular template argument:
4239/// explicitly written, deduced, etc.
4240///
4241/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004242bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004243 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004244 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004245 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004246 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004247 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004248 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004249 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004250 // Check template type parameters.
4251 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004252 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004253
Douglas Gregoreebed722009-11-11 19:41:09 +00004254 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004255 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004256 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004257 // with the template arguments we've seen thus far. But if the
4258 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004259 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004260 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4261 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262
Peter Collingbourne01687632010-12-10 17:08:53 +00004263 if (NTTPType->isDependentType() &&
4264 !isa<TemplateTemplateParmDecl>(Template) &&
4265 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004266 // Do substitution on the type of the non-type template parameter.
4267 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004268 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004269 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004270 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004271 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004272
4273 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004274 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004275 NTTPType = SubstType(NTTPType,
4276 MultiLevelTemplateArgumentList(TemplateArgs),
4277 NTTP->getLocation(),
4278 NTTP->getDeclName());
4279 // If that worked, check the non-type template parameter type
4280 // for validity.
4281 if (!NTTPType.isNull())
4282 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4283 NTTP->getLocation());
4284 if (NTTPType.isNull())
4285 return true;
4286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287
Douglas Gregorda0fb532009-11-11 19:31:23 +00004288 switch (Arg.getArgument().getKind()) {
4289 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004290 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004291
Douglas Gregorda0fb532009-11-11 19:31:23 +00004292 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004293 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00004294 ExprResult Res =
4295 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4296 Result, CTAK);
4297 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004298 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
Richard Trieu15b66532015-01-24 02:48:32 +00004300 // If the resulting expression is new, then use it in place of the
4301 // old expression in the template argument.
4302 if (Res.get() != Arg.getArgument().getAsExpr()) {
4303 TemplateArgument TA(Res.get());
4304 Arg = TemplateArgumentLoc(TA, Res.get());
4305 }
4306
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004307 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004308 break;
4309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310
Douglas Gregorda0fb532009-11-11 19:31:23 +00004311 case TemplateArgument::Declaration:
4312 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004313 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004314 // We've already checked this template argument, so just copy
4315 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004316 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004317 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318
Douglas Gregorda0fb532009-11-11 19:31:23 +00004319 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004320 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004321 // We were given a template template argument. It may not be ill-formed;
4322 // see below.
4323 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004324 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4325 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004326 // We have a template argument such as \c T::template X, which we
4327 // parsed as a template template argument. However, since we now
4328 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004329 // template name into an expression.
4330
4331 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4332 Arg.getTemplateNameLoc());
4333
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004334 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004335 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004336 // FIXME: the template-template arg was a DependentTemplateName,
4337 // so it was provided with a template keyword. However, its source
4338 // location is not stored in the template argument structure.
4339 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004340 ExprResult E = DependentScopeDeclRefExpr::Create(
4341 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4342 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004343
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004344 // If we parsed the template argument as a pack expansion, create a
4345 // pack expansion expression.
4346 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004347 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004348 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004349 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004350 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351
Douglas Gregorda0fb532009-11-11 19:31:23 +00004352 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004353 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004354 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004355 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004356
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004357 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004358 break;
4359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004360
Douglas Gregorda0fb532009-11-11 19:31:23 +00004361 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004362 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004363 // therefore cannot be a non-type template argument.
4364 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4365 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004366
Douglas Gregorda0fb532009-11-11 19:31:23 +00004367 Diag(Param->getLocation(), diag::note_template_param_here);
4368 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004369
Douglas Gregorda0fb532009-11-11 19:31:23 +00004370 case TemplateArgument::Type: {
4371 // We have a non-type template parameter but the template
4372 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004373
Douglas Gregorda0fb532009-11-11 19:31:23 +00004374 // C++ [temp.arg]p2:
4375 // In a template-argument, an ambiguity between a type-id and
4376 // an expression is resolved to a type-id, regardless of the
4377 // form of the corresponding template-parameter.
4378 //
4379 // We warn specifically about this case, since it can be rather
4380 // confusing for users.
4381 QualType T = Arg.getArgument().getAsType();
4382 SourceRange SR = Arg.getSourceRange();
4383 if (T->isFunctionType())
4384 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4385 else
4386 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4387 Diag(Param->getLocation(), diag::note_template_param_here);
4388 return true;
4389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004390
Douglas Gregorda0fb532009-11-11 19:31:23 +00004391 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004392 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004393 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394
Douglas Gregorda0fb532009-11-11 19:31:23 +00004395 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004396 }
4397
4398
Douglas Gregorda0fb532009-11-11 19:31:23 +00004399 // Check template template parameters.
4400 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004401
Douglas Gregorda0fb532009-11-11 19:31:23 +00004402 // Substitute into the template parameter list of the template
4403 // template parameter, since previously-supplied template arguments
4404 // may appear within the template template parameter.
4405 {
4406 // Set up a template instantiation context.
4407 LocalInstantiationScope Scope(*this);
4408 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004409 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004410 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004411 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004412 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004413
David Majnemer8b622692016-07-03 21:17:51 +00004414 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004415 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004416 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004417 MultiLevelTemplateArgumentList(TemplateArgs)));
4418 if (!TempParm)
4419 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004420 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004421
Richard Smith11255ec2017-01-18 19:19:22 +00004422 // C++1z [temp.local]p1: (DR1004)
4423 // When [the injected-class-name] is used [...] as a template-argument for
4424 // a template template-parameter [...] it refers to the class template
4425 // itself.
4426 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4427 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4428 Arg.getTypeSourceInfo()->getTypeLoc());
4429 if (!ConvertedArg.getArgument().isNull())
4430 Arg = ConvertedArg;
4431 }
4432
Douglas Gregorda0fb532009-11-11 19:31:23 +00004433 switch (Arg.getArgument().getKind()) {
4434 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004435 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004436
Douglas Gregorda0fb532009-11-11 19:31:23 +00004437 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004438 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00004439 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004440 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004441
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004442 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004443 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444
Douglas Gregorda0fb532009-11-11 19:31:23 +00004445 case TemplateArgument::Expression:
4446 case TemplateArgument::Type:
4447 // We have a template template parameter but the template
4448 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004449 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004450 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004451 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004452
Douglas Gregorda0fb532009-11-11 19:31:23 +00004453 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004454 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004455 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004456 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004457 case TemplateArgument::NullPtr:
4458 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004459
Douglas Gregorda0fb532009-11-11 19:31:23 +00004460 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004461 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004463
Douglas Gregorda0fb532009-11-11 19:31:23 +00004464 return false;
4465}
4466
Simon Pilgrim6905d222016-12-30 22:55:33 +00004467/// \brief Diagnose an arity mismatch in the
Douglas Gregor8e072612012-02-03 07:34:46 +00004468static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4469 SourceLocation TemplateLoc,
4470 TemplateArgumentListInfo &TemplateArgs) {
4471 TemplateParameterList *Params = Template->getTemplateParameters();
4472 unsigned NumParams = Params->size();
4473 unsigned NumArgs = TemplateArgs.size();
4474
4475 SourceRange Range;
4476 if (NumArgs > NumParams)
Simon Pilgrim6905d222016-12-30 22:55:33 +00004477 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
Douglas Gregor8e072612012-02-03 07:34:46 +00004478 TemplateArgs.getRAngleLoc());
4479 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4480 << (NumArgs > NumParams)
Richard Smith0c062b42017-01-14 02:19:59 +00004481 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
Douglas Gregor8e072612012-02-03 07:34:46 +00004482 << Template << Range;
4483 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4484 << Params->getSourceRange();
4485 return true;
4486}
4487
Richard Smith1fde8ec2012-09-07 02:06:42 +00004488/// \brief Check whether the template parameter is a pack expansion, and if so,
4489/// determine the number of parameters produced by that expansion. For instance:
4490///
4491/// \code
4492/// template<typename ...Ts> struct A {
4493/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4494/// };
4495/// \endcode
4496///
4497/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4498/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004499static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004500 if (NonTypeTemplateParmDecl *NTTP
4501 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4502 if (NTTP->isExpandedParameterPack())
4503 return NTTP->getNumExpansionTypes();
4504 }
4505
4506 if (TemplateTemplateParmDecl *TTP
4507 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4508 if (TTP->isExpandedParameterPack())
4509 return TTP->getNumExpansionTemplateParameters();
4510 }
4511
David Blaikie7a30dc52013-02-21 01:47:18 +00004512 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00004513}
4514
Richard Smith35c1df52015-06-17 20:16:32 +00004515/// Diagnose a missing template argument.
4516template<typename TemplateParmDecl>
4517static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4518 TemplateDecl *TD,
4519 const TemplateParmDecl *D,
4520 TemplateArgumentListInfo &Args) {
4521 // Dig out the most recent declaration of the template parameter; there may be
4522 // declarations of the template that are more recent than TD.
4523 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4524 ->getTemplateParameters()
4525 ->getParam(D->getIndex()));
4526
4527 // If there's a default argument that's not visible, diagnose that we're
4528 // missing a module import.
4529 llvm::SmallVector<Module*, 8> Modules;
4530 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4531 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4532 D->getDefaultArgumentLoc(), Modules,
4533 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00004534 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00004535 return true;
4536 }
4537
4538 // FIXME: If there's a more recent default argument that *is* visible,
4539 // diagnose that it was declared too late.
4540
4541 return diagnoseArityMismatch(S, TD, Loc, Args);
4542}
4543
Douglas Gregord32e0282009-02-09 23:23:08 +00004544/// \brief Check that the given template argument list is well-formed
4545/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00004546bool Sema::CheckTemplateArgumentList(
4547 TemplateDecl *Template, SourceLocation TemplateLoc,
4548 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4549 SmallVectorImpl<TemplateArgument> &Converted,
4550 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00004551 // Make a copy of the template arguments for processing. Only make the
4552 // changes at the end when successful in matching the arguments to the
4553 // template.
4554 TemplateArgumentListInfo NewArgs = TemplateArgs;
4555
Douglas Gregord32e0282009-02-09 23:23:08 +00004556 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00004557
Richard Trieu15b66532015-01-24 02:48:32 +00004558 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00004559
Mike Stump11289f42009-09-09 15:08:12 +00004560 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00004561 // [...] The type and form of each template-argument specified in
4562 // a template-id shall match the type and form specified for the
4563 // corresponding parameter declared by the template in its
4564 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00004565 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004566 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00004567 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00004568 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00004569 for (TemplateParameterList::iterator Param = Params->begin(),
4570 ParamEnd = Params->end();
4571 Param != ParamEnd; /* increment in loop */) {
4572 // If we have an expanded parameter pack, make sure we don't have too
4573 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00004574 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004575 if (*Expansions == ArgumentPack.size()) {
4576 // We're done with this parameter pack. Pack up its arguments and add
4577 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00004578 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00004579 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004580 ArgumentPack.clear();
4581
Richard Smith1fde8ec2012-09-07 02:06:42 +00004582 // This argument is assigned to the next parameter.
4583 ++Param;
4584 continue;
4585 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4586 // Not enough arguments for this parameter pack.
4587 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4588 << false
Richard Smith0c062b42017-01-14 02:19:59 +00004589 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00004590 << Template;
4591 Diag(Template->getLocation(), diag::note_template_decl_here)
4592 << Params->getSourceRange();
4593 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004594 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004596
Richard Smith1fde8ec2012-09-07 02:06:42 +00004597 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00004598 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00004599 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004600 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004601 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00004602 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004603
Richard Smith96d71c32014-11-12 23:38:38 +00004604 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00004605 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00004606 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4607 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00004608 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00004609 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00004610 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00004611 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00004612 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00004613 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00004614 Diag((*Param)->getLocation(), diag::note_template_param_here);
4615 return true;
4616 }
4617
Richard Smith1fde8ec2012-09-07 02:06:42 +00004618 // We're now done with this argument.
4619 ++ArgIdx;
4620
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004621 if ((*Param)->isTemplateParameterPack()) {
4622 // The template parameter was a template parameter pack, so take the
4623 // deduced argument and place it on the argument pack. Note that we
4624 // stay on the same template parameter so that we can deduce more
4625 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004626 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004627 } else {
4628 // Move to the next template parameter.
4629 ++Param;
4630 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004631
Richard Smith96d71c32014-11-12 23:38:38 +00004632 // If we just saw a pack expansion into a non-pack, then directly convert
4633 // the remaining arguments, because we don't know what parameters they'll
4634 // match up with.
4635 if (PackExpansionIntoNonPack) {
4636 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004637 // If we were part way through filling in an expanded parameter pack,
4638 // fall back to just producing individual arguments.
4639 Converted.insert(Converted.end(),
4640 ArgumentPack.begin(), ArgumentPack.end());
4641 ArgumentPack.clear();
4642 }
4643
4644 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00004645 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00004646 ++ArgIdx;
4647 }
4648
Richard Smith1fde8ec2012-09-07 02:06:42 +00004649 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00004650 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004651
Douglas Gregor84d49a22009-11-11 21:54:23 +00004652 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004654
Douglas Gregor2f157c92011-06-03 02:59:40 +00004655 // If we're checking a partial template argument list, we're done.
4656 if (PartialTemplateArgs) {
4657 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00004658 Converted.push_back(
4659 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4660
Richard Smith1fde8ec2012-09-07 02:06:42 +00004661 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00004662 }
4663
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004664 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004665 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00004666 if ((*Param)->isTemplateParameterPack()) {
4667 assert(!getExpandedPackSize(*Param) &&
4668 "Should have dealt with this already");
4669
4670 // A non-expanded parameter pack before the end of the parameter list
4671 // only occurs for an ill-formed template parameter list, unless we've
4672 // got a partial argument list for a function template, so just bail out.
4673 if (Param + 1 != ParamEnd)
4674 return true;
4675
Benjamin Kramercce63472015-08-05 09:40:22 +00004676 Converted.push_back(
4677 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004678 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00004679
4680 ++Param;
4681 continue;
4682 }
4683
Douglas Gregor8e072612012-02-03 07:34:46 +00004684 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00004685 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004686
Douglas Gregor84d49a22009-11-11 21:54:23 +00004687 // Retrieve the default template argument from the template
4688 // parameter. For each kind of template parameter, we substitute the
4689 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004690 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004691 // the default argument.
4692 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004693 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004694 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4695 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004696
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004697 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004698 Template,
4699 TemplateLoc,
4700 RAngleLoc,
4701 TTP,
4702 Converted);
4703 if (!ArgType)
4704 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004705
Douglas Gregor84d49a22009-11-11 21:54:23 +00004706 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4707 ArgType);
4708 } else if (NonTypeTemplateParmDecl *NTTP
4709 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004710 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004711 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4712 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004713
John McCalldadc5752010-08-24 06:29:42 +00004714 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004715 TemplateLoc,
4716 RAngleLoc,
4717 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004718 Converted);
4719 if (E.isInvalid())
4720 return true;
4721
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004722 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004723 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4724 } else {
4725 TemplateTemplateParmDecl *TempParm
4726 = cast<TemplateTemplateParmDecl>(*Param);
4727
Richard Smith95d83952015-06-10 20:36:34 +00004728 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004729 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4730 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004731
Douglas Gregordf846d12011-03-02 18:46:51 +00004732 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004733 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004734 TemplateLoc,
4735 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004736 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004737 Converted,
4738 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004739 if (Name.isNull())
4740 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004741
Douglas Gregor9d802122011-03-02 17:09:35 +00004742 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4743 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004745
Douglas Gregor84d49a22009-11-11 21:54:23 +00004746 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00004747 // the default template argument. We're not actually instantiating a
4748 // template here, we just create this object to put a note into the
4749 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004750 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4751 SourceRange(TemplateLoc, RAngleLoc));
4752 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004753 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004754
Douglas Gregor84d49a22009-11-11 21:54:23 +00004755 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004756 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004757 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004758 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004759
Richard Trieu15b66532015-01-24 02:48:32 +00004760 // Core issue 150 (assumed resolution): if this is a template template
4761 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004762 // template definition.
4763 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004764 NewArgs.addArgument(Arg);
4765
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004766 // Move to the next template parameter and argument.
4767 ++Param;
4768 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004770
Richard Smith07f79912014-06-06 16:00:50 +00004771 // If we're performing a partial argument substitution, allow any trailing
4772 // pack expansions; they might be empty. This can happen even if
4773 // PartialTemplateArgs is false (the list of arguments is complete but
4774 // still dependent).
4775 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4776 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004777 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4778 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004779 }
4780
Douglas Gregor8e072612012-02-03 07:34:46 +00004781 // If we have any leftover arguments, then there were too many arguments.
4782 // Complain and fail.
4783 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004784 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4785
4786 // No problems found with the new argument list, propagate changes back
4787 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00004788 if (UpdateArgsWithConversions)
4789 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004790
Richard Smith1fde8ec2012-09-07 02:06:42 +00004791 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004792}
4793
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004794namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004795 class UnnamedLocalNoLinkageFinder
4796 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004797 {
4798 Sema &S;
4799 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004800
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004801 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004802
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004803 public:
4804 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4805
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004806 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00004807 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004808 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004809
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004810#define TYPE(Class, Parent) \
4811 bool Visit##Class##Type(const Class##Type *);
4812#define ABSTRACT_TYPE(Class, Parent) \
4813 bool Visit##Class##Type(const Class##Type *) { return false; }
4814#define NON_CANONICAL_TYPE(Class, Parent) \
4815 bool Visit##Class##Type(const Class##Type *) { return false; }
4816#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004817
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004818 bool VisitTagDecl(const TagDecl *Tag);
4819 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4820 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004821} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004822
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004823bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004824 return false;
4825}
4826
4827bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4828 return Visit(T->getElementType());
4829}
4830
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004831bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004832 return Visit(T->getPointeeType());
4833}
4834
4835bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004837 return Visit(T->getPointeeType());
4838}
4839
4840bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004842 return Visit(T->getPointeeType());
4843}
4844
4845bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004846 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004847 return Visit(T->getPointeeType());
4848}
4849
4850bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004851 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004852 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4853}
4854
4855bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004856 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004857 return Visit(T->getElementType());
4858}
4859
4860bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004861 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004862 return Visit(T->getElementType());
4863}
4864
4865bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004866 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004867 return Visit(T->getElementType());
4868}
4869
4870bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004871 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004872 return Visit(T->getElementType());
4873}
4874
4875bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004877 return Visit(T->getElementType());
4878}
4879
4880bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4881 return Visit(T->getElementType());
4882}
4883
4884bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4885 return Visit(T->getElementType());
4886}
4887
4888bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4889 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004890 for (const auto &A : T->param_types()) {
4891 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004892 return true;
4893 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004894
Alp Toker314cc812014-01-25 16:55:45 +00004895 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004896}
4897
4898bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4899 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004900 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004901}
4902
4903bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4904 const UnresolvedUsingType*) {
4905 return false;
4906}
4907
4908bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4909 return false;
4910}
4911
4912bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4913 return Visit(T->getUnderlyingType());
4914}
4915
4916bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4917 return false;
4918}
4919
Alexis Hunte852b102011-05-24 22:41:36 +00004920bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4921 const UnaryTransformType*) {
4922 return false;
4923}
4924
Richard Smith30482bc2011-02-20 03:19:35 +00004925bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4926 return Visit(T->getDeducedType());
4927}
4928
Richard Smith600b5262017-01-26 20:40:47 +00004929bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
4930 const DeducedTemplateSpecializationType *T) {
4931 return Visit(T->getDeducedType());
4932}
4933
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004934bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4935 return VisitTagDecl(T->getDecl());
4936}
4937
4938bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4939 return VisitTagDecl(T->getDecl());
4940}
4941
4942bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4943 const TemplateTypeParmType*) {
4944 return false;
4945}
4946
Douglas Gregorada4b792011-01-14 02:55:32 +00004947bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4948 const SubstTemplateTypeParmPackType *) {
4949 return false;
4950}
4951
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004952bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4953 const TemplateSpecializationType*) {
4954 return false;
4955}
4956
4957bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4958 const InjectedClassNameType* T) {
4959 return VisitTagDecl(T->getDecl());
4960}
4961
4962bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4963 const DependentNameType* T) {
4964 return VisitNestedNameSpecifier(T->getQualifier());
4965}
4966
4967bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4968 const DependentTemplateSpecializationType* T) {
4969 return VisitNestedNameSpecifier(T->getQualifier());
4970}
4971
Douglas Gregord2fa7662010-12-20 02:24:11 +00004972bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4973 const PackExpansionType* T) {
4974 return Visit(T->getPattern());
4975}
4976
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004977bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4978 return false;
4979}
4980
4981bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4982 const ObjCInterfaceType *) {
4983 return false;
4984}
4985
4986bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4987 const ObjCObjectPointerType *) {
4988 return false;
4989}
4990
Eli Friedman0dfb8892011-10-06 23:00:33 +00004991bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4992 return Visit(T->getValueType());
4993}
4994
Xiuli Pan9c14e282016-01-09 12:53:17 +00004995bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4996 return false;
4997}
4998
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004999bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5000 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005001 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005002 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005003 diag::warn_cxx98_compat_template_arg_local_type :
5004 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005005 << S.Context.getTypeDeclType(Tag) << SR;
5006 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005007 }
5008
John McCall5ea95772013-03-09 00:54:27 +00005009 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005010 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005011 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005012 diag::warn_cxx98_compat_template_arg_unnamed_type :
5013 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005014 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5015 return true;
5016 }
5017
5018 return false;
5019}
5020
5021bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5022 NestedNameSpecifier *NNS) {
5023 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5024 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005025
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005026 switch (NNS->getKind()) {
5027 case NestedNameSpecifier::Identifier:
5028 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005029 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005030 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005031 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005032 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005033
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005034 case NestedNameSpecifier::TypeSpec:
5035 case NestedNameSpecifier::TypeSpecWithTemplate:
5036 return Visit(QualType(NNS->getAsType(), 0));
5037 }
David Blaikie8a40f702012-01-17 06:56:22 +00005038 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005039}
5040
Douglas Gregord32e0282009-02-09 23:23:08 +00005041/// \brief Check a template argument against its corresponding
5042/// template type parameter.
5043///
5044/// This routine implements the semantics of C++ [temp.arg.type]. It
5045/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005046bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005047 TypeSourceInfo *ArgInfo) {
5048 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005049 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005050 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005051
5052 if (Arg->isVariablyModifiedType()) {
5053 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005054 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005055 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005056 }
5057
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005058 // C++03 [temp.arg.type]p2:
5059 // A local type, a type with no linkage, an unnamed type or a type
5060 // compounded from any of these types shall not be used as a
5061 // template-argument for a template type-parameter.
5062 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005063 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005064 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005065 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005066 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5067 (void)Finder.Visit(Context.getCanonicalType(Arg));
5068 }
5069
Douglas Gregord32e0282009-02-09 23:23:08 +00005070 return false;
5071}
5072
Douglas Gregor20fdef32012-04-10 17:08:25 +00005073enum NullPointerValueKind {
5074 NPV_NotNullPointer,
5075 NPV_NullPointer,
5076 NPV_Error
5077};
5078
5079/// \brief Determine whether the given template argument is a null pointer
5080/// value of the appropriate type.
5081static NullPointerValueKind
5082isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5083 QualType ParamType, Expr *Arg) {
5084 if (Arg->isValueDependent() || Arg->isTypeDependent())
5085 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005086
Richard Smithdb0ac552015-12-18 22:40:25 +00005087 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005088 llvm_unreachable(
5089 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005090
David Majnemer5c734ad2014-08-14 00:49:23 +00005091 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005092 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005093
Douglas Gregor20fdef32012-04-10 17:08:25 +00005094 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005095 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5096 if (ArgRV.isInvalid())
5097 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005098 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005099
Douglas Gregor20fdef32012-04-10 17:08:25 +00005100 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005101 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005102 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005103 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005104 EvalResult.HasSideEffects) {
5105 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005106
Douglas Gregor350880c2012-04-10 19:03:30 +00005107 // If our only note is the usual "invalid subexpression" note, just point
5108 // the caret at its location rather than producing an essentially
5109 // redundant note.
5110 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5111 diag::note_invalid_subexpr_in_const_expr) {
5112 DiagLoc = Notes[0].first;
5113 Notes.clear();
5114 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005115
Douglas Gregor350880c2012-04-10 19:03:30 +00005116 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5117 << Arg->getType() << Arg->getSourceRange();
5118 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5119 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005120
Douglas Gregor350880c2012-04-10 19:03:30 +00005121 S.Diag(Param->getLocation(), diag::note_template_param_here);
5122 return NPV_Error;
5123 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005124
Douglas Gregor20fdef32012-04-10 17:08:25 +00005125 // C++11 [temp.arg.nontype]p1:
5126 // - an address constant expression of type std::nullptr_t
5127 if (Arg->getType()->isNullPtrType())
5128 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005129
Douglas Gregor20fdef32012-04-10 17:08:25 +00005130 // - a constant expression that evaluates to a null pointer value (4.10); or
5131 // - a constant expression that evaluates to a null member pointer value
5132 // (4.11); or
5133 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5134 (EvalResult.Val.isMemberPointer() &&
5135 !EvalResult.Val.getMemberPointerDecl())) {
5136 // If our expression has an appropriate type, we've succeeded.
5137 bool ObjCLifetimeConversion;
5138 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5139 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5140 ObjCLifetimeConversion))
5141 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005142
Douglas Gregor20fdef32012-04-10 17:08:25 +00005143 // The types didn't match, but we know we got a null pointer; complain,
5144 // then recover as if the types were correct.
5145 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5146 << Arg->getType() << ParamType << Arg->getSourceRange();
5147 S.Diag(Param->getLocation(), diag::note_template_param_here);
5148 return NPV_NullPointer;
5149 }
5150
5151 // If we don't have a null pointer value, but we do have a NULL pointer
5152 // constant, suggest a cast to the appropriate type.
5153 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5154 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5155 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005156 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5157 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5158 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005159 S.Diag(Param->getLocation(), diag::note_template_param_here);
5160 return NPV_NullPointer;
5161 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005162
Douglas Gregor20fdef32012-04-10 17:08:25 +00005163 // FIXME: If we ever want to support general, address-constant expressions
5164 // as non-type template arguments, we should return the ExprResult here to
5165 // be interpreted by the caller.
5166 return NPV_NotNullPointer;
5167}
5168
David Majnemer61c39a12013-08-23 05:39:39 +00005169/// \brief Checks whether the given template argument is compatible with its
5170/// template parameter.
5171static bool CheckTemplateArgumentIsCompatibleWithParameter(
5172 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5173 Expr *Arg, QualType ArgType) {
5174 bool ObjCLifetimeConversion;
5175 if (ParamType->isPointerType() &&
5176 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5177 S.IsQualificationConversion(ArgType, ParamType, false,
5178 ObjCLifetimeConversion)) {
5179 // For pointer-to-object types, qualification conversions are
5180 // permitted.
5181 } else {
5182 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5183 if (!ParamRef->getPointeeType()->isFunctionType()) {
5184 // C++ [temp.arg.nontype]p5b3:
5185 // For a non-type template-parameter of type reference to
5186 // object, no conversions apply. The type referred to by the
5187 // reference may be more cv-qualified than the (otherwise
5188 // identical) type of the template- argument. The
5189 // template-parameter is bound directly to the
5190 // template-argument, which shall be an lvalue.
5191
5192 // FIXME: Other qualifiers?
5193 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5194 unsigned ArgQuals = ArgType.getCVRQualifiers();
5195
5196 if ((ParamQuals | ArgQuals) != ParamQuals) {
5197 S.Diag(Arg->getLocStart(),
5198 diag::err_template_arg_ref_bind_ignores_quals)
5199 << ParamType << Arg->getType() << Arg->getSourceRange();
5200 S.Diag(Param->getLocation(), diag::note_template_param_here);
5201 return true;
5202 }
5203 }
5204 }
5205
5206 // At this point, the template argument refers to an object or
5207 // function with external linkage. We now need to check whether the
5208 // argument and parameter types are compatible.
5209 if (!S.Context.hasSameUnqualifiedType(ArgType,
5210 ParamType.getNonReferenceType())) {
5211 // We can't perform this conversion or binding.
5212 if (ParamType->isReferenceType())
5213 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5214 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5215 else
5216 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5217 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5218 S.Diag(Param->getLocation(), diag::note_template_param_here);
5219 return true;
5220 }
5221 }
5222
5223 return false;
5224}
5225
Douglas Gregorccb07762009-02-11 19:52:55 +00005226/// \brief Checks whether the given template argument is the address
5227/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005228static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005229CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5230 NonTypeTemplateParmDecl *Param,
5231 QualType ParamType,
5232 Expr *ArgIn,
5233 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005234 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005235 Expr *Arg = ArgIn;
5236 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005237
Douglas Gregorb242683d2010-04-01 18:32:35 +00005238 bool AddressTaken = false;
5239 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005240 if (S.getLangOpts().MicrosoftExt) {
5241 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5242 // dereference and address-of operators.
5243 Arg = Arg->IgnoreParenCasts();
5244
5245 bool ExtWarnMSTemplateArg = false;
5246 UnaryOperatorKind FirstOpKind;
5247 SourceLocation FirstOpLoc;
5248 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5249 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5250 if (UnOpKind == UO_Deref)
5251 ExtWarnMSTemplateArg = true;
5252 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5253 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5254 if (!AddrOpLoc.isValid()) {
5255 FirstOpKind = UnOpKind;
5256 FirstOpLoc = UnOp->getOperatorLoc();
5257 }
5258 } else
5259 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005260 }
David Majnemer61c39a12013-08-23 05:39:39 +00005261 if (FirstOpLoc.isValid()) {
5262 if (ExtWarnMSTemplateArg)
5263 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5264 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005265
David Majnemer61c39a12013-08-23 05:39:39 +00005266 if (FirstOpKind == UO_AddrOf)
5267 AddressTaken = true;
5268 else if (Arg->getType()->isPointerType()) {
5269 // We cannot let pointers get dereferenced here, that is obviously not a
5270 // constant expression.
5271 assert(FirstOpKind == UO_Deref);
5272 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5273 << Arg->getSourceRange();
5274 }
5275 }
5276 } else {
5277 // See through any implicit casts we added to fix the type.
5278 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005279
David Majnemer61c39a12013-08-23 05:39:39 +00005280 // C++ [temp.arg.nontype]p1:
5281 //
5282 // A template-argument for a non-type, non-template
5283 // template-parameter shall be one of: [...]
5284 //
5285 // -- the address of an object or function with external
5286 // linkage, including function templates and function
5287 // template-ids but excluding non-static class members,
5288 // expressed as & id-expression where the & is optional if
5289 // the name refers to a function or array, or if the
5290 // corresponding template-parameter is a reference; or
5291
5292 // In C++98/03 mode, give an extension warning on any extra parentheses.
5293 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5294 bool ExtraParens = false;
5295 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5296 if (!Invalid && !ExtraParens) {
5297 S.Diag(Arg->getLocStart(),
5298 S.getLangOpts().CPlusPlus11
5299 ? diag::warn_cxx98_compat_template_arg_extra_parens
5300 : diag::ext_template_arg_extra_parens)
5301 << Arg->getSourceRange();
5302 ExtraParens = true;
5303 }
5304
5305 Arg = Parens->getSubExpr();
5306 }
5307
5308 while (SubstNonTypeTemplateParmExpr *subst =
5309 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5310 Arg = subst->getReplacement()->IgnoreImpCasts();
5311
5312 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5313 if (UnOp->getOpcode() == UO_AddrOf) {
5314 Arg = UnOp->getSubExpr();
5315 AddressTaken = true;
5316 AddrOpLoc = UnOp->getOperatorLoc();
5317 }
5318 }
5319
5320 while (SubstNonTypeTemplateParmExpr *subst =
5321 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5322 Arg = subst->getReplacement()->IgnoreImpCasts();
5323 }
John McCall7c454bb2011-07-15 05:09:51 +00005324
David Majnemer07910d62014-06-26 07:48:46 +00005325 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5326 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5327
5328 // If our parameter has pointer type, check for a null template value.
5329 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5330 NullPointerValueKind NPV;
5331 // dllimport'd entities aren't constant but are available inside of template
5332 // arguments.
5333 if (Entity && Entity->hasAttr<DLLImportAttr>())
5334 NPV = NPV_NotNullPointer;
5335 else
5336 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
5337 switch (NPV) {
5338 case NPV_NullPointer:
5339 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005340 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5341 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005342 return false;
5343
5344 case NPV_Error:
5345 return true;
5346
5347 case NPV_NotNullPointer:
5348 break;
5349 }
5350 }
5351
Chandler Carruth724a8a12010-01-31 10:01:20 +00005352 // Stop checking the precise nature of the argument if it is value dependent,
5353 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005354 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005355 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005356 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005357 }
David Majnemer61c39a12013-08-23 05:39:39 +00005358
5359 if (isa<CXXUuidofExpr>(Arg)) {
5360 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5361 ArgIn, Arg, ArgType))
5362 return true;
5363
5364 Converted = TemplateArgument(ArgIn);
5365 return false;
5366 }
5367
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005368 if (!DRE) {
5369 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5370 << Arg->getSourceRange();
5371 S.Diag(Param->getLocation(), diag::note_template_param_here);
5372 return true;
5373 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00005374
Douglas Gregorccb07762009-02-11 19:52:55 +00005375 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00005376 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005377 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00005378 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005379 S.Diag(Param->getLocation(), diag::note_template_param_here);
5380 return true;
5381 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005382
5383 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00005384 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005385 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005386 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00005387 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005388 S.Diag(Param->getLocation(), diag::note_template_param_here);
5389 return true;
5390 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005391 }
Mike Stump11289f42009-09-09 15:08:12 +00005392
Richard Smith9380e0e2012-04-04 21:11:30 +00005393 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5394 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00005395
Richard Smith9380e0e2012-04-04 21:11:30 +00005396 // A non-type template argument must refer to an object or function.
5397 if (!Func && !Var) {
5398 // We found something, but we don't know specifically what it is.
5399 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5400 << Arg->getSourceRange();
5401 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5402 return true;
5403 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005404
Richard Smith9380e0e2012-04-04 21:11:30 +00005405 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00005406 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005407 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00005408 diag::warn_cxx98_compat_template_arg_object_internal :
5409 diag::ext_template_arg_object_internal)
5410 << !Func << Entity << Arg->getSourceRange();
5411 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5412 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00005413 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005414 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5415 << !Func << Entity << Arg->getSourceRange();
5416 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5417 << !Func;
5418 return true;
5419 }
5420
5421 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005422 // If the template parameter has pointer type, the function decays.
5423 if (ParamType->isPointerType() && !AddressTaken)
5424 ArgType = S.Context.getPointerType(Func->getType());
5425 else if (AddressTaken && ParamType->isReferenceType()) {
5426 // If we originally had an address-of operator, but the
5427 // parameter has reference type, complain and (if things look
5428 // like they will work) drop the address-of operator.
5429 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5430 ParamType.getNonReferenceType())) {
5431 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5432 << ParamType;
5433 S.Diag(Param->getLocation(), diag::note_template_param_here);
5434 return true;
5435 }
5436
5437 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5438 << ParamType
5439 << FixItHint::CreateRemoval(AddrOpLoc);
5440 S.Diag(Param->getLocation(), diag::note_template_param_here);
5441
5442 ArgType = Func->getType();
5443 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005444 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005445 // A value of reference type is not an object.
5446 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005447 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00005448 diag::err_template_arg_reference_var)
5449 << Var->getType() << Arg->getSourceRange();
5450 S.Diag(Param->getLocation(), diag::note_template_param_here);
5451 return true;
5452 }
5453
Richard Smith9380e0e2012-04-04 21:11:30 +00005454 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005455 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005456 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5457 << Arg->getSourceRange();
5458 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5459 return true;
5460 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005461
5462 // If the template parameter has pointer type, we must have taken
5463 // the address of this object.
5464 if (ParamType->isReferenceType()) {
5465 if (AddressTaken) {
5466 // If we originally had an address-of operator, but the
5467 // parameter has reference type, complain and (if things look
5468 // like they will work) drop the address-of operator.
5469 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5470 ParamType.getNonReferenceType())) {
5471 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5472 << ParamType;
5473 S.Diag(Param->getLocation(), diag::note_template_param_here);
5474 return true;
5475 }
5476
5477 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5478 << ParamType
5479 << FixItHint::CreateRemoval(AddrOpLoc);
5480 S.Diag(Param->getLocation(), diag::note_template_param_here);
5481
5482 ArgType = Var->getType();
5483 }
5484 } else if (!AddressTaken && ParamType->isPointerType()) {
5485 if (Var->getType()->isArrayType()) {
5486 // Array-to-pointer decay.
5487 ArgType = S.Context.getArrayDecayedType(Var->getType());
5488 } else {
5489 // If the template parameter has pointer type but the address of
5490 // this object was not taken, complain and (possibly) recover by
5491 // taking the address of the entity.
5492 ArgType = S.Context.getPointerType(Var->getType());
5493 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5494 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5495 << ParamType;
5496 S.Diag(Param->getLocation(), diag::note_template_param_here);
5497 return true;
5498 }
5499
5500 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5501 << ParamType
5502 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5503
5504 S.Diag(Param->getLocation(), diag::note_template_param_here);
5505 }
5506 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005507 }
Mike Stump11289f42009-09-09 15:08:12 +00005508
David Majnemer61c39a12013-08-23 05:39:39 +00005509 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5510 Arg, ArgType))
5511 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005512
5513 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00005514 Converted =
5515 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00005516 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00005517 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005518}
5519
5520/// \brief Checks whether the given template argument is a pointer to
5521/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005522static bool CheckTemplateArgumentPointerToMember(Sema &S,
5523 NonTypeTemplateParmDecl *Param,
5524 QualType ParamType,
5525 Expr *&ResultArg,
5526 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005527 bool Invalid = false;
5528
Douglas Gregor20fdef32012-04-10 17:08:25 +00005529 // Check for a null pointer value.
5530 Expr *Arg = ResultArg;
5531 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
5532 case NPV_Error:
5533 return true;
5534 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005535 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005536 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5537 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00005538 return false;
5539 case NPV_NotNullPointer:
5540 break;
5541 }
5542
5543 bool ObjCLifetimeConversion;
5544 if (S.IsQualificationConversion(Arg->getType(),
5545 ParamType.getNonReferenceType(),
5546 false, ObjCLifetimeConversion)) {
5547 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005548 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00005549 ResultArg = Arg;
5550 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
5551 ParamType.getNonReferenceType())) {
5552 // We can't perform this conversion.
5553 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5554 << Arg->getType() << ParamType << Arg->getSourceRange();
5555 S.Diag(Param->getLocation(), diag::note_template_param_here);
5556 return true;
5557 }
5558
Douglas Gregorccb07762009-02-11 19:52:55 +00005559 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00005560 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00005561 Arg = Cast->getSubExpr();
5562
5563 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005564 //
Douglas Gregorccb07762009-02-11 19:52:55 +00005565 // A template-argument for a non-type, non-template
5566 // template-parameter shall be one of: [...]
5567 //
5568 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00005569 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00005570
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005571 // In C++98/03 mode, give an extension warning on any extra parentheses.
5572 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5573 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005574 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005575 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005576 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005577 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00005578 diag::warn_cxx98_compat_template_arg_extra_parens :
5579 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00005580 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005581 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00005582 }
5583
5584 Arg = Parens->getSubExpr();
5585 }
5586
John McCall7c454bb2011-07-15 05:09:51 +00005587 while (SubstNonTypeTemplateParmExpr *subst =
5588 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5589 Arg = subst->getReplacement()->IgnoreImpCasts();
5590
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005591 // A pointer-to-member constant written &Class::member.
5592 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00005593 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005594 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5595 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005596 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005597 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005598 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005599 // A constant of pointer-to-member type.
5600 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5601 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5602 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00005603 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005604 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005605 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005606 } else {
5607 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005608 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005609 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005610 return Invalid;
5611 }
5612 }
5613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005614
Craig Topperc3ec1492014-05-26 06:22:03 +00005615 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005617
Douglas Gregorccb07762009-02-11 19:52:55 +00005618 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005619 return S.Diag(Arg->getLocStart(),
5620 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00005621 << Arg->getSourceRange();
5622
David Majnemer3ac84e62013-10-22 21:56:38 +00005623 if (isa<FieldDecl>(DRE->getDecl()) ||
5624 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5625 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005626 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00005627 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00005628 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5629 "Only non-static member pointers can make it here");
5630
5631 // Okay: this is the address of a non-static member, and therefore
5632 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00005633 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005634 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005635 } else {
5636 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005637 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005638 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005639 return Invalid;
5640 }
5641
5642 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005643 S.Diag(Arg->getLocStart(),
5644 diag::err_template_arg_not_pointer_to_member_form)
5645 << Arg->getSourceRange();
5646 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00005647 return true;
5648}
5649
Douglas Gregord32e0282009-02-09 23:23:08 +00005650/// \brief Check a template argument against its corresponding
5651/// non-type template parameter.
5652///
Douglas Gregor463421d2009-03-03 04:44:36 +00005653/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00005654/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00005655/// returns the converted template argument. \p ParamType is the
5656/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00005657ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00005658 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00005659 TemplateArgument &Converted,
5660 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005661 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00005662
Richard Smith5f274382016-09-28 23:55:27 +00005663 // If the parameter type somehow involves auto, deduce the type now.
5664 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
Richard Smith87d263e2016-12-25 08:05:23 +00005665 // When checking a deduced template argument, deduce from its type even if
5666 // the type is dependent, in order to check the types of non-type template
5667 // arguments line up properly in partial ordering.
5668 Optional<unsigned> Depth;
5669 if (CTAK != CTAK_Specified)
5670 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00005671 if (DeduceAutoType(
5672 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00005673 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00005674 Diag(Arg->getExprLoc(),
5675 diag::err_non_type_template_parm_type_deduction_failure)
5676 << Param->getDeclName() << Param->getType() << Arg->getType()
5677 << Arg->getSourceRange();
5678 Diag(Param->getLocation(), diag::note_template_param_here);
5679 return ExprError();
5680 }
5681 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5682 // an error. The error message normally references the parameter
5683 // declaration, but here we'll pass the argument location because that's
5684 // where the parameter type is deduced.
5685 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5686 if (ParamType.isNull()) {
5687 Diag(Param->getLocation(), diag::note_template_param_here);
5688 return ExprError();
5689 }
5690 }
5691
Richard Smithd663fdd2014-12-17 20:42:37 +00005692 // We should have already dropped all cv-qualifiers by now.
5693 assert(!ParamType.hasQualifiers() &&
5694 "non-type template parameter type cannot be qualified");
5695
5696 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00005697 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00005698 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00005699 // FIXME: If either type is dependent, we skip the check. This isn't
5700 // correct, since during deduction we're supposed to have replaced each
5701 // template parameter with some unique (non-dependent) placeholder.
5702 // FIXME: If the argument type contains 'auto', we carry on and fail the
5703 // type check in order to force specific types to be more specialized than
5704 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5705 // work.
5706 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5707 !Arg->getType()->getContainedAutoType()) {
5708 Converted = TemplateArgument(Arg);
5709 return Arg;
5710 }
5711 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5712 // we should actually be checking the type of the template argument in P,
5713 // not the type of the template argument deduced from A, against the
5714 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00005715 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00005716 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00005717 << ParamType.getUnqualifiedType();
5718 Diag(Param->getLocation(), diag::note_template_param_here);
5719 return ExprError();
5720 }
5721
Richard Smith87d263e2016-12-25 08:05:23 +00005722 // If either the parameter has a dependent type or the argument is
5723 // type-dependent, there's nothing we can check now.
5724 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5725 // FIXME: Produce a cloned, canonical expression?
5726 Converted = TemplateArgument(Arg);
5727 return Arg;
5728 }
5729
Richard Smithe5945872017-01-06 22:52:53 +00005730 // The initialization of the parameter from the argument is
5731 // a constant-evaluated context.
5732 EnterExpressionEvaluationContext ConstantEvaluated(*this,
5733 Sema::ConstantEvaluated);
5734
Richard Smith410cc892014-11-26 03:26:53 +00005735 if (getLangOpts().CPlusPlus1z) {
Richard Smith410cc892014-11-26 03:26:53 +00005736 // C++1z [temp.arg.nontype]p1:
5737 // A template-argument for a non-type template parameter shall be
5738 // a converted constant expression of the type of the template-parameter.
5739 APValue Value;
5740 ExprResult ArgResult = CheckConvertedConstantExpression(
5741 Arg, ParamType, Value, CCEK_TemplateArg);
5742 if (ArgResult.isInvalid())
5743 return ExprError();
5744
Richard Smith52e624f2016-12-21 21:42:57 +00005745 // For a value-dependent argument, CheckConvertedConstantExpression is
5746 // permitted (and expected) to be unable to determine a value.
5747 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00005748 Converted = TemplateArgument(ArgResult.get());
5749 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00005750 }
5751
Richard Smithd663fdd2014-12-17 20:42:37 +00005752 QualType CanonParamType = Context.getCanonicalType(ParamType);
5753
Richard Smith410cc892014-11-26 03:26:53 +00005754 // Convert the APValue to a TemplateArgument.
5755 switch (Value.getKind()) {
5756 case APValue::Uninitialized:
5757 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005758 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005759 break;
5760 case APValue::Int:
5761 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005762 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005763 break;
5764 case APValue::MemberPointer: {
5765 assert(ParamType->isMemberPointerType());
5766
5767 // FIXME: We need TemplateArgument representation and mangling for these.
5768 if (!Value.getMemberPointerPath().empty()) {
5769 Diag(Arg->getLocStart(),
5770 diag::err_template_arg_member_ptr_base_derived_not_supported)
5771 << Value.getMemberPointerDecl() << ParamType
5772 << Arg->getSourceRange();
5773 return ExprError();
5774 }
5775
5776 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005777 Converted = VD ? TemplateArgument(VD, CanonParamType)
5778 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005779 break;
5780 }
5781 case APValue::LValue: {
5782 // For a non-type template-parameter of pointer or reference type,
5783 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00005784 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5785 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00005786 // -- a temporary object
5787 // -- a string literal
5788 // -- the result of a typeid expression, or
5789 // -- a predefind __func__ variable
5790 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5791 if (isa<CXXUuidofExpr>(E)) {
5792 Converted = TemplateArgument(const_cast<Expr*>(E));
5793 break;
5794 }
5795 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5796 << Arg->getSourceRange();
5797 return ExprError();
5798 }
5799 auto *VD = const_cast<ValueDecl *>(
5800 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5801 // -- a subobject
5802 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5803 VD && VD->getType()->isArrayType() &&
5804 Value.getLValuePath()[0].ArrayIndex == 0 &&
5805 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5806 // Per defect report (no number yet):
5807 // ... other than a pointer to the first element of a complete array
5808 // object.
5809 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5810 Value.isLValueOnePastTheEnd()) {
5811 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5812 << Value.getAsString(Context, ParamType);
5813 return ExprError();
5814 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005815 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005816 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005817 assert((!VD || !ParamType->isNullPtrType()) &&
5818 "non-null value of type nullptr_t?");
5819 Converted = VD ? TemplateArgument(VD, CanonParamType)
5820 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005821 break;
5822 }
5823 case APValue::AddrLabelDiff:
5824 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5825 case APValue::Float:
5826 case APValue::ComplexInt:
5827 case APValue::ComplexFloat:
5828 case APValue::Vector:
5829 case APValue::Array:
5830 case APValue::Struct:
5831 case APValue::Union:
5832 llvm_unreachable("invalid kind for template argument");
5833 }
5834
5835 return ArgResult.get();
5836 }
5837
Douglas Gregor86560402009-02-10 23:36:10 +00005838 // C++ [temp.arg.nontype]p5:
5839 // The following conversions are performed on each expression used
5840 // as a non-type template-argument. If a non-type
5841 // template-argument cannot be converted to the type of the
5842 // corresponding template-parameter then the program is
5843 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005844 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005845 // C++11:
5846 // -- for a non-type template-parameter of integral or
5847 // enumeration type, conversions permitted in a converted
5848 // constant expression are applied.
5849 //
5850 // C++98:
5851 // -- for a non-type template-parameter of integral or
5852 // enumeration type, integral promotions (4.5) and integral
5853 // conversions (4.7) are applied.
5854
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005855 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005856 // C++ [temp.arg.nontype]p1:
5857 // A template-argument for a non-type, non-template template-parameter
5858 // shall be one of:
5859 //
5860 // -- for a non-type template-parameter of integral or enumeration
5861 // type, a converted constant expression of the type of the
5862 // template-parameter; or
5863 llvm::APSInt Value;
5864 ExprResult ArgResult =
5865 CheckConvertedConstantExpression(Arg, ParamType, Value,
5866 CCEK_TemplateArg);
5867 if (ArgResult.isInvalid())
5868 return ExprError();
5869
Richard Smith01bfa682016-12-27 02:02:09 +00005870 // We can't check arbitrary value-dependent arguments.
5871 if (ArgResult.get()->isValueDependent()) {
5872 Converted = TemplateArgument(ArgResult.get());
5873 return ArgResult;
5874 }
5875
Richard Smithf8379a02012-01-18 23:55:52 +00005876 // Widen the argument value to sizeof(parameter type). This is almost
5877 // always a no-op, except when the parameter type is bool. In
5878 // that case, this may extend the argument from 1 bit to 8 bits.
5879 QualType IntegerType = ParamType;
5880 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5881 IntegerType = Enum->getDecl()->getIntegerType();
5882 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5883
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005884 Converted = TemplateArgument(Context, Value,
5885 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005886 return ArgResult;
5887 }
5888
Richard Smith08b12f12011-10-27 22:11:44 +00005889 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5890 if (ArgResult.isInvalid())
5891 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005892 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005893
5894 QualType ArgType = Arg->getType();
5895
Douglas Gregor86560402009-02-10 23:36:10 +00005896 // C++ [temp.arg.nontype]p1:
5897 // A template-argument for a non-type, non-template
5898 // template-parameter shall be one of:
5899 //
5900 // -- an integral constant-expression of integral or enumeration
5901 // type; or
5902 // -- the name of a non-type template-parameter; or
5903 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005904 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005905 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005906 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005907 diag::err_template_arg_not_integral_or_enumeral)
5908 << ArgType << Arg->getSourceRange();
5909 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005910 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005911 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005912 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5913 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005914
Douglas Gregore2b37442012-05-04 22:38:52 +00005915 public:
5916 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005917
5918 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5919 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005920 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5921 }
5922 } Diagnoser(ArgType);
5923
5924 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005925 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005926 if (!Arg)
5927 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005928 }
5929
Richard Smithd663fdd2014-12-17 20:42:37 +00005930 // From here on out, all we care about is the unqualified form
5931 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005932 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005933
5934 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005935 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005936 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005937 } else if (ParamType->isBooleanType()) {
5938 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005939 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005940 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5941 !ParamType->isEnumeralType()) {
5942 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005943 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005944 } else {
5945 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005946 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005947 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005948 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005949 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005950 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005951 }
5952
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005953 // Add the value of this argument to the list of converted
5954 // arguments. We use the bitwidth and signedness of the template
5955 // parameter.
5956 if (Arg->isValueDependent()) {
5957 // The argument is value-dependent. Create a new
5958 // TemplateArgument with the converted expression.
5959 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005960 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005961 }
5962
Douglas Gregor52aba872009-03-14 00:20:21 +00005963 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005964 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005965 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005966
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005967 if (ParamType->isBooleanType()) {
5968 // Value must be zero or one.
5969 Value = Value != 0;
5970 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5971 if (Value.getBitWidth() != AllowedBits)
5972 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005973 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005974 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005975 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005976
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005977 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005978 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005979 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005980 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005981 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005982 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00005983
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005984 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005985 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005986 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005987 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005988 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5989 << Arg->getSourceRange();
5990 Diag(Param->getLocation(), diag::note_template_param_here);
5991 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005992
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005993 // Complain if we overflowed the template parameter's type.
5994 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005995 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005996 RequiredBits = OldValue.getActiveBits();
5997 else if (OldValue.isUnsigned())
5998 RequiredBits = OldValue.getActiveBits() + 1;
5999 else
6000 RequiredBits = OldValue.getMinSignedBits();
6001 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006002 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006003 diag::warn_template_arg_too_large)
6004 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6005 << Arg->getSourceRange();
6006 Diag(Param->getLocation(), diag::note_template_param_here);
6007 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006008 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006009
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006010 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006011 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006012 ? Context.getCanonicalType(ParamType)
6013 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006014 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006015 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006016
Richard Smith08b12f12011-10-27 22:11:44 +00006017 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006018 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6019
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006020 // Handle pointer-to-function, reference-to-function, and
6021 // pointer-to-member-function all in (roughly) the same way.
6022 if (// -- For a non-type template-parameter of type pointer to
6023 // function, only the function-to-pointer conversion (4.3) is
6024 // applied. If the template-argument represents a set of
6025 // overloaded functions (or a pointer to such), the matching
6026 // function is selected from the set (13.4).
6027 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006028 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006029 // -- For a non-type template-parameter of type reference to
6030 // function, no conversions apply. If the template-argument
6031 // represents a set of overloaded functions, the matching
6032 // function is selected from the set (13.4).
6033 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006034 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006035 // -- For a non-type template-parameter of type pointer to
6036 // member function, no conversions apply. If the
6037 // template-argument represents a set of overloaded member
6038 // functions, the matching member function is selected from
6039 // the set (13.4).
6040 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006041 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006042 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006043
Douglas Gregor064fdb22010-04-14 23:11:21 +00006044 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006045 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006046 true,
6047 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006048 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006049 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006050
6051 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6052 ArgType = Arg->getType();
6053 } else
John Wiegley01296292011-04-08 18:41:53 +00006054 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006056
John Wiegley01296292011-04-08 18:41:53 +00006057 if (!ParamType->isMemberPointerType()) {
6058 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6059 ParamType,
6060 Arg, Converted))
6061 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006062 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006063 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006064
Douglas Gregor20fdef32012-04-10 17:08:25 +00006065 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6066 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006067 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006068 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006069 }
6070
Chris Lattner696197c2009-02-20 21:37:53 +00006071 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006072 // -- for a non-type template-parameter of type pointer to
6073 // object, qualification conversions (4.4) and the
6074 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006075 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006076 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006077 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006078
John Wiegley01296292011-04-08 18:41:53 +00006079 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6080 ParamType,
6081 Arg, Converted))
6082 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006083 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006084 }
Mike Stump11289f42009-09-09 15:08:12 +00006085
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006086 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006087 // -- For a non-type template-parameter of type reference to
6088 // object, no conversions apply. The type referred to by the
6089 // reference may be more cv-qualified than the (otherwise
6090 // identical) type of the template-argument. The
6091 // template-parameter is bound directly to the
6092 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006093 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006094 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006095
Douglas Gregor064fdb22010-04-14 23:11:21 +00006096 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006097 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6098 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006099 true,
6100 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006101 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006102 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006103
6104 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6105 ArgType = Arg->getType();
6106 } else
John Wiegley01296292011-04-08 18:41:53 +00006107 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006109
John Wiegley01296292011-04-08 18:41:53 +00006110 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6111 ParamType,
6112 Arg, Converted))
6113 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006114 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006115 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006116
Douglas Gregor20fdef32012-04-10 17:08:25 +00006117 // Deal with parameters of type std::nullptr_t.
6118 if (ParamType->isNullPtrType()) {
6119 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6120 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006121 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006122 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006123
Douglas Gregor20fdef32012-04-10 17:08:25 +00006124 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6125 case NPV_NotNullPointer:
6126 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6127 << Arg->getType() << ParamType;
6128 Diag(Param->getLocation(), diag::note_template_param_here);
6129 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006130
Douglas Gregor20fdef32012-04-10 17:08:25 +00006131 case NPV_Error:
6132 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006133
Douglas Gregor20fdef32012-04-10 17:08:25 +00006134 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006135 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006136 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6137 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006138 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006139 }
6140 }
6141
Douglas Gregor0e558532009-02-11 16:16:59 +00006142 // -- For a non-type template-parameter of type pointer to data
6143 // member, qualification conversions (4.4) are applied.
6144 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6145
Douglas Gregor20fdef32012-04-10 17:08:25 +00006146 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6147 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006148 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006149 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006150}
6151
Richard Smith26b86ea2016-12-31 21:41:23 +00006152static void DiagnoseTemplateParameterListArityMismatch(
6153 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6154 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6155
Douglas Gregord32e0282009-02-09 23:23:08 +00006156/// \brief Check a template argument against its corresponding
6157/// template template parameter.
6158///
6159/// This routine implements the semantics of C++ [temp.arg.template].
6160/// It returns true if an error occurred, and false otherwise.
6161bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00006162 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00006163 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006164 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006165 TemplateDecl *Template = Name.getAsTemplateDecl();
6166 if (!Template) {
6167 // Any dependent template name is fine.
6168 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6169 return false;
6170 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006171
Richard Smith26b86ea2016-12-31 21:41:23 +00006172 if (Template->isInvalidDecl())
6173 return true;
6174
Richard Smith3f1b5d02011-05-05 21:57:07 +00006175 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006176 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006177 // the name of a class template or an alias template, expressed as an
6178 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006179 // primary class templates are considered when matching the
6180 // template template argument with the corresponding parameter;
6181 // partial specializations are not considered even if their
6182 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006183 //
6184 // Note that we also allow template template parameters here, which
6185 // will happen when we are dealing with, e.g., class template
6186 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006187 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006188 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006189 !isa<TypeAliasTemplateDecl>(Template) &&
6190 !isa<BuiltinTemplateDecl>(Template)) {
6191 assert(isa<FunctionTemplateDecl>(Template) &&
6192 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006193 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006194 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6195 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006196 }
6197
Richard Smith1fde8ec2012-09-07 02:06:42 +00006198 TemplateParameterList *Params = Param->getTemplateParameters();
6199 if (Param->isExpandedParameterPack())
6200 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6201
Richard Smith26b86ea2016-12-31 21:41:23 +00006202 // C++1z [temp.arg.template]p3: (DR 150)
6203 // A template-argument matches a template template-parameter P when P
6204 // is at least as specialized as the template-argument A.
6205 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6206 // Quick check for the common case:
6207 // If P contains a parameter pack, then A [...] matches P if each of A's
6208 // template parameters matches the corresponding template parameter in
6209 // the template-parameter-list of P.
6210 if (TemplateParameterListsAreEqual(
6211 Template->getTemplateParameters(), Params, false,
6212 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6213 return false;
6214
6215 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6216 Arg.getLocation()))
6217 return false;
6218 // FIXME: Produce better diagnostics for deduction failures.
6219 }
6220
Douglas Gregor85e0f662009-02-10 00:24:35 +00006221 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006222 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006223 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006224 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006225 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006226}
6227
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006228/// \brief Given a non-type template argument that refers to a
6229/// declaration and the type of its corresponding non-type template
6230/// parameter, produce an expression that properly refers to that
6231/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006232ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006233Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6234 QualType ParamType,
6235 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006236 // C++ [temp.param]p8:
6237 //
6238 // A non-type template-parameter of type "array of T" or
6239 // "function returning T" is adjusted to be of type "pointer to
6240 // T" or "pointer to function returning T", respectively.
6241 if (ParamType->isArrayType())
6242 ParamType = Context.getArrayDecayedType(ParamType);
6243 else if (ParamType->isFunctionType())
6244 ParamType = Context.getPointerType(ParamType);
6245
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006246 // For a NULL non-type template argument, return nullptr casted to the
6247 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006248 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006249 return ImpCastExprToType(
6250 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6251 ParamType,
6252 ParamType->getAs<MemberPointerType>()
6253 ? CK_NullToMemberPointer
6254 : CK_NullToPointer);
6255 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006256 assert(Arg.getKind() == TemplateArgument::Declaration &&
6257 "Only declaration template arguments permitted here");
6258
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006259 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6260
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006261 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006262 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6263 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006264 // If the value is a class member, we might have a pointer-to-member.
6265 // Determine whether the non-type template template parameter is of
6266 // pointer-to-member type. If so, we need to build an appropriate
6267 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6268 // would refer to the member itself.
6269 if (ParamType->isMemberPointerType()) {
6270 QualType ClassType
6271 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6272 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006273 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006274 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006275 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006276 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006277
6278 // The actual value-ness of this is unimportant, but for
6279 // internal consistency's sake, references to instance methods
6280 // are r-values.
6281 ExprValueKind VK = VK_LValue;
6282 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6283 VK = VK_RValue;
6284
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006285 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006286 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006287 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006288 Loc,
6289 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006290 if (RefExpr.isInvalid())
6291 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006292
John McCalle3027922010-08-25 11:45:40 +00006293 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006294
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006295 // We might need to perform a trailing qualification conversion, since
6296 // the element type on the parameter could be more qualified than the
6297 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006298 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006299 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006300 ParamType.getUnqualifiedType(), false,
6301 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006302 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006303
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006304 assert(!RefExpr.isInvalid() &&
6305 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006306 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006307 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006308 }
6309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006310
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006311 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006312
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006313 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006314 // When the non-type template parameter is a pointer, take the
6315 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006316 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006317 if (RefExpr.isInvalid())
6318 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006319
Richard Smithfc6fca12017-01-28 00:38:35 +00006320 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6321 (T->isFunctionType() || T->isArrayType())) {
6322 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006323 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006324 if (RefExpr.isInvalid())
6325 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006326
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006327 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006329
Douglas Gregorb242683d2010-04-01 18:32:35 +00006330 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006331 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006332 }
6333
John McCall7decc9e2010-11-18 06:31:45 +00006334 ExprValueKind VK = VK_RValue;
6335
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006336 // If the non-type template parameter has reference type, qualify the
6337 // resulting declaration reference with the extra qualifiers on the
6338 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006339 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6340 VK = VK_LValue;
6341 T = Context.getQualifiedType(T,
6342 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006343 } else if (isa<FunctionDecl>(VD)) {
6344 // References to functions are always lvalues.
6345 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006346 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006347
John McCall7decc9e2010-11-18 06:31:45 +00006348 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006349}
6350
6351/// \brief Construct a new expression that refers to the given
6352/// integral template argument with the given source-location
6353/// information.
6354///
6355/// This routine takes care of the mapping from an integral template
6356/// argument (which may have any integral type) to the appropriate
6357/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006358ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006359Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6360 SourceLocation Loc) {
6361 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006362 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006363 QualType OrigT = Arg.getIntegralType();
6364
6365 // If this is an enum type that we're instantiating, we need to use an integer
6366 // type the same size as the enumerator. We don't want to build an
6367 // IntegerLiteral with enum type. The integer type of an enum type can be of
6368 // any integral type with C++11 enum classes, make sure we create the right
6369 // type of literal for it.
6370 QualType T = OrigT;
6371 if (const EnumType *ET = OrigT->getAs<EnumType>())
6372 T = ET->getDecl()->getIntegerType();
6373
6374 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006375 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00006376 // This does not need to handle u8 character literals because those are
6377 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00006378 CharacterLiteral::CharacterKind Kind;
6379 if (T->isWideCharType())
6380 Kind = CharacterLiteral::Wide;
6381 else if (T->isChar16Type())
6382 Kind = CharacterLiteral::UTF16;
6383 else if (T->isChar32Type())
6384 Kind = CharacterLiteral::UTF32;
6385 else
6386 Kind = CharacterLiteral::Ascii;
6387
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006388 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6389 Kind, T, Loc);
6390 } else if (T->isBooleanType()) {
6391 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6392 T, Loc);
6393 } else if (T->isNullPtrType()) {
6394 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6395 } else {
6396 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00006397 }
6398
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006399 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00006400 // FIXME: This is a hack. We need a better way to handle substituted
6401 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00006402 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6403 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006404 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00006405 Loc, Loc);
6406 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006407
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006408 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006409}
6410
Richard Smith43a833b2017-01-09 23:54:33 +00006411static bool isDependentOnOuter(NonTypeTemplateParmDecl *NTTP) {
6412 if (NTTP->getDepth() == 0 || !NTTP->getType()->isDependentType())
6413 return false;
6414 DependencyChecker Checker(NTTP->getDepth(), /*IgnoreNonTypeDependent*/ false,
6415 /*FindLessThanDepth*/ true);
6416 Checker.TraverseType(NTTP->getType());
6417 return Checker.Match;
6418}
6419
Douglas Gregor641040a2011-01-12 23:45:44 +00006420/// \brief Match two template parameters within template parameter lists.
6421static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6422 bool Complain,
6423 Sema::TemplateParameterListEqualKind Kind,
6424 SourceLocation TemplateArgLoc) {
6425 // Check the actual kind (type, non-type, template).
6426 if (Old->getKind() != New->getKind()) {
6427 if (Complain) {
6428 unsigned NextDiag = diag::err_template_param_different_kind;
6429 if (TemplateArgLoc.isValid()) {
6430 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6431 NextDiag = diag::note_template_param_different_kind;
6432 }
6433 S.Diag(New->getLocation(), NextDiag)
6434 << (Kind != Sema::TPL_TemplateMatch);
6435 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6436 << (Kind != Sema::TPL_TemplateMatch);
6437 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006438
Douglas Gregor641040a2011-01-12 23:45:44 +00006439 return false;
6440 }
6441
Richard Smith26b86ea2016-12-31 21:41:23 +00006442 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006443 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006444 // template template parameter, the template template parameter can have
6445 // a parameter pack where the template template argument does not.
6446 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6447 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6448 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006449 if (Complain) {
6450 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6451 if (TemplateArgLoc.isValid()) {
6452 S.Diag(TemplateArgLoc,
6453 diag::err_template_arg_template_params_mismatch);
6454 NextDiag = diag::note_template_parameter_pack_non_pack;
6455 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006456
Douglas Gregor641040a2011-01-12 23:45:44 +00006457 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6458 : isa<NonTypeTemplateParmDecl>(New)? 1
6459 : 2;
6460 S.Diag(New->getLocation(), NextDiag)
6461 << ParamKind << New->isParameterPack();
6462 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6463 << ParamKind << Old->isParameterPack();
6464 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006465
Douglas Gregor641040a2011-01-12 23:45:44 +00006466 return false;
6467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006468
Douglas Gregor641040a2011-01-12 23:45:44 +00006469 // For non-type template parameters, check the type of the parameter.
6470 if (NonTypeTemplateParmDecl *OldNTTP
6471 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6472 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006473
Douglas Gregor641040a2011-01-12 23:45:44 +00006474 // If we are matching a template template argument to a template
6475 // template parameter and one of the non-type template parameter types
Richard Smith43a833b2017-01-09 23:54:33 +00006476 // is dependent on an outer template's parameter, then we must wait until
6477 // template instantiation time to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00006478 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith43a833b2017-01-09 23:54:33 +00006479 (isDependentOnOuter(OldNTTP) || isDependentOnOuter(NewNTTP)))
Douglas Gregor641040a2011-01-12 23:45:44 +00006480 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006481
Douglas Gregor641040a2011-01-12 23:45:44 +00006482 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6483 if (Complain) {
6484 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6485 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006486 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00006487 diag::err_template_arg_template_params_mismatch);
6488 NextDiag = diag::note_template_nontype_parm_different_type;
6489 }
6490 S.Diag(NewNTTP->getLocation(), NextDiag)
6491 << NewNTTP->getType()
6492 << (Kind != Sema::TPL_TemplateMatch);
6493 S.Diag(OldNTTP->getLocation(),
6494 diag::note_template_nontype_parm_prev_declaration)
6495 << OldNTTP->getType();
6496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006497
Douglas Gregor641040a2011-01-12 23:45:44 +00006498 return false;
6499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006500
Douglas Gregor641040a2011-01-12 23:45:44 +00006501 return true;
6502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006503
Douglas Gregor641040a2011-01-12 23:45:44 +00006504 // For template template parameters, check the template parameter types.
6505 // The template parameter lists of template template
6506 // parameters must agree.
6507 if (TemplateTemplateParmDecl *OldTTP
6508 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006509 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00006510 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6511 OldTTP->getTemplateParameters(),
6512 Complain,
6513 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006514 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00006515 : Kind),
6516 TemplateArgLoc);
6517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006518
Douglas Gregor641040a2011-01-12 23:45:44 +00006519 return true;
6520}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006521
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006522/// \brief Diagnose a known arity mismatch when comparing template argument
6523/// lists.
6524static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006525void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006526 TemplateParameterList *New,
6527 TemplateParameterList *Old,
6528 Sema::TemplateParameterListEqualKind Kind,
6529 SourceLocation TemplateArgLoc) {
6530 unsigned NextDiag = diag::err_template_param_list_different_arity;
6531 if (TemplateArgLoc.isValid()) {
6532 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6533 NextDiag = diag::note_template_param_list_different_arity;
6534 }
6535 S.Diag(New->getTemplateLoc(), NextDiag)
6536 << (New->size() > Old->size())
6537 << (Kind != Sema::TPL_TemplateMatch)
6538 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6539 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6540 << (Kind != Sema::TPL_TemplateMatch)
6541 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6542}
6543
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006544/// \brief Determine whether the given template parameter lists are
6545/// equivalent.
6546///
Mike Stump11289f42009-09-09 15:08:12 +00006547/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006548/// source code as part of a new template declaration.
6549///
6550/// \param Old The old template parameter list, typically found via
6551/// name lookup of the template declared with this template parameter
6552/// list.
6553///
6554/// \param Complain If true, this routine will produce a diagnostic if
6555/// the template parameter lists are not equivalent.
6556///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006557/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00006558///
6559/// \param TemplateArgLoc If this source location is valid, then we
6560/// are actually checking the template parameter list of a template
6561/// argument (New) against the template parameter list of its
6562/// corresponding template template parameter (Old). We produce
6563/// slightly different diagnostics in this scenario.
6564///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006565/// \returns True if the template parameter lists are equal, false
6566/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00006567bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006568Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6569 TemplateParameterList *Old,
6570 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006571 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00006572 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006573 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6574 if (Complain)
6575 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6576 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006577
6578 return false;
6579 }
6580
Douglas Gregor641040a2011-01-12 23:45:44 +00006581 // C++0x [temp.arg.template]p3:
6582 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006583 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00006584 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006585 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006586 // template-parameter-list of P. [...]
6587 TemplateParameterList::iterator NewParm = New->begin();
6588 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006589 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006590 OldParmEnd = Old->end();
6591 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00006592 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6593 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006594 if (NewParm == NewParmEnd) {
6595 if (Complain)
6596 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6597 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006598
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006599 return false;
6600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006601
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006602 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6603 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006604 return false;
6605
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006606 ++NewParm;
6607 continue;
6608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006609
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006610 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006611 // [...] When P's template- parameter-list contains a template parameter
6612 // pack (14.5.3), the template parameter pack will match zero or more
6613 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006614 // template-parameter-list of A with the same type and form as the
6615 // template parameter pack in P (ignoring whether those template
6616 // parameters are template parameter packs).
6617 for (; NewParm != NewParmEnd; ++NewParm) {
6618 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6619 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006620 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006621 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006623
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006624 // Make sure we exhausted all of the arguments.
6625 if (NewParm != NewParmEnd) {
6626 if (Complain)
6627 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6628 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006629
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006630 return false;
6631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006632
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006633 return true;
6634}
6635
6636/// \brief Check whether a template can be declared within this scope.
6637///
6638/// If the template declaration is valid in this scope, returns
6639/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00006640bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006641Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00006642 if (!S)
6643 return false;
6644
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006645 // Find the nearest enclosing declaration scope.
6646 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6647 (S->getFlags() & Scope::TemplateParamScope) != 0)
6648 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006649
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006650 // C++ [temp]p4:
6651 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00006652 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00006653 if (Ctx && Ctx->isExternCContext()) {
6654 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6655 << TemplateParams->getSourceRange();
6656 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6657 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6658 return true;
6659 }
Richard Smith8df390f2016-09-08 23:14:54 +00006660 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006661
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006662 // C++ [temp]p2:
6663 // A template-declaration can appear only as a namespace scope or
6664 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00006665 if (Ctx) {
6666 if (Ctx->isFileContext())
6667 return false;
6668 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6669 // C++ [temp.mem]p2:
6670 // A local class shall not have member templates.
6671 if (RD->isLocalClass())
6672 return Diag(TemplateParams->getTemplateLoc(),
6673 diag::err_template_inside_local_class)
6674 << TemplateParams->getSourceRange();
6675 else
6676 return false;
6677 }
6678 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006679
Mike Stump11289f42009-09-09 15:08:12 +00006680 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006681 diag::err_template_outside_namespace_or_class_scope)
6682 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006683}
Douglas Gregor67a65642009-02-17 23:15:12 +00006684
Douglas Gregor54888652009-10-07 00:13:32 +00006685/// \brief Determine what kind of template specialization the given declaration
6686/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006687static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00006688 if (!D)
6689 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006690
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006691 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6692 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00006693 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6694 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006695 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6696 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006697
Douglas Gregor54888652009-10-07 00:13:32 +00006698 return TSK_Undeclared;
6699}
6700
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006701/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006702/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00006703///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006704/// This routine determines whether a template specialization can be declared
6705/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00006706///
6707/// \param S the semantic analysis object for which this check is being
6708/// performed.
6709///
6710/// \param Specialized the entity being specialized or instantiated, which
6711/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006712/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00006713/// member class).
6714///
6715/// \param PrevDecl the previous declaration of this entity, if any.
6716///
6717/// \param Loc the location of the explicit specialization or instantiation of
6718/// this entity.
6719///
6720/// \param IsPartialSpecialization whether this is a partial specialization of
6721/// a class template.
6722///
Douglas Gregor54888652009-10-07 00:13:32 +00006723/// \returns true if there was an error that we cannot recover from, false
6724/// otherwise.
6725static bool CheckTemplateSpecializationScope(Sema &S,
6726 NamedDecl *Specialized,
6727 NamedDecl *PrevDecl,
6728 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006729 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00006730 // Keep these "kind" numbers in sync with the %select statements in the
6731 // various diagnostics emitted by this routine.
6732 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006733 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006734 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006735 else if (isa<VarTemplateDecl>(Specialized))
6736 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006737 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006738 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006739 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006740 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006741 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00006742 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006743 else if (isa<RecordDecl>(Specialized))
6744 EntityKind = 7;
6745 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6746 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00006747 else {
Richard Smith7d137e32012-03-23 03:33:32 +00006748 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006749 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006750 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00006751 return true;
6752 }
6753
Douglas Gregorf47b9112009-02-25 22:02:03 +00006754 // C++ [temp.expl.spec]p2:
6755 // An explicit specialization shall be declared in the namespace
6756 // of which the template is a member, or, for member templates, in
6757 // the namespace of which the enclosing class or enclosing class
6758 // template is a member. An explicit specialization of a member
6759 // function, member class or static data member of a class
6760 // template shall be declared in the namespace of which the class
6761 // template is a member. Such a declaration may also be a
6762 // definition. If the declaration is not a definition, the
6763 // specialization may be defined later in the name- space in which
6764 // the explicit specialization was declared, or in a namespace
6765 // that encloses the one in which the explicit specialization was
6766 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00006767 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00006768 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006769 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006770 return true;
6771 }
Douglas Gregore4b05162009-10-07 17:21:34 +00006772
Douglas Gregor40fb7442009-10-07 17:30:37 +00006773 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006774 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006775 // Do not warn for class scope explicit specialization during
6776 // instantiation, warning was already emitted during pattern
6777 // semantic analysis.
6778 if (!S.ActiveTemplateInstantiations.size())
6779 S.Diag(Loc, diag::ext_function_specialization_in_class)
6780 << Specialized;
6781 } else {
6782 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6783 << Specialized;
6784 return true;
6785 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006787
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006788 if (S.CurContext->isRecord() &&
6789 !S.CurContext->Equals(Specialized->getDeclContext())) {
6790 // Make sure that we're specializing in the right record context.
6791 // Otherwise, things can go horribly wrong.
6792 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6793 << Specialized;
6794 return true;
6795 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006796
Douglas Gregore4b05162009-10-07 17:21:34 +00006797 // C++ [temp.class.spec]p6:
6798 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006799 // in any namespace scope in which its definition may be defined (14.5.1
6800 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00006801 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00006802 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00006803 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00006804
6805 // Make sure that this redeclaration (or definition) occurs in an enclosing
6806 // namespace.
6807 // Note that HandleDeclarator() performs this check for explicit
6808 // specializations of function templates, static data members, and member
6809 // functions, so we skip the check here for those kinds of entities.
6810 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6811 // Should we refactor that check, so that it occurs later?
6812 if (!DC->Encloses(SpecializedContext) &&
6813 !(isa<FunctionTemplateDecl>(Specialized) ||
6814 isa<FunctionDecl>(Specialized) ||
6815 isa<VarTemplateDecl>(Specialized) ||
6816 isa<VarDecl>(Specialized))) {
6817 if (isa<TranslationUnitDecl>(SpecializedContext))
6818 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6819 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00006820 else if (isa<NamespaceDecl>(SpecializedContext)) {
6821 int Diag = diag::err_template_spec_redecl_out_of_scope;
6822 if (S.getLangOpts().MicrosoftExt)
6823 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6824 S.Diag(Loc, Diag) << EntityKind << Specialized
6825 << cast<NamedDecl>(SpecializedContext);
6826 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00006827 llvm_unreachable("unexpected namespace context for specialization");
6828
6829 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6830 } else if ((!PrevDecl ||
6831 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6832 getTemplateSpecializationKind(PrevDecl) ==
6833 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006834 // C++ [temp.exp.spec]p2:
6835 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006836 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006837 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006838 // An explicit specialization of a member function, member class or
6839 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006840 // namespace of which the class template is a member.
6841 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006842 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006843 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006844 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006845 // C++11 [temp.explicit]p3:
6846 // An explicit instantiation shall appear in an enclosing namespace of its
6847 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006848 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006849 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006850 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006851 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006852 "DC encloses TU but isn't in enclosing namespace set");
6853 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006854 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006855 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6856 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006857 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006858 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006859 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006860 Diag = diag::ext_template_spec_decl_out_of_scope;
6861 else
6862 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6863 S.Diag(Loc, Diag)
6864 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6865 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006866
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006867 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006868 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006869 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006870
Douglas Gregorf47b9112009-02-25 22:02:03 +00006871 return false;
6872}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006873
Richard Smith57aae072016-12-28 02:37:25 +00006874static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
6875 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00006876 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006877 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006878 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00006879 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006880 return E->getSourceRange();
6881 return Checker.MatchLoc;
6882}
6883
6884static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6885 if (!TL.getType()->isDependentType())
6886 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006887 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006888 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00006889 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006890 return TL.getSourceRange();
6891 return Checker.MatchLoc;
6892}
6893
Larisse Voufo39a1e502013-08-06 01:03:05 +00006894/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006895/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006896static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006897 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6898 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006899 for (unsigned I = 0; I != NumArgs; ++I) {
6900 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006901 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006902 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6903 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006904 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006905
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006906 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006907 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006908
Eli Friedmanb826a002012-09-26 02:36:12 +00006909 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006910 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006911
6912 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006913
Douglas Gregor98318c22011-01-03 21:37:45 +00006914 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006915 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6916 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006917
6918 // Strip off any implicit casts we added as part of type checking.
6919 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6920 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006921
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006922 // C++ [temp.class.spec]p8:
6923 // A non-type argument is non-specialized if it is the name of a
6924 // non-type parameter. All other non-type arguments are
6925 // specialized.
6926 //
6927 // Below, we check the two conditions that only apply to
6928 // specialized non-type arguments, so skip any non-specialized
6929 // arguments.
6930 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006931 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006932 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006933
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006934 // C++ [temp.class.spec]p9:
6935 // Within the argument list of a class template partial
6936 // specialization, the following restrictions apply:
6937 // -- A partially specialized non-type argument expression
6938 // shall not involve a template parameter of the partial
6939 // specialization except when the argument expression is a
6940 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00006941 // -- The type of a template parameter corresponding to a
6942 // specialized non-type argument shall not be dependent on a
6943 // parameter of the specialization.
6944 // DR1315 removes the first bullet, leaving an incoherent set of rules.
6945 // We implement a compromise between the original rules and DR1315:
6946 // -- A specialized non-type template argument shall not be
6947 // type-dependent and the corresponding template parameter
6948 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00006949 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00006950 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00006951 if (ParamUseRange.isValid()) {
6952 if (IsDefaultArgument) {
6953 S.Diag(TemplateNameLoc,
6954 diag::err_dependent_non_type_arg_in_partial_spec);
6955 S.Diag(ParamUseRange.getBegin(),
6956 diag::note_dependent_non_type_default_arg_in_partial_spec)
6957 << ParamUseRange;
6958 } else {
6959 S.Diag(ParamUseRange.getBegin(),
6960 diag::err_dependent_non_type_arg_in_partial_spec)
6961 << ParamUseRange;
6962 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006963 return true;
6964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006965
Richard Smith6056d5e2014-02-09 00:54:43 +00006966 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00006967 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00006968 if (ParamUseRange.isValid()) {
6969 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6970 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Richard Smith57aae072016-12-28 02:37:25 +00006971 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00006972 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00006973 << (IsDefaultArgument ? ParamUseRange : SourceRange())
6974 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006975 return true;
6976 }
6977 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006978
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006979 return false;
6980}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006981
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006982/// \brief Check the non-type template arguments of a class template
6983/// partial specialization according to C++ [temp.class.spec]p9.
6984///
Richard Smith6056d5e2014-02-09 00:54:43 +00006985/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00006986/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006987/// template.
6988/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006989/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006990/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006991///
Richard Smith6056d5e2014-02-09 00:54:43 +00006992/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00006993bool Sema::CheckTemplatePartialSpecializationArgs(
6994 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
6995 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
6996 // We have to be conservative when checking a template in a dependent
6997 // context.
6998 if (PrimaryTemplate->getDeclContext()->isDependentContext())
6999 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007000
Richard Smith57aae072016-12-28 02:37:25 +00007001 TemplateParameterList *TemplateParams =
7002 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007003 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7004 NonTypeTemplateParmDecl *Param
7005 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7006 if (!Param)
7007 continue;
7008
Richard Smith57aae072016-12-28 02:37:25 +00007009 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7010 Param, &TemplateArgs[I],
7011 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007012 return true;
7013 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007014
7015 return false;
7016}
7017
John McCall48871652010-08-21 09:40:31 +00007018DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00007019Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
7020 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00007021 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007022 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007023 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00007024 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00007025 MultiTemplateParamsArg
7026 TemplateParameterLists,
7027 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007028 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007029
Richard Smith4b55a9c2014-04-17 03:29:33 +00007030 CXXScopeSpec &SS = TemplateId.SS;
7031
Abramo Bagnara60804e12011-03-18 15:16:37 +00007032 // NOTE: KWLoc is the location of the tag keyword. This will instead
7033 // store the location of the outermost template keyword in the declaration.
7034 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007035 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7036 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7037 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7038 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007039
Douglas Gregor67a65642009-02-17 23:15:12 +00007040 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007041 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007042 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007043 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7044
7045 if (!ClassTemplate) {
7046 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007047 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007048 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7049 return true;
7050 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007051
Richard Smithf445f192017-02-09 21:04:43 +00007052 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007053 bool isPartialSpecialization = false;
7054
Douglas Gregorf47b9112009-02-25 22:02:03 +00007055 // Check the validity of the template headers that introduce this
7056 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007057 // FIXME: We probably shouldn't complain about these headers for
7058 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007059 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007060 TemplateParameterList *TemplateParams =
7061 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007062 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007063 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007064 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007065 if (Invalid)
7066 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007067
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007068 if (TemplateParams && TemplateParams->size() > 0) {
7069 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007070
Douglas Gregorec9518b2010-12-21 08:14:57 +00007071 if (TUK == TUK_Friend) {
7072 Diag(KWLoc, diag::err_partial_specialization_friend)
7073 << SourceRange(LAngleLoc, RAngleLoc);
7074 return true;
7075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007076
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007077 // C++ [temp.class.spec]p10:
7078 // The template parameter list of a specialization shall not
7079 // contain default template argument values.
7080 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7081 Decl *Param = TemplateParams->getParam(I);
7082 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7083 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007084 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007085 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007086 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007087 }
7088 } else if (NonTypeTemplateParmDecl *NTTP
7089 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7090 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007091 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007092 diag::err_default_arg_in_partial_spec)
7093 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007094 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007095 }
7096 } else {
7097 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007098 if (TTP->hasDefaultArgument()) {
7099 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007100 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007101 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007102 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007103 }
7104 }
7105 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007106 } else if (TemplateParams) {
7107 if (TUK == TUK_Friend)
7108 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007109 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007110 SourceRange(TemplateParams->getTemplateLoc(),
7111 TemplateParams->getRAngleLoc()))
7112 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007113 } else {
7114 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007115 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007116
Douglas Gregor67a65642009-02-17 23:15:12 +00007117 // Check that the specialization uses the same tag kind as the
7118 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007119 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7120 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007121 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007122 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007123 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007124 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007125 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007126 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007127 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007128 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007129 diag::note_previous_use);
7130 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7131 }
7132
Douglas Gregorc40290e2009-03-09 23:48:35 +00007133 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007134 TemplateArgumentListInfo TemplateArgs =
7135 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007136
Douglas Gregor14406932011-01-03 20:35:03 +00007137 // Check for unexpanded parameter packs in any of the template arguments.
7138 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007139 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007140 UPPC_PartialSpecialization))
7141 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007142
Douglas Gregor67a65642009-02-17 23:15:12 +00007143 // Check that the template argument list is well-formed for this
7144 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007145 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007146 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7147 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007148 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007149
Douglas Gregor2373c592009-05-31 09:31:02 +00007150 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007151 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007152 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007153 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7154 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007155 return true;
7156
Richard Smith57aae072016-12-28 02:37:25 +00007157 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7158 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007159 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007160 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007161 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007162 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007163 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7164 << ClassTemplate->getDeclName();
7165 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007166 }
7167 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007168
Craig Topperc3ec1492014-05-26 06:22:03 +00007169 void *InsertPos = nullptr;
7170 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007171
7172 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007173 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007174 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007175 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007176 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007177
Craig Topperc3ec1492014-05-26 06:22:03 +00007178 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007179
Douglas Gregorf47b9112009-02-25 22:02:03 +00007180 // Check whether we can declare a class template specialization in
7181 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007182 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007183 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7184 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007185 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007186 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007187
Douglas Gregor15301382009-07-30 17:40:51 +00007188 // The canonical type
7189 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007190 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007191 // Build the canonical type that describes the converted template
7192 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007193 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7194 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007195 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007196
7197 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007198 ClassTemplate->getInjectedClassNameSpecialization())) {
7199 // C++ [temp.class.spec]p9b3:
7200 //
7201 // -- The argument list of the specialization shall not be identical
7202 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007203 //
7204 // This rule has since been removed, because it's redundant given DR1495,
7205 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007206 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007207 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007208 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007209 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7210 ClassTemplate->getIdentifier(),
7211 TemplateNameLoc,
7212 Attr,
7213 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007214 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007215 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007216 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007217 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007218 }
Douglas Gregor15301382009-07-30 17:40:51 +00007219
Douglas Gregor2373c592009-05-31 09:31:02 +00007220 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007221 ClassTemplatePartialSpecializationDecl *PrevPartial
7222 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007223 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007224 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007225 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007226 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007227 TemplateParams,
7228 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007229 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007230 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007231 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007232 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00007233 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007234 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007235 Partial->setTemplateParameterListsInfo(
7236 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007237 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007238
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007239 if (!PrevPartial)
7240 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007241 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007242
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007243 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007244 // template specialization, make a note of that.
7245 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7246 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007247
Richard Smith57aae072016-12-28 02:37:25 +00007248 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007249 } else {
7250 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007251 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007252 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007253 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007254 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007255 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007256 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007257 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007258 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007259 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007260 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007261 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007262 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007263 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007264
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007265 if (!PrevDecl)
7266 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007267
David Majnemer678f50b2015-11-18 19:49:19 +00007268 if (CurContext->isDependentContext()) {
7269 // -fms-extensions permits specialization of nested classes without
7270 // fully specializing the outer class(es).
7271 assert(getLangOpts().MicrosoftExt &&
7272 "Only possible with -fms-extensions!");
7273 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7274 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007275 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007276 } else {
7277 CanonType = Context.getTypeDeclType(Specialization);
7278 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007279 }
7280
Douglas Gregor06db9f52009-10-12 20:18:28 +00007281 // C++ [temp.expl.spec]p6:
7282 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007283 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007284 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007285 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007286 // use occurs; no diagnostic is required.
7287 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007288 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007289 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007290 // Is there any previous explicit specialization declaration?
7291 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7292 Okay = true;
7293 break;
7294 }
7295 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007296
Douglas Gregorc854c662010-02-26 06:03:23 +00007297 if (!Okay) {
7298 SourceRange Range(TemplateNameLoc, RAngleLoc);
7299 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7300 << Context.getTypeDeclType(Specialization) << Range;
7301
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007302 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007303 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007304 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007305 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007306 return true;
7307 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007309
Douglas Gregor2208a292009-09-26 20:57:03 +00007310 // If this is not a friend, note that this is an explicit specialization.
7311 if (TUK != TUK_Friend)
7312 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007313
7314 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007315 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007316 RecordDecl *Def = Specialization->getDefinition();
7317 NamedDecl *Hidden = nullptr;
7318 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7319 SkipBody->ShouldSkip = true;
7320 makeMergedDefinitionVisible(Hidden, KWLoc);
7321 // From here on out, treat this as just a redeclaration.
7322 TUK = TUK_Declaration;
7323 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007324 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007325 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007326 Diag(Def->getLocation(), diag::note_previous_definition);
7327 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007328 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007329 }
7330 }
7331
John McCall659a3372010-12-18 03:30:47 +00007332 if (Attr)
7333 ProcessDeclAttributeList(S, Specialization, Attr);
7334
Richard Smith034b94a2012-08-17 03:20:55 +00007335 // Add alignment attributes if necessary; these attributes are checked when
7336 // the ASTContext lays out the structure.
7337 if (TUK == TUK_Definition) {
7338 AddAlignmentAttributesForRecord(Specialization);
7339 AddMsStructLayoutForRecord(Specialization);
7340 }
7341
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007342 if (ModulePrivateLoc.isValid())
7343 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7344 << (isPartialSpecialization? 1 : 0)
7345 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007346
Douglas Gregord56a91e2009-02-26 22:19:44 +00007347 // Build the fully-sugared type for this class template
7348 // specialization as the user wrote in the specialization
7349 // itself. This means that we'll pretty-print the type retrieved
7350 // from the specialization's declaration the way that the user
7351 // actually wrote the specialization, rather than formatting the
7352 // name based on the "canonical" representation used to store the
7353 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007354 TypeSourceInfo *WrittenTy
7355 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7356 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007357 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007358 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007359 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007360 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007361
Douglas Gregor1e249f82009-02-25 22:18:32 +00007362 // C++ [temp.expl.spec]p9:
7363 // A template explicit specialization is in the scope of the
7364 // namespace in which the template was defined.
7365 //
7366 // We actually implement this paragraph where we set the semantic
7367 // context (in the creation of the ClassTemplateSpecializationDecl),
7368 // but we also maintain the lexical context where the actual
7369 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007370 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007371
Douglas Gregor67a65642009-02-17 23:15:12 +00007372 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007373 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00007374 Specialization->startDefinition();
7375
Douglas Gregor2208a292009-09-26 20:57:03 +00007376 if (TUK == TUK_Friend) {
7377 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7378 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007379 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007380 /*FIXME:*/KWLoc);
7381 Friend->setAccess(AS_public);
7382 CurContext->addDecl(Friend);
7383 } else {
7384 // Add the specialization into its lexical context, so that it can
7385 // be seen when iterating through the list of declarations in that
7386 // context. However, specializations are not found by name lookup.
7387 CurContext->addDecl(Specialization);
7388 }
John McCall48871652010-08-21 09:40:31 +00007389 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007390}
Douglas Gregor333489b2009-03-27 23:10:48 +00007391
John McCall48871652010-08-21 09:40:31 +00007392Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007393 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007394 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007395 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007396 ActOnDocumentableDecl(NewDecl);
7397 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007398}
7399
John McCall4f7ced62010-02-11 01:33:53 +00007400/// \brief Strips various properties off an implicit instantiation
7401/// that has just been explicitly specialized.
7402static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007403 D->dropAttr<DLLImportAttr>();
7404 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007405
Nico Webere4974382014-12-19 23:52:45 +00007406 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007407 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007408}
7409
Nico Webera8f80b32012-01-09 19:52:25 +00007410/// \brief Compute the diagnostic location for an explicit instantiation
7411// declaration or definition.
7412static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007413 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007414 // Explicit instantiations following a specialization have no effect and
7415 // hence no PointOfInstantiation. In that case, walk decl backwards
7416 // until a valid name loc is found.
7417 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007418 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7419 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007420 PrevDiagLoc = Prev->getLocation();
7421 }
7422 assert(PrevDiagLoc.isValid() &&
7423 "Explicit instantiation without point of instantiation?");
7424 return PrevDiagLoc;
7425}
7426
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007427/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007428/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007429/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007430/// new specialization/instantiation will have any effect.
7431///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007432/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007433/// instantiation.
7434///
7435/// \param NewTSK the kind of the new explicit specialization or instantiation.
7436///
7437/// \param PrevDecl the previous declaration of the entity.
7438///
7439/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7440///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007441/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007442/// declaration was instantiated (either implicitly or explicitly).
7443///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007444/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007445/// specialization or instantiation has no effect and should be ignored.
7446///
7447/// \returns true if there was an error that should prevent the introduction of
7448/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007449bool
7450Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7451 TemplateSpecializationKind NewTSK,
7452 NamedDecl *PrevDecl,
7453 TemplateSpecializationKind PrevTSK,
7454 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007455 bool &HasNoEffect) {
7456 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007457
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007458 switch (NewTSK) {
7459 case TSK_Undeclared:
7460 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007461 assert(
7462 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7463 "previous declaration must be implicit!");
7464 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007465
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007466 case TSK_ExplicitSpecialization:
7467 switch (PrevTSK) {
7468 case TSK_Undeclared:
7469 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007470 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007471 // explicitly specialized or has merely been mentioned without any
7472 // instantiation.
7473 return false;
7474
7475 case TSK_ImplicitInstantiation:
7476 if (PrevPointOfInstantiation.isInvalid()) {
7477 // The declaration itself has not actually been instantiated, so it is
7478 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007479 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007480 return false;
7481 }
7482 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007483
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007484 case TSK_ExplicitInstantiationDeclaration:
7485 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007486 assert((PrevTSK == TSK_ImplicitInstantiation ||
7487 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007488 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007489
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007490 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007491 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007492 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007493 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007494 // implicit instantiation to take place, in every translation unit in
7495 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007496 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007497 // Is there any previous explicit specialization declaration?
7498 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7499 return false;
7500 }
7501
Douglas Gregor1d957a32009-10-27 18:42:08 +00007502 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007503 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007504 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007505 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007506
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007507 return true;
7508 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007509
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007510 case TSK_ExplicitInstantiationDeclaration:
7511 switch (PrevTSK) {
7512 case TSK_ExplicitInstantiationDeclaration:
7513 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007514 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007515 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007516
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007517 case TSK_Undeclared:
7518 case TSK_ImplicitInstantiation:
7519 // We're explicitly instantiating something that may have already been
7520 // implicitly instantiated; that's fine.
7521 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007522
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007523 case TSK_ExplicitSpecialization:
7524 // C++0x [temp.explicit]p4:
7525 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007526 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007527 // specialization for that template, the explicit instantiation has no
7528 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007529 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007530 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007531
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007532 case TSK_ExplicitInstantiationDefinition:
7533 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007534 // If an entity is the subject of both an explicit instantiation
7535 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007536 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007537 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007538 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007539
7540 // Explicit instantiations following a specialization have no effect and
7541 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7542 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007543 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7544 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007545 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007546 return false;
7547 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007548
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007549 case TSK_ExplicitInstantiationDefinition:
7550 switch (PrevTSK) {
7551 case TSK_Undeclared:
7552 case TSK_ImplicitInstantiation:
7553 // We're explicitly instantiating something that may have already been
7554 // implicitly instantiated; that's fine.
7555 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007556
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007557 case TSK_ExplicitSpecialization:
7558 // C++ DR 259, C++0x [temp.explicit]p4:
7559 // For a given set of template parameters, if an explicit
7560 // instantiation of a template appears after a declaration of
7561 // an explicit specialization for that template, the explicit
7562 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00007563 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007564 << PrevDecl;
7565 Diag(PrevDecl->getLocation(),
7566 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007567 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007568 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007569
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007570 case TSK_ExplicitInstantiationDeclaration:
7571 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007572 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00007573
7574 // C++0x [temp.explicit]p4:
7575 // For a given set of template parameters, if an explicit instantiation
7576 // of a template appears after a declaration of an explicit
7577 // specialization for that template, the explicit instantiation has no
7578 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007579 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00007580 // Is there any previous explicit specialization declaration?
7581 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7582 HasNoEffect = true;
7583 break;
7584 }
7585 }
7586
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007587 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007588
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007589 case TSK_ExplicitInstantiationDefinition:
7590 // C++0x [temp.spec]p5:
7591 // For a given template and a given set of template-arguments,
7592 // - an explicit instantiation definition shall appear at most once
7593 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007594
7595 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7596 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00007597 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007598 : diag::err_explicit_instantiation_duplicate)
7599 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00007600 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00007601 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007602 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007603 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007604 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007605 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007606
David Blaikie83d382b2011-09-23 05:06:16 +00007607 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007608}
7609
John McCallb9c78482010-04-08 09:05:18 +00007610/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00007611/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00007612///
James Dennettf14a6e52012-06-15 22:23:43 +00007613/// The only possible way to get a dependent function template specialization
7614/// is with a friend declaration, like so:
7615///
7616/// \code
7617/// template \<class T> void foo(T);
7618/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00007619/// friend void foo<>(T);
7620/// };
James Dennettf14a6e52012-06-15 22:23:43 +00007621/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00007622///
7623/// There really isn't any useful analysis we can do here, so we
7624/// just store the information.
7625bool
7626Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7627 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7628 LookupResult &Previous) {
7629 // Remove anything from Previous that isn't a function template in
7630 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00007631 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00007632 LookupResult::Filter F = Previous.makeFilter();
7633 while (F.hasNext()) {
7634 NamedDecl *D = F.next()->getUnderlyingDecl();
7635 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00007636 !FDLookupContext->InEnclosingNamespaceSetOf(
7637 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00007638 F.erase();
7639 }
7640 F.done();
7641
7642 // Should this be diagnosed here?
7643 if (Previous.empty()) return true;
7644
7645 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7646 ExplicitTemplateArgs);
7647 return false;
7648}
7649
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007650/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007651/// specialization.
7652///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007653/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007654/// explicit function template specialization. On successful completion,
7655/// the function declaration \p FD will become a function template
7656/// specialization.
7657///
7658/// \param FD the function declaration, which will be updated to become a
7659/// function template specialization.
7660///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007661/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7662/// if any. Note that this may be valid info even when 0 arguments are
7663/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7664/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007665///
Francois Pichet3a44e432011-07-08 06:21:47 +00007666/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007667/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007668bool Sema::CheckFunctionTemplateSpecialization(
7669 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7670 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007671 // The set of function template specializations that could match this
7672 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00007673 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007674 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7675 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007676
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007677 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7678 ConvertedTemplateArgs;
7679
Sebastian Redl50c68252010-08-31 00:36:30 +00007680 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00007681 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7682 I != E; ++I) {
7683 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7684 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007685 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007686 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007687 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7688 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007689 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007690
Richard Smith574f4f62013-01-14 05:37:29 +00007691 // When matching a constexpr member function template specialization
7692 // against the primary template, we don't yet know whether the
7693 // specialization has an implicit 'const' (because we don't know whether
7694 // it will be a static member function until we know which template it
7695 // specializes), so adjust it now assuming it specializes this template.
7696 QualType FT = FD->getType();
7697 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007698 CXXMethodDecl *OldMD =
7699 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00007700 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007701 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00007702 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7703 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007704 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007705 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00007706 }
7707 }
7708
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007709 TemplateArgumentListInfo Args;
7710 if (ExplicitTemplateArgs)
7711 Args = *ExplicitTemplateArgs;
7712
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007713 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007714 // A trailing template-argument can be left unspecified in the
7715 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007716 // provided it can be deduced from the function argument type.
7717 // Perform template argument deduction to determine whether we may be
7718 // specializing this template.
7719 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00007720 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007721 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00007722 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7723 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00007724 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7725 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007726 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007727 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00007728 FailedCandidates.addCandidate().set(
7729 I.getPair(), FunTmpl->getTemplatedDecl(),
7730 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007731 (void)TDK;
7732 continue;
7733 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007734
Artem Belevich64135c32016-12-08 19:38:13 +00007735 // Target attributes are part of the cuda function signature, so
7736 // the deduced template's cuda target must match that of the
7737 // specialization. Given that C++ template deduction does not
7738 // take target attributes into account, we reject candidates
7739 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007740 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00007741 IdentifyCUDATarget(Specialization,
7742 /* IgnoreImplicitHDAttributes = */ true) !=
7743 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007744 FailedCandidates.addCandidate().set(
7745 I.getPair(), FunTmpl->getTemplatedDecl(),
7746 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7747 continue;
7748 }
7749
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007750 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007751 if (ExplicitTemplateArgs)
7752 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00007753 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007754 }
7755 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007756
Douglas Gregor5de279c2009-09-26 03:41:46 +00007757 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007758 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007759 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007760 FD->getLocation(),
7761 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7762 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00007763 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007764 PDiag(diag::note_function_template_spec_matched));
7765
John McCall58cc69d2010-01-27 01:50:18 +00007766 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007767 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007768
7769 // Ignore access information; it doesn't figure into redeclaration checking.
7770 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007771
Nathan Wilson83839122016-04-09 02:55:27 +00007772 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7773 // an explicit specialization (14.8.3) [...] of a concept definition.
7774 if (Specialization->getPrimaryTemplate()->isConcept()) {
7775 Diag(FD->getLocation(), diag::err_concept_specialized)
7776 << 0 /*function*/ << 1 /*explicitly specialized*/;
7777 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7778 return true;
7779 }
7780
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007781 FunctionTemplateSpecializationInfo *SpecInfo
7782 = Specialization->getTemplateSpecializationInfo();
7783 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007784
7785 // Note: do not overwrite location info if previous template
7786 // specialization kind was explicit.
7787 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00007788 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00007789 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00007790 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7791 // function can differ from the template declaration with respect to
7792 // the constexpr specifier.
7793 Specialization->setConstexpr(FD->isConstexpr());
7794 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007795
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007796 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00007797 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00007798
7799 // If this is a friend declaration, then we're not really declaring
7800 // an explicit specialization.
7801 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007802
Douglas Gregor54888652009-10-07 00:13:32 +00007803 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00007804 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007805 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00007806 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007807 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007808 false))
Douglas Gregor54888652009-10-07 00:13:32 +00007809 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007810
7811 // C++ [temp.expl.spec]p6:
7812 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007813 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007814 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007815 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007816 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007817 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007818 if (!isFriend &&
7819 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007820 TSK_ExplicitSpecialization,
7821 Specialization,
7822 SpecInfo->getTemplateSpecializationKind(),
7823 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007824 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007825 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00007826
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007827 // Mark the prior declaration as an explicit specialization, so that later
7828 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007829 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007830 // Since explicit specializations do not inherit '=delete' from their
7831 // primary function template - check if the 'specialization' that was
7832 // implicitly generated (during template argument deduction for partial
7833 // ordering) from the most specialized of all the function templates that
7834 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7835 // first check that it was implicitly generated during template argument
7836 // deduction by making sure it wasn't referenced, and then reset the deleted
7837 // flag to not-deleted, so that we can inherit that information from 'FD'.
7838 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7839 !Specialization->getCanonicalDecl()->isReferenced()) {
7840 assert(
7841 Specialization->getCanonicalDecl() == Specialization &&
7842 "This must be the only existing declaration of this specialization");
7843 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007844 }
John McCall816d75b2010-03-24 07:46:06 +00007845 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007846 MarkUnusedFileScopedDecl(Specialization);
7847 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007848
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007849 // Turn the given function declaration into a function template
7850 // specialization, with the template arguments from the previous
7851 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007852 // Take copies of (semantic and syntactic) template argument lists.
7853 const TemplateArgumentList* TemplArgs = new (Context)
7854 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007855 FD->setFunctionTemplateSpecialization(
7856 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7857 SpecInfo->getTemplateSpecializationKind(),
7858 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007859
Artem Belevich64135c32016-12-08 19:38:13 +00007860 // A function template specialization inherits the target attributes
7861 // of its template. (We require the attributes explicitly in the
7862 // code to match, but a template may have implicit attributes by
7863 // virtue e.g. of being constexpr, and it passes these implicit
7864 // attributes on to its specializations.)
7865 if (LangOpts.CUDA)
7866 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
7867
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007868 // The "previous declaration" for this function template specialization is
7869 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007870 Previous.clear();
7871 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007872 return false;
7873}
7874
Douglas Gregor86d142a2009-10-08 07:24:58 +00007875/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007876/// specialization.
7877///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007878/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007879/// explicit member function specialization. On successful completion,
7880/// the function declaration \p FD will become a member function
7881/// specialization.
7882///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007883/// \param Member the member declaration, which will be updated to become a
7884/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007885///
John McCall1f82f242009-11-18 22:49:29 +00007886/// \param Previous the set of declarations, one of which may be specialized
7887/// by this function specialization; the set will be modified to contain the
7888/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007889bool
John McCall1f82f242009-11-18 22:49:29 +00007890Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007891 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007892
Douglas Gregor86d142a2009-10-08 07:24:58 +00007893 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007894 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007895 NamedDecl *Instantiation = nullptr;
7896 NamedDecl *InstantiatedFrom = nullptr;
7897 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007898
John McCall1f82f242009-11-18 22:49:29 +00007899 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007900 // Nowhere to look anyway.
7901 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007902 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7903 I != E; ++I) {
7904 NamedDecl *D = (*I)->getUnderlyingDecl();
7905 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007906 QualType Adjusted = Function->getType();
7907 if (!hasExplicitCallingConv(Adjusted))
7908 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7909 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007910 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007911 Instantiation = Method;
7912 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007913 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007914 break;
7915 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007916 }
7917 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007918 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007919 VarDecl *PrevVar;
7920 if (Previous.isSingleResult() &&
7921 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007922 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007923 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007924 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007925 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007926 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007927 }
7928 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007929 CXXRecordDecl *PrevRecord;
7930 if (Previous.isSingleResult() &&
7931 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007932 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007933 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007934 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007935 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007936 }
Richard Smith7d137e32012-03-23 03:33:32 +00007937 } else if (isa<EnumDecl>(Member)) {
7938 EnumDecl *PrevEnum;
7939 if (Previous.isSingleResult() &&
7940 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007941 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007942 Instantiation = PrevEnum;
7943 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7944 MSInfo = PrevEnum->getMemberSpecializationInfo();
7945 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007946 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007947
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007948 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007949 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007950 // specializations are always out-of-line, the caller will complain about
7951 // this mismatch later.
7952 return false;
7953 }
John McCalle820e5e2010-04-13 20:37:33 +00007954
7955 // If this is a friend, just bail out here before we start turning
7956 // things into explicit specializations.
7957 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7958 // Preserve instantiation information.
7959 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7960 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7961 cast<CXXMethodDecl>(InstantiatedFrom),
7962 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7963 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7964 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7965 cast<CXXRecordDecl>(InstantiatedFrom),
7966 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7967 }
7968
7969 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007970 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007971 return false;
7972 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007973
Douglas Gregor86d142a2009-10-08 07:24:58 +00007974 // Make sure that this is a specialization of a member.
7975 if (!InstantiatedFrom) {
7976 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7977 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007978 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7979 return true;
7980 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007981
Douglas Gregor06db9f52009-10-12 20:18:28 +00007982 // C++ [temp.expl.spec]p6:
7983 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007984 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007985 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007986 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007987 // use occurs; no diagnostic is required.
7988 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007989
Abramo Bagnara8075c852010-06-12 07:44:57 +00007990 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007991 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7992 TSK_ExplicitSpecialization,
7993 Instantiation,
7994 MSInfo->getTemplateSpecializationKind(),
7995 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007996 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007997 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007998
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007999 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008000 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008001 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008002 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008003 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008004 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008005
Douglas Gregor86d142a2009-10-08 07:24:58 +00008006 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008007 // the original declaration to note that it is an explicit specialization
8008 // (if it was previously an implicit instantiation). This latter step
8009 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00008010 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008011 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8012 if (InstantiationFunction->getTemplateSpecializationKind() ==
8013 TSK_ImplicitInstantiation) {
8014 InstantiationFunction->setTemplateSpecializationKind(
8015 TSK_ExplicitSpecialization);
8016 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008017 // Explicit specializations of member functions of class templates do not
8018 // inherit '=delete' from the member function they are specializing.
8019 if (InstantiationFunction->isDeleted()) {
8020 assert(InstantiationFunction->getCanonicalDecl() ==
8021 InstantiationFunction);
Richard Smith5f274382016-09-28 23:55:27 +00008022 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008023 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008025
Douglas Gregor86d142a2009-10-08 07:24:58 +00008026 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
8027 cast<CXXMethodDecl>(InstantiatedFrom),
8028 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008029 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00008030 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008031 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
8032 if (InstantiationVar->getTemplateSpecializationKind() ==
8033 TSK_ImplicitInstantiation) {
8034 InstantiationVar->setTemplateSpecializationKind(
8035 TSK_ExplicitSpecialization);
8036 InstantiationVar->setLocation(Member->getLocation());
8037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008038
Larisse Voufo39a1e502013-08-06 01:03:05 +00008039 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
8040 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008041 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00008042 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008043 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
8044 if (InstantiationClass->getTemplateSpecializationKind() ==
8045 TSK_ImplicitInstantiation) {
8046 InstantiationClass->setTemplateSpecializationKind(
8047 TSK_ExplicitSpecialization);
8048 InstantiationClass->setLocation(Member->getLocation());
8049 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008050
Douglas Gregor86d142a2009-10-08 07:24:58 +00008051 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008052 cast<CXXRecordDecl>(InstantiatedFrom),
8053 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00008054 } else {
8055 assert(isa<EnumDecl>(Member) && "Only member enums remain");
8056 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
8057 if (InstantiationEnum->getTemplateSpecializationKind() ==
8058 TSK_ImplicitInstantiation) {
8059 InstantiationEnum->setTemplateSpecializationKind(
8060 TSK_ExplicitSpecialization);
8061 InstantiationEnum->setLocation(Member->getLocation());
8062 }
8063
8064 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
8065 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00008066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008067
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008068 // Save the caller the trouble of having to figure out which declaration
8069 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008070 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008071 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008072 return false;
8073}
8074
Douglas Gregore47f5a72009-10-14 23:41:34 +00008075/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008076///
8077/// \returns true if a serious error occurs, false otherwise.
8078static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008079 SourceLocation InstLoc,
8080 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008081 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8082 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008083
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008084 if (CurContext->isRecord()) {
8085 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8086 << D;
8087 return true;
8088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008089
Richard Smith050d2612011-10-18 02:28:33 +00008090 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008091 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008092 // template. If the name declared in the explicit instantiation is an
8093 // unqualified name, the explicit instantiation shall appear in the
8094 // namespace where its template is declared or, if that namespace is inline
8095 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008096 //
8097 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008098 if (WasQualifiedName) {
8099 if (CurContext->Encloses(OrigContext))
8100 return false;
8101 } else {
8102 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8103 return false;
8104 }
8105
8106 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8107 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008108 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008109 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008110 diag::err_explicit_instantiation_out_of_scope :
8111 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008112 << D << NS;
8113 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008114 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008115 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008116 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8117 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8118 << D << NS;
8119 } else
8120 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008121 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008122 diag::err_explicit_instantiation_must_be_global :
8123 diag::warn_explicit_instantiation_must_be_global_0x)
8124 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008125 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008126 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008127}
8128
8129/// \brief Determine whether the given scope specifier has a template-id in it.
8130static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8131 if (!SS.isSet())
8132 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008133
Richard Smith050d2612011-10-18 02:28:33 +00008134 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008135 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008136 // or a static data member of a class template specialization, the name of
8137 // the class template specialization in the qualified-id for the member
8138 // name shall be a simple-template-id.
8139 //
8140 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008141 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8142 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008143 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008144 if (isa<TemplateSpecializationType>(T))
8145 return true;
8146
8147 return false;
8148}
8149
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008150/// Make a dllexport or dllimport attr on a class template specialization take
8151/// effect.
8152static void dllExportImportClassTemplateSpecialization(
8153 Sema &S, ClassTemplateSpecializationDecl *Def) {
8154 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8155 assert(A && "dllExportImportClassTemplateSpecialization called "
8156 "on Def without dllexport or dllimport");
8157
8158 // We reject explicit instantiations in class scope, so there should
8159 // never be any delayed exported classes to worry about.
8160 assert(S.DelayedDllExportClasses.empty() &&
8161 "delayed exports present at explicit instantiation");
8162 S.checkClassLevelDLLAttribute(Def);
8163
8164 // Propagate attribute to base class templates.
8165 for (auto &B : Def->bases()) {
8166 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8167 B.getType()->getAsCXXRecordDecl()))
8168 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8169 }
8170
8171 S.referenceDLLExportedClassMethods();
8172}
8173
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008174// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00008175DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008176Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008177 SourceLocation ExternLoc,
8178 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008179 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00008180 SourceLocation KWLoc,
8181 const CXXScopeSpec &SS,
8182 TemplateTy TemplateD,
8183 SourceLocation TemplateNameLoc,
8184 SourceLocation LAngleLoc,
8185 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00008186 SourceLocation RAngleLoc,
8187 AttributeList *Attr) {
8188 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008189 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008190 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008191 // Check that the specialization uses the same tag kind as the
8192 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008193 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8194 assert(Kind != TTK_Enum &&
8195 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008196
Richard Trieu265c3442016-04-05 21:13:54 +00008197 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8198
8199 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008200 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8201 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008202 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008203 return true;
8204 }
8205
Douglas Gregord9034f02009-05-14 16:41:31 +00008206 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008207 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008208 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008209 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008210 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008211 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008212 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008213 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008214 diag::note_previous_use);
8215 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8216 }
8217
Douglas Gregore47f5a72009-10-14 23:41:34 +00008218 // C++0x [temp.explicit]p2:
8219 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008220 // definition and an explicit instantiation declaration. An explicit
8221 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008222 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8223 ? TSK_ExplicitInstantiationDefinition
8224 : TSK_ExplicitInstantiationDeclaration;
8225
8226 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8227 // Check for dllexport class template instantiation declarations.
8228 for (AttributeList *A = Attr; A; A = A->getNext()) {
8229 if (A->getKind() == AttributeList::AT_DLLExport) {
8230 Diag(ExternLoc,
8231 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8232 Diag(A->getLoc(), diag::note_attribute);
8233 break;
8234 }
8235 }
8236
8237 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8238 Diag(ExternLoc,
8239 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8240 Diag(A->getLocation(), diag::note_attribute);
8241 }
8242 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008243
Hans Wennborga86a83b2016-05-26 19:42:56 +00008244 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8245 // instantiation declarations for most purposes.
8246 bool DLLImportExplicitInstantiationDef = false;
8247 if (TSK == TSK_ExplicitInstantiationDefinition &&
8248 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8249 // Check for dllimport class template instantiation definitions.
8250 bool DLLImport =
8251 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8252 for (AttributeList *A = Attr; A; A = A->getNext()) {
8253 if (A->getKind() == AttributeList::AT_DLLImport)
8254 DLLImport = true;
8255 if (A->getKind() == AttributeList::AT_DLLExport) {
8256 // dllexport trumps dllimport here.
8257 DLLImport = false;
8258 break;
8259 }
8260 }
8261 if (DLLImport) {
8262 TSK = TSK_ExplicitInstantiationDeclaration;
8263 DLLImportExplicitInstantiationDef = true;
8264 }
8265 }
8266
Douglas Gregora1f49972009-05-13 00:25:59 +00008267 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008268 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008269 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008270
8271 // Check that the template argument list is well-formed for this
8272 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008273 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008274 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8275 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008276 return true;
8277
Douglas Gregora1f49972009-05-13 00:25:59 +00008278 // Find the class template specialization declaration that
8279 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008280 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008281 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008282 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008283
Abramo Bagnara8075c852010-06-12 07:44:57 +00008284 TemplateSpecializationKind PrevDecl_TSK
8285 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8286
Douglas Gregor54888652009-10-07 00:13:32 +00008287 // C++0x [temp.explicit]p2:
8288 // [...] An explicit instantiation shall appear in an enclosing
8289 // namespace of its template. [...]
8290 //
8291 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008292 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8293 SS.isSet()))
8294 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008295
Craig Topperc3ec1492014-05-26 06:22:03 +00008296 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008297
Abramo Bagnara8075c852010-06-12 07:44:57 +00008298 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008299 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008300 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008301 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008302 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008303 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008304 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008305
Abramo Bagnara8075c852010-06-12 07:44:57 +00008306 // Even though HasNoEffect == true means that this explicit instantiation
8307 // has no effect on semantics, we go on to put its syntax in the AST.
8308
8309 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8310 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008311 // Since the only prior class template specialization with these
8312 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008313 // declaration node as our own, updating the source location
8314 // for the template name to reflect our new declaration.
8315 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008316 Specialization = PrevDecl;
8317 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008318 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008319 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008320
8321 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8322 DLLImportExplicitInstantiationDef) {
8323 // The new specialization might add a dllimport attribute.
8324 HasNoEffect = false;
8325 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008326 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008327
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008328 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008329 // Create a new class template specialization declaration node for
8330 // this explicit specialization.
8331 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008332 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008333 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008334 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008335 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008336 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008337 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00008338 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008339
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008340 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008341 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008342 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008343 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008344 }
8345
8346 // Build the fully-sugared type for this explicit instantiation as
8347 // the user wrote in the explicit instantiation itself. This means
8348 // that we'll pretty-print the type retrieved from the
8349 // specialization's declaration the way that the user actually wrote
8350 // the explicit instantiation, rather than formatting the name based
8351 // on the "canonical" representation used to store the template
8352 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008353 TypeSourceInfo *WrittenTy
8354 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8355 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008356 Context.getTypeDeclType(Specialization));
8357 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008358
Abramo Bagnara8075c852010-06-12 07:44:57 +00008359 // Set source locations for keywords.
8360 Specialization->setExternLoc(ExternLoc);
8361 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008362 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008363
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008364 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Rafael Espindola0b062072012-01-03 06:04:21 +00008365 if (Attr)
8366 ProcessDeclAttributeList(S, Specialization, Attr);
8367
Abramo Bagnara8075c852010-06-12 07:44:57 +00008368 // Add the explicit instantiation into its lexical context. However,
8369 // since explicit instantiations are never found by name lookup, we
8370 // just put it into the declaration context directly.
8371 Specialization->setLexicalDeclContext(CurContext);
8372 CurContext->addDecl(Specialization);
8373
8374 // Syntax is now OK, so return if it has no other effect on semantics.
8375 if (HasNoEffect) {
8376 // Set the template specialization kind.
8377 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008378 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008379 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008380
8381 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008382 // A definition of a class template or class member template
8383 // shall be in scope at the point of the explicit instantiation of
8384 // the class template or class member template.
8385 //
8386 // This check comes when we actually try to perform the
8387 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008388 ClassTemplateSpecializationDecl *Def
8389 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008390 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008391 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00008392 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008393 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008394 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008395 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8396 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008397
Douglas Gregor1d957a32009-10-27 18:42:08 +00008398 // Instantiate the members of this class template specialization.
8399 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008400 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00008401 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008402 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008403 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8404 // TSK_ExplicitInstantiationDefinition
8405 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00008406 (TSK == TSK_ExplicitInstantiationDefinition ||
8407 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00008408 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008409 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008410
Hans Wennborgc0875502015-06-09 00:39:05 +00008411 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00008412 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8413 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00008414 // In the MS ABI, an explicit instantiation definition can add a dll
8415 // attribute to a template with a previous instantiation declaration.
8416 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008417 auto *A = cast<InheritableAttr>(
8418 getDLLAttr(Specialization)->clone(getASTContext()));
8419 A->setInherited(true);
8420 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008421 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008422 }
8423 }
8424
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008425 // Fix a TSK_ImplicitInstantiation followed by a
8426 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008427 bool NewlyDLLExported =
8428 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8429 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008430 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8431 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8432 // In the MS ABI, an explicit instantiation definition can add a dll
8433 // attribute to a template with a previous implicit instantiation.
8434 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8435 // avoid potentially strange codegen behavior. For example, if we extend
8436 // this conditional to dllimport, and we have a source file calling a
8437 // method on an implicitly instantiated template class instance and then
8438 // declaring a dllimport explicit instantiation definition for the same
8439 // template class, the codegen for the method call will not respect the
8440 // dllimport, while it will with cl. The Def will already have the DLL
8441 // attribute, since the Def and Specialization will be the same in the
8442 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8443 // attribute to the Specialization; we just need to make it take effect.
8444 assert(Def == Specialization &&
8445 "Def and Specialization should match for implicit instantiation");
8446 dllExportImportClassTemplateSpecialization(*this, Def);
8447 }
8448
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008449 // Set the template specialization kind. Make sure it is set before
8450 // instantiating the members which will trigger ASTConsumer callbacks.
8451 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008452 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008453 } else {
8454
8455 // Set the template specialization kind.
8456 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008457 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008458
John McCall48871652010-08-21 09:40:31 +00008459 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008460}
8461
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008462// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008463DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008464Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008465 SourceLocation ExternLoc,
8466 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008467 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008468 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008469 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008470 IdentifierInfo *Name,
8471 SourceLocation NameLoc,
8472 AttributeList *Attr) {
8473
Douglas Gregord6ab8742009-05-28 23:31:59 +00008474 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008475 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008476 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008477 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008478 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008479 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008480 SourceLocation(), false, TypeResult(),
8481 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00008482 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8483
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008484 if (!TagD)
8485 return true;
8486
John McCall48871652010-08-21 09:40:31 +00008487 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00008488 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008489
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008490 if (Tag->isInvalidDecl())
8491 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008492
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008493 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8494 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8495 if (!Pattern) {
8496 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8497 << Context.getTypeDeclType(Record);
8498 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8499 return true;
8500 }
8501
Douglas Gregore47f5a72009-10-14 23:41:34 +00008502 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008503 // If the explicit instantiation is for a class or member class, the
8504 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00008505 // simple-template-id.
8506 //
8507 // C++98 has the same restriction, just worded differently.
8508 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00008509 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008510 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008511
Douglas Gregore47f5a72009-10-14 23:41:34 +00008512 // C++0x [temp.explicit]p2:
8513 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008514 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00008515 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00008516 TemplateSpecializationKind TSK
8517 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8518 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008519
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008520 // C++0x [temp.explicit]p2:
8521 // [...] An explicit instantiation shall appear in an enclosing
8522 // namespace of its template. [...]
8523 //
8524 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008525 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008526
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008527 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008528 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00008529 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008530 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00008531 PrevDecl = Record;
8532 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008533 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008534 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008535 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008536 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008537 PrevDecl,
8538 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008539 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008540 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008541 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00008542 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008543 return TagD;
8544 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008545
Douglas Gregor12e49d32009-10-15 22:53:21 +00008546 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008547 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008548 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00008549 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008550 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00008551 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008552 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008553 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00008554 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00008555 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8556 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00008557 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8558 << Pattern;
8559 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008560 } else {
8561 if (InstantiateClass(NameLoc, Record, Def,
8562 getTemplateInstantiationArgs(Record),
8563 TSK))
8564 return true;
8565
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008566 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00008567 if (!RecordDef)
8568 return true;
8569 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008570 }
8571
Douglas Gregor1d957a32009-10-27 18:42:08 +00008572 // Instantiate all of the members of the class.
8573 InstantiateClassMembers(NameLoc, RecordDef,
8574 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008575
Douglas Gregor88d292c2010-05-13 16:44:06 +00008576 if (TSK == TSK_ExplicitInstantiationDefinition)
8577 MarkVTableUsed(NameLoc, RecordDef, true);
8578
Mike Stump87c57ac2009-05-16 07:39:55 +00008579 // FIXME: We don't have any representation for explicit instantiations of
8580 // member classes. Such a representation is not needed for compilation, but it
8581 // should be available for clients that want to see all of the declarations in
8582 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008583 return TagD;
8584}
8585
John McCallfaf5fb42010-08-26 23:41:50 +00008586DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8587 SourceLocation ExternLoc,
8588 SourceLocation TemplateLoc,
8589 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008590 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008591 // TODO: check if/when DNInfo should replace Name.
8592 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8593 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00008594 if (!Name) {
8595 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008596 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008597 diag::err_explicit_instantiation_requires_name)
8598 << D.getDeclSpec().getSourceRange()
8599 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008600
Douglas Gregor450f00842009-09-25 18:43:00 +00008601 return true;
8602 }
8603
8604 // The scope passed in may not be a decl scope. Zip up the scope tree until
8605 // we find one that is.
8606 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8607 (S->getFlags() & Scope::TemplateParamScope) != 0)
8608 S = S->getParent();
8609
8610 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00008611 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8612 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00008613 if (R.isNull())
8614 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008615
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008616 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00008617 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008618 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00008619 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008620 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8621 << Name;
8622 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008623 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008624 != DeclSpec::SCS_unspecified) {
8625 // Complain about then remove the storage class specifier.
8626 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8627 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008628
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008629 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00008630 }
8631
Douglas Gregor3c74d412009-10-14 20:14:33 +00008632 // C++0x [temp.explicit]p1:
8633 // [...] An explicit instantiation of a function template shall not use the
8634 // inline or constexpr specifiers.
8635 // Presumably, this also applies to member functions of class templates as
8636 // well.
Richard Smith83c19292011-10-18 03:44:03 +00008637 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008638 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008639 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00008640 diag::err_explicit_instantiation_inline :
8641 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00008642 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00008643 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00008644 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8645 // not already specified.
8646 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8647 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008648
Nathan Wilsonde498452016-02-08 05:34:00 +00008649 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8650 // applied only to the definition of a function template or variable template,
8651 // declared in namespace scope.
8652 if (D.getDeclSpec().isConceptSpecified()) {
8653 Diag(D.getDeclSpec().getConceptSpecLoc(),
8654 diag::err_concept_specified_specialization) << 0;
8655 return true;
8656 }
8657
Richard Smith19a311a2017-02-09 22:47:51 +00008658 // A deduction guide is not on the list of entities that can be explicitly
8659 // instantiated.
8660 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8661 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8662 << /*explicit instantiation*/ 0;
8663 return true;
8664 }
8665
Douglas Gregore47f5a72009-10-14 23:41:34 +00008666 // C++0x [temp.explicit]p2:
8667 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008668 // definition and an explicit instantiation declaration. An explicit
8669 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00008670 TemplateSpecializationKind TSK
8671 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8672 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008673
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008674 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00008675 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00008676
8677 if (!R->isFunctionType()) {
8678 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008679 // A [...] static data member of a class template can be explicitly
8680 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008681 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008682 // C++1y [temp.explicit]p1:
8683 // A [...] variable [...] template specialization can be explicitly
8684 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00008685 if (Previous.isAmbiguous())
8686 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008687
John McCall67c00872009-12-02 08:25:40 +00008688 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00008689 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008690
Larisse Voufo39a1e502013-08-06 01:03:05 +00008691 if (!PrevTemplate) {
8692 if (!Prev || !Prev->isStaticDataMember()) {
8693 // We expect to see a data data member here.
8694 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8695 << Name;
8696 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8697 P != PEnd; ++P)
8698 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8699 return true;
8700 }
8701
8702 if (!Prev->getInstantiatedFromStaticDataMember()) {
8703 // FIXME: Check for explicit specialization?
8704 Diag(D.getIdentifierLoc(),
8705 diag::err_explicit_instantiation_data_member_not_instantiated)
8706 << Prev;
8707 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8708 // FIXME: Can we provide a note showing where this was declared?
8709 return true;
8710 }
8711 } else {
8712 // Explicitly instantiate a variable template.
8713
8714 // C++1y [dcl.spec.auto]p6:
8715 // ... A program that uses auto or decltype(auto) in a context not
8716 // explicitly allowed in this section is ill-formed.
8717 //
8718 // This includes auto-typed variable template instantiations.
8719 if (R->isUndeducedType()) {
8720 Diag(T->getTypeLoc().getLocStart(),
8721 diag::err_auto_not_allowed_var_inst);
8722 return true;
8723 }
8724
Richard Smithef985ac2013-09-18 02:10:12 +00008725 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8726 // C++1y [temp.explicit]p3:
8727 // If the explicit instantiation is for a variable, the unqualified-id
8728 // in the declaration shall be a template-id.
8729 Diag(D.getIdentifierLoc(),
8730 diag::err_explicit_instantiation_without_template_id)
8731 << PrevTemplate;
8732 Diag(PrevTemplate->getLocation(),
8733 diag::note_explicit_instantiation_here);
8734 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00008735 }
8736
Nathan Wilson83839122016-04-09 02:55:27 +00008737 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8738 // explicit instantiation (14.8.2) [...] of a concept definition.
8739 if (PrevTemplate->isConcept()) {
8740 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8741 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8742 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8743 return true;
8744 }
8745
Richard Smithef985ac2013-09-18 02:10:12 +00008746 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00008747 TemplateArgumentListInfo TemplateArgs =
8748 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00008749
Larisse Voufo39a1e502013-08-06 01:03:05 +00008750 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8751 D.getIdentifierLoc(), TemplateArgs);
8752 if (Res.isInvalid())
8753 return true;
8754
8755 // Ignore access control bits, we don't need them for redeclaration
8756 // checking.
8757 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00008758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008759
Douglas Gregore47f5a72009-10-14 23:41:34 +00008760 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008761 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008762 // or a static data member of a class template specialization, the name of
8763 // the class template specialization in the qualified-id for the member
8764 // name shall be a simple-template-id.
8765 //
8766 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008767 //
Richard Smith5977d872013-09-18 21:55:14 +00008768 // This does not apply to variable template specializations, where the
8769 // template-id is in the unqualified-id instead.
8770 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008771 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008772 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008773 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008774
Douglas Gregore47f5a72009-10-14 23:41:34 +00008775 // Check the scope of this explicit instantiation.
8776 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008777
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008778 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00008779 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8780 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008781 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008782 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00008783 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008784 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008785
Larisse Voufo39a1e502013-08-06 01:03:05 +00008786 if (!HasNoEffect) {
8787 // Instantiate static data member or variable template.
8788
8789 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8790 if (PrevTemplate) {
8791 // Merge attributes.
8792 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8793 ProcessDeclAttributeList(S, Prev, Attr);
8794 }
8795 if (TSK == TSK_ExplicitInstantiationDefinition)
8796 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8797 }
8798
8799 // Check the new variable specialization against the parsed input.
8800 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8801 Diag(T->getTypeLoc().getLocStart(),
8802 diag::err_invalid_var_template_spec_type)
8803 << 0 << PrevTemplate << R << Prev->getType();
8804 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8805 << 2 << PrevTemplate->getDeclName();
8806 return true;
8807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008808
Douglas Gregor450f00842009-09-25 18:43:00 +00008809 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00008810 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008811 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008812
8813 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00008814 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00008815 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00008816 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00008817 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00008818 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00008819 HasExplicitTemplateArgs = true;
8820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008821
Douglas Gregor450f00842009-09-25 18:43:00 +00008822 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008823 // A [...] function [...] can be explicitly instantiated from its template.
8824 // A member function [...] of a class template can be explicitly
8825 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008826 // template.
John McCall58cc69d2010-01-27 01:50:18 +00008827 UnresolvedSet<8> Matches;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008828 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008829 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00008830 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8831 P != PEnd; ++P) {
8832 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00008833 if (!HasExplicitTemplateArgs) {
8834 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00008835 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
8836 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00008837 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00008838 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008839
John McCall58cc69d2010-01-27 01:50:18 +00008840 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008841 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8842 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00008843 }
Douglas Gregor450f00842009-09-25 18:43:00 +00008844 }
8845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008846
Douglas Gregor450f00842009-09-25 18:43:00 +00008847 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8848 if (!FunTmpl)
8849 continue;
8850
Larisse Voufo98b20f12013-07-19 23:00:19 +00008851 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008852 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008853 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008854 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00008855 (HasExplicitTemplateArgs ? &TemplateArgs
8856 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00008857 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008858 // Keep track of almost-matches.
8859 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00008860 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008861 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008862 (void)TDK;
8863 continue;
8864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008865
Artem Belevich64135c32016-12-08 19:38:13 +00008866 // Target attributes are part of the cuda function signature, so
8867 // the cuda target of the instantiated function must match that of its
8868 // template. Given that C++ template deduction does not take
8869 // target attributes into account, we reject candidates here that
8870 // have a different target.
8871 if (LangOpts.CUDA &&
8872 IdentifyCUDATarget(Specialization,
8873 /* IgnoreImplicitHDAttributes = */ true) !=
8874 IdentifyCUDATarget(Attr)) {
8875 FailedCandidates.addCandidate().set(
8876 P.getPair(), FunTmpl->getTemplatedDecl(),
8877 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8878 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008879 }
8880
John McCall58cc69d2010-01-27 01:50:18 +00008881 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008883
Douglas Gregor450f00842009-09-25 18:43:00 +00008884 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008885 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008886 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008887 D.getIdentifierLoc(),
8888 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8889 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8890 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008891
John McCall58cc69d2010-01-27 01:50:18 +00008892 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008893 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008894
8895 // Ignore access control bits, we don't need them for redeclaration checking.
8896 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008897
Alexey Bataev73983912014-11-06 10:10:50 +00008898 // C++11 [except.spec]p4
8899 // In an explicit instantiation an exception-specification may be specified,
8900 // but is not required.
8901 // If an exception-specification is specified in an explicit instantiation
8902 // directive, it shall be compatible with the exception-specifications of
8903 // other declarations of that function.
8904 if (auto *FPT = R->getAs<FunctionProtoType>())
8905 if (FPT->hasExceptionSpec()) {
8906 unsigned DiagID =
8907 diag::err_mismatched_exception_spec_explicit_instantiation;
8908 if (getLangOpts().MicrosoftExt)
8909 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8910 bool Result = CheckEquivalentExceptionSpec(
8911 PDiag(DiagID) << Specialization->getType(),
8912 PDiag(diag::note_explicit_instantiation_here),
8913 Specialization->getType()->getAs<FunctionProtoType>(),
8914 Specialization->getLocation(), FPT, D.getLocStart());
8915 // In Microsoft mode, mismatching exception specifications just cause a
8916 // warning.
8917 if (!getLangOpts().MicrosoftExt && Result)
8918 return true;
8919 }
8920
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008921 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008922 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008923 diag::err_explicit_instantiation_member_function_not_instantiated)
8924 << Specialization
8925 << (Specialization->getTemplateSpecializationKind() ==
8926 TSK_ExplicitSpecialization);
8927 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8928 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008929 }
8930
Douglas Gregorec9fd132012-01-14 16:38:05 +00008931 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008932 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8933 PrevDecl = Specialization;
8934
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008935 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008936 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008937 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008938 PrevDecl,
8939 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008940 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008941 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008942 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008943
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008944 // FIXME: We may still want to build some representation of this
8945 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008946 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008947 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008948 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008949
8950 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008951 if (Attr)
8952 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008953
Richard Smitheb36ddf2014-04-24 22:45:46 +00008954 if (Specialization->isDefined()) {
8955 // Let the ASTConsumer know that this function has been explicitly
8956 // instantiated now, and its linkage might have changed.
8957 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8958 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008959 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008960
Douglas Gregore47f5a72009-10-14 23:41:34 +00008961 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008962 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008963 // or a static data member of a class template specialization, the name of
8964 // the class template specialization in the qualified-id for the member
8965 // name shall be a simple-template-id.
8966 //
8967 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008968 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008969 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008970 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008971 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008972 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008973 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008974 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008975
Nathan Wilson83839122016-04-09 02:55:27 +00008976 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8977 // explicit instantiation (14.8.2) [...] of a concept definition.
8978 if (FunTmpl && FunTmpl->isConcept() &&
8979 !D.getDeclSpec().isConceptSpecified()) {
8980 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8981 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8982 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8983 return true;
8984 }
8985
Douglas Gregore47f5a72009-10-14 23:41:34 +00008986 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008987 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008988 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008989 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008990 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008991
Douglas Gregor450f00842009-09-25 18:43:00 +00008992 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008993 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008994}
8995
John McCallfaf5fb42010-08-26 23:41:50 +00008996TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008997Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8998 const CXXScopeSpec &SS, IdentifierInfo *Name,
8999 SourceLocation TagLoc, SourceLocation NameLoc) {
9000 // This has to hold, because SS is expected to be defined.
9001 assert(Name && "Expected a name in a dependent tag");
9002
Aaron Ballman4a979672014-01-03 13:56:08 +00009003 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009004 if (!NNS)
9005 return true;
9006
Abramo Bagnara6150c882010-05-11 21:36:43 +00009007 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009008
Douglas Gregorba41d012010-04-24 16:38:41 +00009009 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9010 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009011 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009012 return true;
9013 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009014
Douglas Gregore7c20652011-03-02 00:47:37 +00009015 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009016 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009017 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009018
Douglas Gregore7c20652011-03-02 00:47:37 +00009019 // Create type-source location information for this type.
9020 TypeLocBuilder TLB;
9021 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009022 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009023 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9024 TL.setNameLoc(NameLoc);
9025 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009026}
9027
John McCallfaf5fb42010-08-26 23:41:50 +00009028TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009029Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9030 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009031 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009032 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009033 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009034
Richard Smith0bf8a4922011-10-18 20:49:44 +00009035 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9036 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009037 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009038 diag::warn_cxx98_compat_typename_outside_of_template :
9039 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009040 << FixItHint::CreateRemoval(TypenameLoc);
9041
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009042 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009043 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9044 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009045 if (T.isNull())
9046 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009047
9048 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9049 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009050 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009051 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009052 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009053 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009054 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009055 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009056 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009057 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009058 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009059 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009060
John McCallba7bf592010-08-24 05:47:05 +00009061 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009062}
9063
John McCallfaf5fb42010-08-26 23:41:50 +00009064TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009065Sema::ActOnTypenameType(Scope *S,
9066 SourceLocation TypenameLoc,
9067 const CXXScopeSpec &SS,
9068 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009069 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009070 IdentifierInfo *TemplateII,
9071 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009072 SourceLocation LAngleLoc,
9073 ASTTemplateArgsPtr TemplateArgsIn,
9074 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009075 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9076 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009077 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009078 diag::warn_cxx98_compat_typename_outside_of_template :
9079 diag::ext_typename_outside_of_template)
9080 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009081
Richard Smith74f02342017-01-19 21:00:13 +00009082 // Strangely, non-type results are not ignored by this lookup, so the
9083 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009084 if (TypenameLoc.isValid()) {
9085 auto *LookupRD =
9086 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9087 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9088 Diag(TemplateIILoc,
9089 diag::ext_out_of_line_qualified_id_type_names_constructor)
9090 << TemplateII << 0 /*injected-class-name used as template name*/
9091 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9092 }
Richard Smith74f02342017-01-19 21:00:13 +00009093 }
9094
Douglas Gregorb09518c2011-02-27 22:46:49 +00009095 // Translate the parser's template argument list in our AST format.
9096 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9097 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009098
Douglas Gregorb09518c2011-02-27 22:46:49 +00009099 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009100 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9101 // Construct a dependent template specialization type.
9102 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009103 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009104 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9105 DTN->getQualifier(),
9106 DTN->getIdentifier(),
9107 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009108
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009109 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009110 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009111 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009112 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009113 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9114 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009115 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009116 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009117 SpecTL.setLAngleLoc(LAngleLoc);
9118 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009119 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9120 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009121 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009122 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009123
Richard Smith74f02342017-01-19 21:00:13 +00009124 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009125 if (T.isNull())
9126 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009127
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009128 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009129 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009130 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009131 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009132 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009133 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009134 SpecTL.setLAngleLoc(LAngleLoc);
9135 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009136 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9137 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009138
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009139 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9140 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009141 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009142 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009143
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009144 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9145 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009146}
9147
Douglas Gregorb09518c2011-02-27 22:46:49 +00009148
Richard Smith6f8d2c62012-05-09 05:17:00 +00009149/// Determine whether this failed name lookup should be treated as being
9150/// disabled by a usage of std::enable_if.
9151static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9152 SourceRange &CondRange) {
9153 // We must be looking for a ::type...
9154 if (!II.isStr("type"))
9155 return false;
9156
9157 // ... within an explicitly-written template specialization...
9158 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9159 return false;
9160 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009161 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9162 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9163 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009164 return false;
9165 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00009166 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00009167
9168 // ... which names a complete class template declaration...
9169 const TemplateDecl *EnableIfDecl =
9170 EnableIfTST->getTemplateName().getAsTemplateDecl();
9171 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9172 return false;
9173
9174 // ... called "enable_if".
9175 const IdentifierInfo *EnableIfII =
9176 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9177 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9178 return false;
9179
9180 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009181 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009182 return true;
9183}
9184
Douglas Gregor333489b2009-03-27 23:10:48 +00009185/// \brief Build the type that describes a C++ typename specifier,
9186/// e.g., "typename T::type".
9187QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009188Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009189 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009190 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009191 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009192 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009193 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009194 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009195
John McCall0b66eb32010-05-01 00:40:08 +00009196 DeclContext *Ctx = computeDeclContext(SS);
9197 if (!Ctx) {
9198 // If the nested-name-specifier is dependent and couldn't be
9199 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009200 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009201 return Context.getDependentNameType(Keyword,
9202 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009203 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009204 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009205
John McCall0b66eb32010-05-01 00:40:08 +00009206 // If the nested-name-specifier refers to the current instantiation,
9207 // the "typename" keyword itself is superfluous. In C++03, the
9208 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9209 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009210 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009211
John McCall0b66eb32010-05-01 00:40:08 +00009212 if (RequireCompleteDeclContext(SS, Ctx))
9213 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009214
9215 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009216 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009217 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009218 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009219 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009220 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009221 case LookupResult::NotFound: {
9222 // If we're looking up 'type' within a template named 'enable_if', produce
9223 // a more specific diagnostic.
9224 SourceRange CondRange;
9225 if (isEnableIf(QualifierLoc, II, CondRange)) {
9226 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9227 << Ctx << CondRange;
9228 return QualType();
9229 }
9230
Douglas Gregore40876a2009-10-13 21:16:44 +00009231 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009232 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009233 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009234
9235 case LookupResult::FoundUnresolvedValue: {
9236 // We found a using declaration that is a value. Most likely, the using
9237 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009238 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009239 IILoc);
9240 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9241 << Name << Ctx << FullRange;
9242 if (UnresolvedUsingValueDecl *Using
9243 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009244 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009245 Diag(Loc, diag::note_using_value_decl_missing_typename)
9246 << FixItHint::CreateInsertion(Loc, "typename ");
9247 }
9248 }
9249 // Fall through to create a dependent typename type, from which we can recover
9250 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009251
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009252 case LookupResult::NotFoundInCurrentInstantiation:
9253 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009254 return Context.getDependentNameType(Keyword,
9255 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009256 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009257
9258 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009259 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009260 // C++ [class.qual]p2:
9261 // In a lookup in which function names are not ignored and the
9262 // nested-name-specifier nominates a class C, if the name specified
9263 // after the nested-name-specifier, when looked up in C, is the
9264 // injected-class-name of C [...] then the name is instead considered
9265 // to name the constructor of class C.
9266 //
9267 // Unlike in an elaborated-type-specifier, function names are not ignored
9268 // in typename-specifier lookup. However, they are ignored in all the
9269 // contexts where we form a typename type with no keyword (that is, in
9270 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9271 //
9272 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9273 // ignore functions, but that appears to be an oversight.
9274 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9275 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9276 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9277 FoundRD->isInjectedClassName() &&
9278 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9279 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9280 << &II << 1 << 0 /*'typename' keyword used*/;
9281
Abramo Bagnara6150c882010-05-11 21:36:43 +00009282 // We found a type. Build an ElaboratedType, since the
9283 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009284 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009285 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009286 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009287 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009288 }
9289
Richard Smithee579842017-01-30 20:39:26 +00009290 // C++ [dcl.type.simple]p2:
9291 // A type-specifier of the form
9292 // typename[opt] nested-name-specifier[opt] template-name
9293 // is a placeholder for a deduced class type [...].
9294 if (getLangOpts().CPlusPlus1z) {
9295 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9296 return Context.getElaboratedType(
9297 Keyword, QualifierLoc.getNestedNameSpecifier(),
9298 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9299 QualType(), false));
9300 }
9301 }
Richard Smith600b5262017-01-26 20:40:47 +00009302
Douglas Gregor333489b2009-03-27 23:10:48 +00009303 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009304 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009305 break;
9306
9307 case LookupResult::FoundOverloaded:
9308 DiagID = diag::err_typename_nested_not_type;
9309 Referenced = *Result.begin();
9310 break;
9311
John McCall6538c932009-10-10 05:48:19 +00009312 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009313 return QualType();
9314 }
9315
9316 // If we get here, it's because name lookup did not find a
9317 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009318 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009319 IILoc);
9320 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009321 if (Referenced)
9322 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9323 << Name;
9324 return QualType();
9325}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009326
9327namespace {
9328 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009329 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009330 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009331 SourceLocation Loc;
9332 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009333
Douglas Gregor15acfb92009-08-06 16:20:37 +00009334 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009335 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009336
Mike Stump11289f42009-09-09 15:08:12 +00009337 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009338 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009339 DeclarationName Entity)
9340 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009341 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009342
9343 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009344 /// transformed.
9345 ///
9346 /// For the purposes of type reconstruction, a type has already been
9347 /// transformed if it is NULL or if it is not dependent.
9348 bool AlreadyTransformed(QualType T) {
9349 return T.isNull() || !T->isDependentType();
9350 }
Mike Stump11289f42009-09-09 15:08:12 +00009351
9352 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009353 /// rebuilt.
9354 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009355
Douglas Gregor15acfb92009-08-06 16:20:37 +00009356 /// \brief Returns the name of the entity whose type is being rebuilt.
9357 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009358
Douglas Gregoref6ab412009-10-27 06:26:26 +00009359 /// \brief Sets the "base" location and entity when that
9360 /// information is known based on another transformation.
9361 void setBase(SourceLocation Loc, DeclarationName Entity) {
9362 this->Loc = Loc;
9363 this->Entity = Entity;
9364 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009365
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00009366 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9367 // Lambdas never need to be transformed.
9368 return E;
9369 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00009370 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009371} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00009372
Douglas Gregor15acfb92009-08-06 16:20:37 +00009373/// \brief Rebuilds a type within the context of the current instantiation.
9374///
Mike Stump11289f42009-09-09 15:08:12 +00009375/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00009376/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00009377/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00009378/// partial specialization thereof). This routine will rebuild that type now
9379/// that we have entered the declarator's scope, which may produce different
9380/// canonical types, e.g.,
9381///
9382/// \code
9383/// template<typename T>
9384/// struct X {
9385/// typedef T* pointer;
9386/// pointer data();
9387/// };
9388///
9389/// template<typename T>
9390/// typename X<T>::pointer X<T>::data() { ... }
9391/// \endcode
9392///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00009393/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009394/// since we do not know that we can look into X<T> when we parsed the type.
9395/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00009396/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00009397/// as the canonical type of T*, allowing the return types of the out-of-line
9398/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00009399TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9400 SourceLocation Loc,
9401 DeclarationName Name) {
9402 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00009403 return T;
Mike Stump11289f42009-09-09 15:08:12 +00009404
Douglas Gregor15acfb92009-08-06 16:20:37 +00009405 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9406 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00009407}
Douglas Gregorbe999392009-09-15 16:23:51 +00009408
John McCalldadc5752010-08-24 06:29:42 +00009409ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00009410 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9411 DeclarationName());
9412 return Rebuilder.TransformExpr(E);
9413}
9414
John McCall99b2fe52010-04-29 23:50:39 +00009415bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00009416 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009417 return true;
John McCall2408e322010-04-27 00:57:59 +00009418
Douglas Gregor10176412011-02-25 16:07:42 +00009419 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009420 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9421 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009422 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009423 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009424 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009425 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009426
Douglas Gregor10176412011-02-25 16:07:42 +00009427 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009428 return false;
John McCall2408e322010-04-27 00:57:59 +00009429}
9430
Douglas Gregor041b0842011-10-14 15:31:12 +00009431/// \brief Rebuild the template parameters now that we know we're in a current
9432/// instantiation.
9433bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9434 TemplateParameterList *Params) {
9435 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9436 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009437
Douglas Gregor041b0842011-10-14 15:31:12 +00009438 // There is nothing to rebuild in a type parameter.
9439 if (isa<TemplateTypeParmDecl>(Param))
9440 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009441
Douglas Gregor041b0842011-10-14 15:31:12 +00009442 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009443 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009444 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9445 if (RebuildTemplateParamsInCurrentInstantiation(
9446 TTP->getTemplateParameters()))
9447 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009448
Douglas Gregor041b0842011-10-14 15:31:12 +00009449 continue;
9450 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009451
Douglas Gregor041b0842011-10-14 15:31:12 +00009452 // Rebuild the type of a non-type template parameter.
9453 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009454 TypeSourceInfo *NewTSI
9455 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9456 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009457 NTTP->getDeclName());
9458 if (!NewTSI)
9459 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009460
Douglas Gregor041b0842011-10-14 15:31:12 +00009461 if (NewTSI != NTTP->getTypeSourceInfo()) {
9462 NTTP->setTypeSourceInfo(NewTSI);
9463 NTTP->setType(NewTSI->getType());
9464 }
9465 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009466
Douglas Gregor041b0842011-10-14 15:31:12 +00009467 return false;
9468}
9469
Douglas Gregorbe999392009-09-15 16:23:51 +00009470/// \brief Produces a formatted string that describes the binding of
9471/// template parameters to template arguments.
9472std::string
9473Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9474 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009475 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00009476}
9477
9478std::string
9479Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9480 const TemplateArgument *Args,
9481 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009482 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00009483 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00009484
Douglas Gregore62e6a02009-11-11 19:13:48 +00009485 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009486 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009487
Douglas Gregorbe999392009-09-15 16:23:51 +00009488 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00009489 if (I >= NumArgs)
9490 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009491
Douglas Gregorbe999392009-09-15 16:23:51 +00009492 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009493 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00009494 else
Douglas Gregor0192c232010-12-20 16:52:59 +00009495 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009496
Douglas Gregorbe999392009-09-15 16:23:51 +00009497 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00009498 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00009499 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00009500 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00009501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009502
Douglas Gregor0192c232010-12-20 16:52:59 +00009503 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00009504 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00009505 }
Douglas Gregor0192c232010-12-20 16:52:59 +00009506
9507 Out << ']';
9508 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00009509}
Francois Pichet1c229c02011-04-22 22:18:13 +00009510
Richard Smithe40f2ba2013-08-07 21:41:30 +00009511void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9512 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00009513 if (!FD)
9514 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00009515
Justin Lebar28f09c52016-10-10 16:26:08 +00009516 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00009517
9518 // Take tokens to avoid allocations
9519 LPT->Toks.swap(Toks);
9520 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00009521 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00009522
9523 FD->setLateTemplateParsed(true);
9524}
9525
9526void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9527 if (!FD)
9528 return;
9529 FD->setLateTemplateParsed(false);
9530}
Francois Pichet1c229c02011-04-22 22:18:13 +00009531
9532bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9533 DeclContext *DC = CurContext;
9534
9535 while (DC) {
9536 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9537 const FunctionDecl *FD = RD->isLocalClass();
9538 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9539 } else if (DC->isTranslationUnit() || DC->isNamespace())
9540 return false;
9541
9542 DC = DC->getParent();
9543 }
9544 return false;
9545}
Richard Smith6739a102016-05-05 00:56:12 +00009546
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009547namespace {
Richard Smith6739a102016-05-05 00:56:12 +00009548/// \brief Walk the path from which a declaration was instantiated, and check
9549/// that every explicit specialization along that path is visible. This enforces
9550/// C++ [temp.expl.spec]/6:
9551///
9552/// If a template, a member template or a member of a class template is
9553/// explicitly specialized then that specialization shall be declared before
9554/// the first use of that specialization that would cause an implicit
9555/// instantiation to take place, in every translation unit in which such a
9556/// use occurs; no diagnostic is required.
9557///
9558/// and also C++ [temp.class.spec]/1:
9559///
9560/// A partial specialization shall be declared before the first use of a
9561/// class template specialization that would make use of the partial
9562/// specialization as the result of an implicit or explicit instantiation
9563/// in every translation unit in which such a use occurs; no diagnostic is
9564/// required.
9565class ExplicitSpecializationVisibilityChecker {
9566 Sema &S;
9567 SourceLocation Loc;
9568 llvm::SmallVector<Module *, 8> Modules;
9569
9570public:
9571 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9572 : S(S), Loc(Loc) {}
9573
9574 void check(NamedDecl *ND) {
9575 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9576 return checkImpl(FD);
9577 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9578 return checkImpl(RD);
9579 if (auto *VD = dyn_cast<VarDecl>(ND))
9580 return checkImpl(VD);
9581 if (auto *ED = dyn_cast<EnumDecl>(ND))
9582 return checkImpl(ED);
9583 }
9584
9585private:
9586 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9587 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9588 : Sema::MissingImportKind::ExplicitSpecialization;
9589 const bool Recover = true;
9590
9591 // If we got a custom set of modules (because only a subset of the
9592 // declarations are interesting), use them, otherwise let
9593 // diagnoseMissingImport intelligently pick some.
9594 if (Modules.empty())
9595 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9596 else
9597 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9598 }
9599
9600 // Check a specific declaration. There are three problematic cases:
9601 //
9602 // 1) The declaration is an explicit specialization of a template
9603 // specialization.
9604 // 2) The declaration is an explicit specialization of a member of an
9605 // templated class.
9606 // 3) The declaration is an instantiation of a template, and that template
9607 // is an explicit specialization of a member of a templated class.
9608 //
9609 // We don't need to go any deeper than that, as the instantiation of the
9610 // surrounding class / etc is not triggered by whatever triggered this
9611 // instantiation, and thus should be checked elsewhere.
9612 template<typename SpecDecl>
9613 void checkImpl(SpecDecl *Spec) {
9614 bool IsHiddenExplicitSpecialization = false;
9615 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9616 IsHiddenExplicitSpecialization =
9617 Spec->getMemberSpecializationInfo()
9618 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9619 : !S.hasVisibleDeclaration(Spec);
9620 } else {
9621 checkInstantiated(Spec);
9622 }
9623
9624 if (IsHiddenExplicitSpecialization)
9625 diagnose(Spec->getMostRecentDecl(), false);
9626 }
9627
9628 void checkInstantiated(FunctionDecl *FD) {
9629 if (auto *TD = FD->getPrimaryTemplate())
9630 checkTemplate(TD);
9631 }
9632
9633 void checkInstantiated(CXXRecordDecl *RD) {
9634 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9635 if (!SD)
9636 return;
9637
9638 auto From = SD->getSpecializedTemplateOrPartial();
9639 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9640 checkTemplate(TD);
9641 else if (auto *TD =
9642 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9643 if (!S.hasVisibleDeclaration(TD))
9644 diagnose(TD, true);
9645 checkTemplate(TD);
9646 }
9647 }
9648
9649 void checkInstantiated(VarDecl *RD) {
9650 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9651 if (!SD)
9652 return;
9653
9654 auto From = SD->getSpecializedTemplateOrPartial();
9655 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9656 checkTemplate(TD);
9657 else if (auto *TD =
9658 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9659 if (!S.hasVisibleDeclaration(TD))
9660 diagnose(TD, true);
9661 checkTemplate(TD);
9662 }
9663 }
9664
9665 void checkInstantiated(EnumDecl *FD) {}
9666
9667 template<typename TemplDecl>
9668 void checkTemplate(TemplDecl *TD) {
9669 if (TD->isMemberSpecialization()) {
9670 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9671 diagnose(TD->getMostRecentDecl(), false);
9672 }
9673 }
9674};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009675} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00009676
9677void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
9678 if (!getLangOpts().Modules)
9679 return;
9680
9681 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9682}
9683
9684/// \brief Check whether a template partial specialization that we've discovered
9685/// is hidden, and produce suitable diagnostics if so.
9686void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
9687 NamedDecl *Spec) {
9688 llvm::SmallVector<Module *, 8> Modules;
9689 if (!hasVisibleDeclaration(Spec, &Modules))
9690 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9691 MissingImportKind::PartialSpecialization,
9692 /*Recover*/true);
9693}