blob: a3dbb44ba3a5a396e077a80298db7c97269b6c20 [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 {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000049/// [temp.constr.decl]p2: A template's associated constraints are
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000050/// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000068/// Determine whether the declaration found is acceptable as the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +000069/// 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
Richard Smithcbebd622018-05-14 20:52:48 +0000108 // 'using Dependent::foo;' can resolve to a template name.
109 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
110 // injected-class-name).
111 if (isa<UnresolvedUsingValueDecl>(D))
112 return D;
113
Craig Topperc3ec1492014-05-26 06:22:03 +0000114 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000115}
116
Simon Pilgrim6905d222016-12-30 22:55:33 +0000117void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000118 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000119 // The set of class templates we've already seen.
120 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +0000121 LookupResult::Filter filter = R.makeFilter();
122 while (filter.hasNext()) {
123 NamedDecl *Orig = filter.next();
Simon Pilgrim6905d222016-12-30 22:55:33 +0000124 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000125 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +0000126 if (!Repl)
127 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000128 else if (Repl != Orig) {
129
130 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000131 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000132 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000133 // one base class). If all of the injected-class-names that are found
134 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000135 // is used as a template-name, the reference refers to the class
136 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000137 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000138 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000139 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000140 filter.erase();
141 continue;
142 }
John McCallbd8062d2010-08-13 07:02:08 +0000143
144 // FIXME: we promote access to public here as a workaround to
145 // the fact that LookupResult doesn't let us remember that we
146 // found this template through a particular injected class name,
147 // which means we end up doing nasty things to the invariants.
148 // Pretending that access is public is *much* safer.
149 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000150 }
John McCalle66edc12009-11-24 19:00:30 +0000151 }
152 filter.done();
153}
154
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000155bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
156 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000157 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000158 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000159 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +0000160
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000161 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000162}
163
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000164TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000165 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000166 bool hasTemplateKeyword,
Richard Smithc08b6932018-04-27 02:00:13 +0000167 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000168 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000169 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000170 TemplateTy &TemplateResult,
171 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000172 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000173
Douglas Gregor3cf81312009-11-03 23:16:33 +0000174 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000175 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176
Douglas Gregor3cf81312009-11-03 23:16:33 +0000177 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000178 case UnqualifiedIdKind::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000179 TName = DeclarationName(Name.Identifier);
180 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000181
Faisal Vali2ab8c152017-12-30 04:15:27 +0000182 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000183 TName = Context.DeclarationNames.getCXXOperatorName(
184 Name.OperatorFunctionId.Operator);
185 break;
186
Faisal Vali2ab8c152017-12-30 04:15:27 +0000187 case UnqualifiedIdKind::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000188 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
189 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000190
Douglas Gregor3cf81312009-11-03 23:16:33 +0000191 default:
192 return TNK_Non_template;
193 }
Mike Stump11289f42009-09-09 15:08:12 +0000194
John McCallba7bf592010-08-24 05:47:05 +0000195 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000196
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000197 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000198 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
199 MemberOfUnknownSpecialization))
200 return TNK_Non_template;
John McCallfb3f9ba2010-08-28 20:17:00 +0000201 if (R.empty()) return TNK_Non_template;
202 if (R.isAmbiguous()) {
203 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000204 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000205
206 // FIXME: we might have ambiguous templates, in which case we
207 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000208 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000209 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000210
John McCalld28ae272009-12-02 08:04:21 +0000211 TemplateName Template;
212 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000213
John McCalld28ae272009-12-02 08:04:21 +0000214 unsigned ResultCount = R.end() - R.begin();
215 if (ResultCount > 1) {
216 // We assume that we'll preserve the qualifier from a function
217 // template name in other ways.
218 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
219 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000220
221 // We'll do this lookup again later.
222 R.suppressDiagnostics();
Richard Smithcbebd622018-05-14 20:52:48 +0000223 } else if (isa<UnresolvedUsingValueDecl>((*R.begin())->getUnderlyingDecl())) {
224 // We don't yet know whether this is a template-name or not.
225 MemberOfUnknownSpecialization = true;
226 return TNK_Non_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000227 } else {
John McCalld28ae272009-12-02 08:04:21 +0000228 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
229
230 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000231 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000232 Template = Context.getQualifiedTemplateName(Qualifier,
233 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000234 } else {
235 Template = TemplateName(TD);
236 }
237
John McCalldcc71402010-08-13 02:23:42 +0000238 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000239 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000240
241 // We'll do this lookup again later.
242 R.suppressDiagnostics();
243 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000244 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000245 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
Faisal Valia534f072018-04-26 00:42:40 +0000246 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000247 TemplateKind =
Faisal Valia534f072018-04-26 00:42:40 +0000248 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000249 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000250 }
Mike Stump11289f42009-09-09 15:08:12 +0000251
John McCalld28ae272009-12-02 08:04:21 +0000252 TemplateResult = TemplateTy::make(Template);
253 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000254}
255
Richard Smith278890f2017-02-10 20:39:58 +0000256bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
257 SourceLocation NameLoc,
258 ParsedTemplateTy *Template) {
259 CXXScopeSpec SS;
260 bool MemberOfUnknownSpecialization = false;
261
262 // We could use redeclaration lookup here, but we don't need to: the
263 // syntactic form of a deduction guide is enough to identify it even
264 // if we can't look up the template name at all.
265 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000266 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
267 /*EnteringContext*/ false,
268 MemberOfUnknownSpecialization))
269 return false;
Richard Smith278890f2017-02-10 20:39:58 +0000270
271 if (R.empty()) return false;
272 if (R.isAmbiguous()) {
273 // FIXME: Diagnose an ambiguity if we find at least one template.
274 R.suppressDiagnostics();
275 return false;
276 }
277
278 // We only treat template-names that name type templates as valid deduction
279 // guide names.
280 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
281 if (!TD || !getAsTypeTemplateDecl(TD))
282 return false;
283
284 if (Template)
285 *Template = TemplateTy::make(TemplateName(TD));
286 return true;
287}
288
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000289bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000290 SourceLocation IILoc,
291 Scope *S,
292 const CXXScopeSpec *SS,
293 TemplateTy &SuggestedTemplate,
294 TemplateNameKind &SuggestedKind) {
295 // We can't recover unless there's a dependent scope specifier preceding the
296 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000297 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000298 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
299 computeDeclContext(*SS))
300 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000301
Douglas Gregor18473f32010-01-12 21:28:44 +0000302 // The code is missing a 'template' keyword prior to the dependent template
303 // name.
304 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
305 Diag(IILoc, diag::err_template_kw_missing)
306 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000307 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000308 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000309 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
310 SuggestedKind = TNK_Dependent_template_name;
311 return true;
312}
313
Richard Smith79810042018-05-11 02:43:08 +0000314bool Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000315 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000316 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000317 bool EnteringContext,
Richard Smith79810042018-05-11 02:43:08 +0000318 bool &MemberOfUnknownSpecialization,
319 SourceLocation TemplateKWLoc) {
John McCalle66edc12009-11-24 19:00:30 +0000320 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000321 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000322 DeclContext *LookupCtx = nullptr;
Richard Smith79810042018-05-11 02:43:08 +0000323 bool IsDependent = false;
John McCalle66edc12009-11-24 19:00:30 +0000324 if (!ObjectType.isNull()) {
325 // This nested-name-specifier occurs in a member access expression, e.g.,
326 // x->B::f, and we are looking into the type of the object.
327 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
328 LookupCtx = computeDeclContext(ObjectType);
Richard Smith79810042018-05-11 02:43:08 +0000329 IsDependent = !LookupCtx;
330 assert((IsDependent || !ObjectType->isIncompleteType() ||
Richard Smith5ed79562013-06-07 20:03:01 +0000331 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000332 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000333
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000334 // Template names cannot appear inside an Objective-C class or object type.
335 if (ObjectType->isObjCObjectOrInterfaceType()) {
336 Found.clear();
Richard Smith79810042018-05-11 02:43:08 +0000337 return false;
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000338 }
John McCalle66edc12009-11-24 19:00:30 +0000339 } else if (SS.isSet()) {
340 // This nested-name-specifier occurs after another nested-name-specifier,
341 // so long into the context associated with the prior nested-name-specifier.
342 LookupCtx = computeDeclContext(SS, EnteringContext);
Richard Smith79810042018-05-11 02:43:08 +0000343 IsDependent = !LookupCtx;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344
John McCalle66edc12009-11-24 19:00:30 +0000345 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000346 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
Richard Smith79810042018-05-11 02:43:08 +0000347 return true;
John McCalle66edc12009-11-24 19:00:30 +0000348 }
349
350 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000351 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000352 if (LookupCtx) {
353 // Perform "qualified" name lookup into the declaration context we
354 // computed, which is either the type of the base of a member access
355 // expression or the declaration context associated with a prior
356 // nested-name-specifier.
357 LookupQualifiedName(Found, LookupCtx);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000358
Richard Smith79810042018-05-11 02:43:08 +0000359 // FIXME: The C++ standard does not clearly specify what happens in the
360 // case where the object type is dependent, and implementations vary. In
361 // Clang, we treat a name after a . or -> as a template-name if lookup
362 // finds a non-dependent member or member of the current instantiation that
363 // is a type template, or finds no such members and lookup in the context
364 // of the postfix-expression finds a type template. In the latter case, the
365 // name is nonetheless dependent, and we may resolve it to a member of an
366 // unknown specialization when we come to instantiate the template.
367 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
John McCalle66edc12009-11-24 19:00:30 +0000368 }
369
Richard Smith79810042018-05-11 02:43:08 +0000370 if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
371 // C++ [basic.lookup.classref]p1:
372 // In a class member access expression (5.2.5), if the . or -> token is
373 // immediately followed by an identifier followed by a <, the
374 // identifier must be looked up to determine whether the < is the
375 // beginning of a template argument list (14.2) or a less-than operator.
376 // The identifier is first looked up in the class of the object
377 // expression. If the identifier is not found, it is then looked up in
378 // the context of the entire postfix-expression and shall name a class
379 // template.
380 if (S)
381 LookupName(Found, S);
382
383 if (!ObjectType.isNull()) {
384 // FIXME: We should filter out all non-type templates here, particularly
385 // variable templates and concepts. But the exclusion of alias templates
386 // and template template parameters is a wording defect.
387 AllowFunctionTemplatesInLookup = false;
388 ObjectTypeSearchedInScope = true;
389 }
390
391 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
392 }
393
394 if (Found.empty() && !IsDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000395 // If we did not find any names, attempt to correct any typos.
396 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000397 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000398 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000399 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
400 FilterCCC->WantTypeSpecifiers = false;
401 FilterCCC->WantExpressionKeywords = false;
402 FilterCCC->WantRemainingKeywords = false;
403 FilterCCC->WantCXXNamedCasts = true;
404 if (TypoCorrection Corrected = CorrectTypo(
405 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
406 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000407 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000408 if (auto *ND = Corrected.getFoundDecl())
409 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000410 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000411 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000412 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000413 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
414 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000415 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000416 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
417 << Name << LookupCtx << DroppedSpecifier
418 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000419 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000420 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000421 }
John McCalle9cccd82010-06-16 08:42:20 +0000422 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000423 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000424 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000425 }
426 }
427
Richard Smith79810042018-05-11 02:43:08 +0000428 NamedDecl *ExampleLookupResult =
429 Found.empty() ? nullptr : Found.getRepresentativeDecl();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000430 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000431 if (Found.empty()) {
Richard Smith79810042018-05-11 02:43:08 +0000432 if (IsDependent) {
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000433 MemberOfUnknownSpecialization = true;
Richard Smith79810042018-05-11 02:43:08 +0000434 return false;
435 }
436
437 // If a 'template' keyword was used, a lookup that finds only non-template
438 // names is an error.
439 if (ExampleLookupResult && TemplateKWLoc.isValid()) {
440 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
441 << Found.getLookupName() << SS.getRange();
Richard Smithcbebd622018-05-14 20:52:48 +0000442 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
Richard Smith79810042018-05-11 02:43:08 +0000443 diag::note_template_kw_refers_to_non_template)
444 << Found.getLookupName();
445 return true;
446 }
447
448 return false;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000449 }
John McCalle66edc12009-11-24 19:00:30 +0000450
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000451 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000452 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000453 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000454 // [...] If the lookup in the class of the object expression finds a
455 // template, the name is also looked up in the context of the entire
456 // postfix-expression and [...]
457 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000458 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000459 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
460 LookupOrdinaryName);
461 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000462 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000463
John McCalle66edc12009-11-24 19:00:30 +0000464 if (FoundOuter.empty()) {
465 // - if the name is not found, the name found in the class of the
466 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000467 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
468 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000469 // - if the name is found in the context of the entire
470 // postfix-expression and does not name a class template, the name
471 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000472 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000473 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000474 // - if the name found is a class template, it must refer to the same
475 // entity as the one found in the class of the object expression,
476 // otherwise the program is ill-formed.
477 if (!Found.isSingleResult() ||
478 Found.getFoundDecl()->getCanonicalDecl()
479 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000480 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000481 diag::ext_nested_name_member_ref_lookup_ambiguous)
482 << Found.getLookupName()
483 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000484 Diag(Found.getRepresentativeDecl()->getLocation(),
485 diag::note_ambig_member_ref_object_type)
486 << ObjectType;
487 Diag(FoundOuter.getFoundDecl()->getLocation(),
488 diag::note_ambig_member_ref_scope);
489
490 // Recover by taking the template that we found in the object
491 // expression's type.
492 }
493 }
494 }
Richard Smith79810042018-05-11 02:43:08 +0000495
496 return false;
John McCalle66edc12009-11-24 19:00:30 +0000497}
498
Richard Smith42bc73a2017-05-10 02:30:28 +0000499void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
500 SourceLocation Less,
501 SourceLocation Greater) {
502 if (TemplateName.isInvalid())
503 return;
504
505 DeclarationNameInfo NameInfo;
506 CXXScopeSpec SS;
507 LookupNameKind LookupKind;
508
509 DeclContext *LookupCtx = nullptr;
510 NamedDecl *Found = nullptr;
Richard Smithbf5bcf22018-06-26 23:20:26 +0000511 bool MissingTemplateKeyword = false;
Richard Smith42bc73a2017-05-10 02:30:28 +0000512
513 // Figure out what name we looked up.
Richard Smithbf5bcf22018-06-26 23:20:26 +0000514 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
515 NameInfo = DRE->getNameInfo();
516 SS.Adopt(DRE->getQualifierLoc());
517 LookupKind = LookupOrdinaryName;
518 Found = DRE->getFoundDecl();
519 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000520 NameInfo = ME->getMemberNameInfo();
521 SS.Adopt(ME->getQualifierLoc());
522 LookupKind = LookupMemberName;
523 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
524 Found = ME->getMemberDecl();
Richard Smithbf5bcf22018-06-26 23:20:26 +0000525 } else if (auto *DSDRE =
526 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
527 NameInfo = DSDRE->getNameInfo();
528 SS.Adopt(DSDRE->getQualifierLoc());
529 MissingTemplateKeyword = true;
530 } else if (auto *DSME =
531 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
532 NameInfo = DSME->getMemberNameInfo();
533 SS.Adopt(DSME->getQualifierLoc());
534 MissingTemplateKeyword = true;
Richard Smith42bc73a2017-05-10 02:30:28 +0000535 } else {
Richard Smithbf5bcf22018-06-26 23:20:26 +0000536 llvm_unreachable("unexpected kind of potential template name");
537 }
538
539 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
540 // was missing.
541 if (MissingTemplateKeyword) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000542 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
543 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
Richard Smithbf5bcf22018-06-26 23:20:26 +0000544 return;
Richard Smith42bc73a2017-05-10 02:30:28 +0000545 }
546
547 // Try to correct the name by looking for templates and C++ named casts.
548 struct TemplateCandidateFilter : CorrectionCandidateCallback {
549 TemplateCandidateFilter() {
550 WantTypeSpecifiers = false;
551 WantExpressionKeywords = false;
552 WantRemainingKeywords = false;
553 WantCXXNamedCasts = true;
554 };
555 bool ValidateCandidate(const TypoCorrection &Candidate) override {
556 if (auto *ND = Candidate.getCorrectionDecl())
557 return isAcceptableTemplateName(ND->getASTContext(), ND, true);
558 return Candidate.isKeyword();
559 }
560 };
561
562 DeclarationName Name = NameInfo.getName();
563 if (TypoCorrection Corrected =
564 CorrectTypo(NameInfo, LookupKind, S, &SS,
565 llvm::make_unique<TemplateCandidateFilter>(),
566 CTK_ErrorRecovery, LookupCtx)) {
567 auto *ND = Corrected.getFoundDecl();
568 if (ND)
569 ND = isAcceptableTemplateName(Context, ND,
570 /*AllowFunctionTemplates*/ true);
571 if (ND || Corrected.isKeyword()) {
572 if (LookupCtx) {
573 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
574 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
575 Name.getAsString() == CorrectedStr;
576 diagnoseTypo(Corrected,
577 PDiag(diag::err_non_template_in_member_template_id_suggest)
578 << Name << LookupCtx << DroppedSpecifier
Richard Smith52f8d192017-05-10 21:32:16 +0000579 << SS.getRange(), false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000580 } else {
581 diagnoseTypo(Corrected,
582 PDiag(diag::err_non_template_in_template_id_suggest)
Richard Smith52f8d192017-05-10 21:32:16 +0000583 << Name, false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000584 }
585 if (Found)
586 Diag(Found->getLocation(),
587 diag::note_non_template_in_template_id_found);
588 return;
589 }
590 }
591
592 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
593 << Name << SourceRange(Less, Greater);
594 if (Found)
595 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
596}
597
John McCallcd4b4772009-12-02 03:53:29 +0000598/// ActOnDependentIdExpression - Handle a dependent id-expression that
599/// was just parsed. This is only possible with an explicit scope
600/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000601ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000602Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000603 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000604 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000605 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000606 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000607 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Reid Kleckner1af391df2016-03-11 18:59:12 +0000609 // C++11 [expr.prim.general]p12:
610 // An id-expression that denotes a non-static data member or non-static
611 // member function of a class can only be used:
612 // (...)
613 // - if that id-expression denotes a non-static data member and it
614 // appears in an unevaluated operand.
615 //
616 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
617 // CXXDependentScopeMemberExpr. The former can instantiate to either
618 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
619 // always a MemberExpr.
620 bool MightBeCxx11UnevalField =
621 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
622
Akira Hatanakad644e022016-12-16 03:19:41 +0000623 // Check if the nested name specifier is an enum type.
624 bool IsEnum = false;
625 if (NestedNameSpecifier *NNS = SS.getScopeRep())
626 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
627
628 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000629 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000630 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631
John McCalle66edc12009-11-24 19:00:30 +0000632 // Since the 'this' expression is synthesized, we don't need to
633 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000634 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000635
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000636 return CXXDependentScopeMemberExpr::Create(
637 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
638 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
639 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000640 }
641
Abramo Bagnara7945c982012-01-27 09:46:47 +0000642 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000643}
644
John McCalldadc5752010-08-24 06:29:42 +0000645ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000646Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000647 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000648 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000649 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000650 return DependentScopeDeclRefExpr::Create(
651 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
652 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000653}
654
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000655
656/// Determine whether we would be unable to instantiate this template (because
657/// it either has no definition, or is in the process of being instantiated).
658bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
659 NamedDecl *Instantiation,
660 bool InstantiatedFromMember,
661 const NamedDecl *Pattern,
662 const NamedDecl *PatternDef,
663 TemplateSpecializationKind TSK,
664 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000665 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
666 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000667
Richard Smithedbc6e92016-10-14 21:41:24 +0000668 bool IsEntityBeingDefined = false;
669 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
670 IsEntityBeingDefined = TD->isBeingDefined();
671
672 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000673 NamedDecl *SuggestedDef = nullptr;
674 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
675 /*OnlyNeedComplete*/false)) {
676 // If we're allowed to diagnose this and recover, do so.
677 bool Recover = Complain && !isSFINAEContext();
678 if (Complain)
679 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
680 Sema::MissingImportKind::Definition, Recover);
681 return !Recover;
682 }
683 return false;
684 }
685
Richard Smith6f4e2e02016-08-23 19:41:39 +0000686 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
687 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000688
Richard Smithedbc6e92016-10-14 21:41:24 +0000689 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000690 QualType InstantiationTy;
691 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
692 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000693 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000694 Diag(PointOfInstantiation,
695 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000696 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000697 << InstantiationTy;
698 // Not much point in noting the template declaration here, since
699 // we're lexically inside it.
700 Instantiation->setInvalidDecl();
701 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000702 if (isa<FunctionDecl>(Instantiation)) {
703 Diag(PointOfInstantiation,
704 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000705 << /*member function*/ 1 << Instantiation->getDeclName()
706 << Instantiation->getDeclContext();
707 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000708 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000709 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000710 Diag(PointOfInstantiation,
711 diag::err_implicit_instantiate_member_undefined)
712 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000713 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000714 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000715 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000716 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000717 Diag(PointOfInstantiation,
718 diag::err_explicit_instantiation_undefined_func_template)
719 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000720 Note = diag::note_explicit_instantiation_here;
721 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000722 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
723 << (TSK != TSK_ImplicitInstantiation)
724 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000725 Note = diag::note_template_decl_here;
726 } else {
727 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
728 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
729 Diag(PointOfInstantiation,
730 diag::err_explicit_instantiation_undefined_var_template)
731 << Instantiation;
732 Instantiation->setInvalidDecl();
733 } else
734 Diag(PointOfInstantiation,
735 diag::err_explicit_instantiation_undefined_member)
736 << /*static data member*/ 2 << Instantiation->getDeclName()
737 << Instantiation->getDeclContext();
738 Note = diag::note_explicit_instantiation_here;
739 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000740 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000741 if (Note) // Diagnostics were emitted.
742 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000743
744 // In general, Instantiation isn't marked invalid to get more than one
745 // error for multiple undefined instantiations. But the code that does
746 // explicit declaration -> explicit definition conversion can't handle
747 // invalid declarations, so mark as invalid in that case.
748 if (TSK == TSK_ExplicitInstantiationDeclaration)
749 Instantiation->setInvalidDecl();
750 return true;
751}
752
Douglas Gregor5101c242008-12-05 18:15:24 +0000753/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
754/// that the template parameter 'PrevDecl' is being shadowed by a new
755/// declaration at location Loc. Returns true to indicate that this is
756/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000757void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000758 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000759
760 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000761 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000762 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000763
764 // C++ [temp.local]p4:
765 // A template-parameter shall not be redeclared within its
766 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000767 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000768 << cast<NamedDecl>(PrevDecl)->getDeclName();
769 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000770}
771
Douglas Gregor463421d2009-03-03 04:44:36 +0000772/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000773/// the parameter D to reference the templated declaration and return a pointer
774/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000775TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
776 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
777 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000778 return Temp;
779 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000780 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000781}
782
Douglas Gregoreb29d182011-01-05 17:40:24 +0000783ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
784 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000785 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000786 "Only template template arguments can be pack expansions here");
787 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
788 "Template template argument pack expansion without packs");
789 ParsedTemplateArgument Result(*this);
790 Result.EllipsisLoc = EllipsisLoc;
791 return Result;
792}
793
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000794static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
795 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000796
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000797 switch (Arg.getKind()) {
798 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000799 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000800 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000802 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000803 return TemplateArgumentLoc(TemplateArgument(T), DI);
804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000805
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000806 case ParsedTemplateArgument::NonType: {
807 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
808 return TemplateArgumentLoc(TemplateArgument(E), E);
809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000811 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000812 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000813 TemplateArgument TArg;
814 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000815 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000816 else
817 TArg = Template;
818 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000819 Arg.getScopeSpec().getWithLocInContext(
820 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000821 Arg.getLocation(),
822 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000823 }
824 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000825
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000826 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000827}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000828
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000829/// Translates template arguments as provided by the parser
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000830/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000831void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
832 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000833 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000834 TemplateArgs.addArgument(translateTemplateArgument(*this,
835 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000836}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000837
Richard Smithb80d5402013-06-25 22:21:36 +0000838static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
839 SourceLocation Loc,
840 IdentifierInfo *Name) {
841 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
Richard Smithbecb92d2017-10-10 22:33:17 +0000842 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
Richard Smithb80d5402013-06-25 22:21:36 +0000843 if (PrevDecl && PrevDecl->isTemplateParameter())
844 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
845}
846
Richard Smith77a9c602018-02-28 03:02:23 +0000847/// Convert a parsed type into a parsed template argument. This is mostly
848/// trivial, except that we may have parsed a C++17 deduced class template
849/// specialization type, in which case we should form a template template
850/// argument instead of a type template argument.
851ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
852 TypeSourceInfo *TInfo;
853 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
854 if (T.isNull())
855 return ParsedTemplateArgument();
856 assert(TInfo && "template argument with no location");
857
858 // If we might have formed a deduced template specialization type, convert
859 // it to a template template argument.
860 if (getLangOpts().CPlusPlus17) {
861 TypeLoc TL = TInfo->getTypeLoc();
862 SourceLocation EllipsisLoc;
863 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
864 EllipsisLoc = PET.getEllipsisLoc();
865 TL = PET.getPatternLoc();
866 }
867
868 CXXScopeSpec SS;
869 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
870 SS.Adopt(ET.getQualifierLoc());
871 TL = ET.getNamedTypeLoc();
872 }
873
874 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
875 TemplateName Name = DTST.getTypePtr()->getTemplateName();
876 if (SS.isSet())
877 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
878 /*HasTemplateKeyword*/ false,
879 Name.getAsTemplateDecl());
880 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
881 DTST.getTemplateNameLoc());
882 if (EllipsisLoc.isValid())
883 Result = Result.getTemplatePackExpansion(EllipsisLoc);
884 return Result;
885 }
886 }
887
888 // This is a normal type template argument. Note, if the type template
889 // argument is an injected-class-name for a template, it has a dual nature
Fangrui Song6907ce22018-07-30 19:24:48 +0000890 // and can be used as either a type or a template. We handle that in
Richard Smith77a9c602018-02-28 03:02:23 +0000891 // convertTypeTemplateArgumentToTemplate.
892 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
893 ParsedType.get().getAsOpaquePtr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000894 TInfo->getTypeLoc().getBeginLoc());
Richard Smith77a9c602018-02-28 03:02:23 +0000895}
896
Douglas Gregor5101c242008-12-05 18:15:24 +0000897/// ActOnTypeParameter - Called when a C++ template type parameter
898/// (e.g., "typename T") has been parsed. Typename specifies whether
899/// the keyword "typename" was used to declare the type parameter
900/// (otherwise, "class" was used), and KeyLoc is the location of the
901/// "class" or "typename" keyword. ParamName is the name of the
902/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000903/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000904/// If the type parameter has a default argument, it will be added
905/// later via ActOnTypeParameterDefault.
Faisal Valibe294032017-12-23 18:56:34 +0000906NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000907 SourceLocation EllipsisLoc,
908 SourceLocation KeyLoc,
909 IdentifierInfo *ParamName,
910 SourceLocation ParamNameLoc,
911 unsigned Depth, unsigned Position,
912 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000913 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000914 assert(S->isTemplateParamScope() &&
915 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000916
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000917 SourceLocation Loc = ParamNameLoc;
918 if (!ParamName)
919 Loc = KeyLoc;
920
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000921 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000922 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000923 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000924 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000925 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000926 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000927
928 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000929 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
930
Douglas Gregor5101c242008-12-05 18:15:24 +0000931 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000932 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000933 IdResolver.AddDecl(Param);
934 }
935
Douglas Gregorf5500772011-01-05 15:48:55 +0000936 // C++0x [temp.param]p9:
937 // A default template-argument may be specified for any kind of
938 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000939 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000940 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000941 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000942 }
943
Douglas Gregordc13ded2010-07-01 00:00:45 +0000944 // Handle the default argument, if provided.
945 if (DefaultArg) {
946 TypeSourceInfo *DefaultTInfo;
947 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000948
Douglas Gregordc13ded2010-07-01 00:00:45 +0000949 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000950
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000951 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000952 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000953 UPPC_DefaultArgument))
954 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000955
Douglas Gregordc13ded2010-07-01 00:00:45 +0000956 // Check the template argument itself.
957 if (CheckTemplateArgument(Param, DefaultTInfo)) {
958 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000959 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000960 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000961
Richard Smith1469b912015-06-10 00:29:03 +0000962 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000963 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000964
John McCall48871652010-08-21 09:40:31 +0000965 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000966}
967
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000968/// Check that the type of a non-type template parameter is
Douglas Gregor463421d2009-03-03 04:44:36 +0000969/// well-formed.
970///
971/// \returns the (possibly-promoted) parameter type if valid;
972/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000973QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
974 SourceLocation Loc) {
975 if (TSI->getType()->isUndeducedType()) {
Erik Pilkington9f9462a2018-08-07 22:59:02 +0000976 // C++17 [temp.dep.expr]p3:
Richard Smith15361a22016-12-28 06:27:18 +0000977 // An id-expression is type-dependent if it contains
978 // - an identifier associated by name lookup with a non-type
979 // template-parameter declared with a type that contains a
980 // placeholder type (7.1.7.4),
981 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
982 }
983
984 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
985}
986
987QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
988 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000989 // We don't allow variably-modified types as the type of non-type template
990 // parameters.
991 if (T->isVariablyModifiedType()) {
992 Diag(Loc, diag::err_variably_modified_nontype_template_param)
993 << T;
994 return QualType();
995 }
996
Douglas Gregor463421d2009-03-03 04:44:36 +0000997 // C++ [temp.param]p4:
998 //
999 // A non-type template-parameter shall have one of the following
1000 // (optionally cv-qualified) types:
1001 //
1002 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +00001003 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001004 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +00001005 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001006 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +00001007 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001008 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +00001009 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001010 // -- std::nullptr_t.
1011 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +00001012 // If T is a dependent type, we can't do the check now, so we
1013 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +00001014 T->isDependentType() ||
1015 // Allow use of auto in template parameter declarations.
1016 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +00001017 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1018 // are ignored when determining its type.
1019 return T.getUnqualifiedType();
1020 }
1021
Douglas Gregor463421d2009-03-03 04:44:36 +00001022 // C++ [temp.param]p8:
1023 //
1024 // A non-type template-parameter of type "array of T" or
1025 // "function returning T" is adjusted to be of type "pointer to
1026 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +00001027 else if (T->isArrayType() || T->isFunctionType())
1028 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001029
Douglas Gregor463421d2009-03-03 04:44:36 +00001030 Diag(Loc, diag::err_template_nontype_parm_bad_type)
1031 << T;
1032
1033 return QualType();
1034}
1035
Faisal Valibe294032017-12-23 18:56:34 +00001036NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
John McCall48871652010-08-21 09:40:31 +00001037 unsigned Depth,
1038 unsigned Position,
1039 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +00001040 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +00001041 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +00001042
Faisal Valia223d1c2017-12-22 03:50:55 +00001043 // Check that we have valid decl-specifiers specified.
1044 auto CheckValidDeclSpecifiers = [this, &D] {
1045 // C++ [temp.param]
Fangrui Song6907ce22018-07-30 19:24:48 +00001046 // p1
Malcolm Parsonsfab36802018-04-16 08:31:08 +00001047 // template-parameter:
1048 // ...
1049 // parameter-declaration
Fangrui Song6907ce22018-07-30 19:24:48 +00001050 // p2
Faisal Valia223d1c2017-12-22 03:50:55 +00001051 // ... A storage class shall not be specified in a template-parameter
1052 // declaration.
Fangrui Song6907ce22018-07-30 19:24:48 +00001053 // [dcl.typedef]p1:
Faisal Valia223d1c2017-12-22 03:50:55 +00001054 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1055 // of a parameter-declaration
1056 const DeclSpec &DS = D.getDeclSpec();
1057 auto EmitDiag = [this](SourceLocation Loc) {
1058 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1059 << FixItHint::CreateRemoval(Loc);
1060 };
1061 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1062 EmitDiag(DS.getStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001063
Sam McCall1371cba2017-12-22 07:09:51 +00001064 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
Faisal Valia223d1c2017-12-22 03:50:55 +00001065 EmitDiag(DS.getThreadStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001066
1067 // [dcl.inline]p1:
1068 // The inline specifier can be applied only to the declaration or
Faisal Valia223d1c2017-12-22 03:50:55 +00001069 // definition of a variable or function.
Fangrui Song6907ce22018-07-30 19:24:48 +00001070
Faisal Valia223d1c2017-12-22 03:50:55 +00001071 if (DS.isInlineSpecified())
1072 EmitDiag(DS.getInlineSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001073
Faisal Valia223d1c2017-12-22 03:50:55 +00001074 // [dcl.constexpr]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00001075 // The constexpr specifier shall be applied only to the definition of a
1076 // variable or variable template or the declaration of a function or
Faisal Valia223d1c2017-12-22 03:50:55 +00001077 // function template.
Fangrui Song6907ce22018-07-30 19:24:48 +00001078
Faisal Valia223d1c2017-12-22 03:50:55 +00001079 if (DS.isConstexprSpecified())
1080 EmitDiag(DS.getConstexprSpecLoc());
1081
1082 // [dcl.fct.spec]p1:
1083 // Function-specifiers can be used only in function declarations.
1084
1085 if (DS.isVirtualSpecified())
1086 EmitDiag(DS.getVirtualSpecLoc());
1087
1088 if (DS.isExplicitSpecified())
1089 EmitDiag(DS.getExplicitSpecLoc());
1090
1091 if (DS.isNoreturnSpecified())
1092 EmitDiag(DS.getNoreturnSpecLoc());
1093 };
1094
1095 CheckValidDeclSpecifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00001096
Richard Smith15361a22016-12-28 06:27:18 +00001097 if (TInfo->getType()->isUndeducedType()) {
1098 Diag(D.getIdentifierLoc(),
1099 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1100 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1101 }
Douglas Gregor5101c242008-12-05 18:15:24 +00001102
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001103 assert(S->isTemplateParamScope() &&
1104 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +00001105 bool Invalid = false;
1106
Richard Smith15361a22016-12-28 06:27:18 +00001107 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001108 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001109 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +00001110 Invalid = true;
1111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001112
Richard Smithb80d5402013-06-25 22:21:36 +00001113 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001114 bool IsParameterPack = D.hasEllipsis();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001115 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1116 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1117 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1118 TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001119 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +00001120
Douglas Gregor5101c242008-12-05 18:15:24 +00001121 if (Invalid)
1122 Param->setInvalidDecl();
1123
Richard Smithb80d5402013-06-25 22:21:36 +00001124 if (ParamName) {
1125 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1126 ParamName);
1127
Douglas Gregor5101c242008-12-05 18:15:24 +00001128 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +00001129 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +00001130 IdResolver.AddDecl(Param);
1131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001132
Douglas Gregorf5500772011-01-05 15:48:55 +00001133 // C++0x [temp.param]p9:
1134 // A default template-argument may be specified for any kind of
1135 // template-parameter that is not a template parameter pack.
1136 if (Default && IsParameterPack) {
1137 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +00001138 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +00001139 }
1140
Douglas Gregordc13ded2010-07-01 00:00:45 +00001141 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001142 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001143 // Check for unexpanded parameter packs.
1144 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1145 return Param;
1146
Douglas Gregordc13ded2010-07-01 00:00:45 +00001147 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +00001148 ExprResult DefaultRes =
1149 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +00001150 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +00001151 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00001152 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001153 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001154 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001155
Richard Smith1469b912015-06-10 00:29:03 +00001156 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +00001157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001158
John McCall48871652010-08-21 09:40:31 +00001159 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +00001160}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001161
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001162/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +00001163/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001164/// has been parsed. S is the current scope.
Faisal Valibe294032017-12-23 18:56:34 +00001165NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
John McCall48871652010-08-21 09:40:31 +00001166 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00001167 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +00001168 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +00001169 IdentifierInfo *Name,
1170 SourceLocation NameLoc,
1171 unsigned Depth,
1172 unsigned Position,
1173 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +00001174 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001175 assert(S->isTemplateParamScope() &&
1176 "Template template parameter not in template parameter scope!");
1177
1178 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +00001179 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001180 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +00001181 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001182 NameLoc.isInvalid()? TmpLoc : NameLoc,
1183 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +00001184 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001185 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001186
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001187 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +00001188 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001189 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +00001190 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1191
John McCall48871652010-08-21 09:40:31 +00001192 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001193 IdResolver.AddDecl(Param);
1194 }
1195
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001196 if (Params->size() == 0) {
1197 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1198 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1199 Param->setInvalidDecl();
1200 }
1201
Douglas Gregorf5500772011-01-05 15:48:55 +00001202 // C++0x [temp.param]p9:
1203 // A default template-argument may be specified for any kind of
1204 // template-parameter that is not a template parameter pack.
1205 if (IsParameterPack && !Default.isInvalid()) {
1206 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1207 Default = ParsedTemplateArgument();
1208 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001209
Douglas Gregordc13ded2010-07-01 00:00:45 +00001210 if (!Default.isInvalid()) {
1211 // Check only that we have a template template argument. We don't want to
1212 // try to check well-formedness now, because our template template parameter
1213 // might have dependent types in its template parameters, which we wouldn't
1214 // be able to match now.
1215 //
1216 // If none of the template template parameter's template arguments mention
1217 // other template parameters, we could actually perform more checking here.
1218 // However, it isn't worth doing.
1219 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1220 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +00001221 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +00001222 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00001223 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001224 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001225
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001226 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001227 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001228 DefaultArg.getArgument().getAsTemplate(),
1229 UPPC_DefaultArgument))
1230 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001231
Richard Smith1469b912015-06-10 00:29:03 +00001232 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +00001233 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001234
John McCall48871652010-08-21 09:40:31 +00001235 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +00001236}
1237
Hubert Tongf608c052016-04-29 18:05:37 +00001238/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1239/// constrained by RequiresClause, that contains the template parameters in
1240/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +00001241TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001242Sema::ActOnTemplateParameterList(unsigned Depth,
1243 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001244 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001245 SourceLocation LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001246 ArrayRef<NamedDecl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001247 SourceLocation RAngleLoc,
1248 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001249 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001250 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001251
David Majnemer902f8c62015-12-27 07:16:27 +00001252 return TemplateParameterList::Create(
1253 Context, TemplateLoc, LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001254 llvm::makeArrayRef(Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001255 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001256}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001257
John McCall3e11ebe2010-03-15 10:12:16 +00001258static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1259 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +00001260 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00001261}
1262
Erich Keanec480f302018-07-12 21:09:05 +00001263DeclResult Sema::CheckClassTemplate(
1264 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1265 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1266 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1267 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1268 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1269 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001270 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001271 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001272 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001273 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001274
1275 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001276 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001277 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001278
Abramo Bagnara6150c882010-05-11 21:36:43 +00001279 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1280 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001281
1282 // There is no such thing as an unnamed class template.
1283 if (!Name) {
1284 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001285 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001286 }
1287
Richard Smith6483d222012-04-21 01:27:54 +00001288 // Find any previous declaration with this name. For a friend with no
1289 // scope explicitly specified, we only look for tag declarations (per
1290 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001291 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001292 LookupResult Previous(*this, Name, NameLoc,
1293 (SS.isEmpty() && TUK == TUK_Friend)
1294 ? LookupTagName : LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001295 forRedeclarationInCurContext());
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001296 if (SS.isNotEmpty() && !SS.isInvalid()) {
1297 SemanticContext = computeDeclContext(SS, true);
1298 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001299 // FIXME: Horrible, horrible hack! We can't currently represent this
1300 // in the AST, and historically we have just ignored such friend
1301 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001302 Diag(NameLoc, TUK == TUK_Friend
1303 ? diag::warn_template_qualified_friend_ignored
1304 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001305 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001306 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001307 }
Mike Stump11289f42009-09-09 15:08:12 +00001308
John McCall0b66eb32010-05-01 00:40:08 +00001309 if (RequireCompleteDeclContext(SS, SemanticContext))
1310 return true;
1311
Simon Pilgrim6905d222016-12-30 22:55:33 +00001312 // If we're adding a template to a dependent context, we may need to
1313 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001314 // now that we know what the current instantiation is.
1315 if (SemanticContext->isDependentContext()) {
1316 ContextRAII SavedContext(*this, SemanticContext);
1317 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1318 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001319 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
Richard Smithc660c8f2018-03-16 13:36:56 +00001320 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
Richard Smith6483d222012-04-21 01:27:54 +00001321
John McCall27b18f82009-11-17 02:14:36 +00001322 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001323 } else {
1324 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001325
1326 // C++14 [class.mem]p14:
1327 // If T is the name of a class, then each of the following shall have a
1328 // name different from T:
1329 // -- every member template of class T
1330 if (TUK != TUK_Friend &&
1331 DiagnoseClassNameShadow(SemanticContext,
1332 DeclarationNameInfo(Name, NameLoc)))
1333 return true;
1334
John McCall27b18f82009-11-17 02:14:36 +00001335 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001336 }
Mike Stump11289f42009-09-09 15:08:12 +00001337
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001338 if (Previous.isAmbiguous())
1339 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001340
Craig Topperc3ec1492014-05-26 06:22:03 +00001341 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001342 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001343 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001344
Serge Pavlove50bf752016-06-10 04:39:07 +00001345 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1346 // Maybe we will complain about the shadowed template parameter.
1347 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1348 // Just pretend that we didn't see the previous declaration.
1349 PrevDecl = nullptr;
1350 }
1351
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001352 // If there is a previous declaration with the same name, check
1353 // whether this is a valid redeclaration.
Richard Smithbecb92d2017-10-10 22:33:17 +00001354 ClassTemplateDecl *PrevClassTemplate =
1355 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001356
1357 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001358 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001359 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001360 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001361 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1362 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001364 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1365 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1366 PrevClassTemplate
1367 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1368 ->getSpecializedTemplate();
1369 }
1370 }
1371
John McCalld43784f2009-12-18 11:25:59 +00001372 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001373 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001374 // [...] When looking for a prior declaration of a class or a function
1375 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001376 // function is neither a qualified name nor a template-id, scopes outside
1377 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001378 if (!SS.isSet()) {
1379 DeclContext *OutermostContext = CurContext;
1380 while (!OutermostContext->isFileContext())
1381 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001382
Richard Smith61e582f2012-04-20 07:12:26 +00001383 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001384 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1385 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1386 SemanticContext = PrevDecl->getDeclContext();
1387 } else {
1388 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001389 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001390 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001391 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001392 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001393
1394 // Check that the chosen semantic context doesn't already contain a
1395 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001396 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001397 DeclContext *LookupContext = SemanticContext;
1398 while (LookupContext->isTransparentContext())
1399 LookupContext = LookupContext->getLookupParent();
1400 LookupQualifiedName(Previous, LookupContext);
1401
1402 if (Previous.isAmbiguous())
1403 return true;
1404
1405 if (Previous.begin() != Previous.end())
1406 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001407 }
John McCall90d3bb92009-12-17 23:21:11 +00001408 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001409 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001410 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1411 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001412 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001413
Richard Smithfc805ca2015-07-06 04:43:58 +00001414 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1415 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1416 if (SS.isEmpty() &&
1417 !(PrevClassTemplate &&
1418 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1419 SemanticContext->getRedeclContext()))) {
1420 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1421 Diag(Shadow->getTargetDecl()->getLocation(),
1422 diag::note_using_decl_target);
1423 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1424 // Recover by ignoring the old declaration.
1425 PrevDecl = PrevClassTemplate = nullptr;
1426 }
1427 }
1428
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001429 // TODO Memory management; associated constraints are not always stored.
1430 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1431
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001432 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001433 // Ensure that the template parameter lists are compatible. Skip this check
1434 // for a friend in a dependent context: the template parameter list itself
1435 // could be dependent.
1436 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1437 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001438 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001439 /*Complain=*/true,
1440 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001441 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001442
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001443 // Check for matching associated constraints on redeclarations.
1444 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1445 const bool RedeclACMismatch = [&] {
1446 if (!(CurAC || PrevAC))
1447 return false; // Nothing to check; no mismatch.
1448 if (CurAC && PrevAC) {
1449 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1450 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1451 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1452 if (CurACInfo == PrevACInfo)
1453 return false; // All good; no mismatch.
1454 }
1455 return true;
1456 }();
1457
1458 if (RedeclACMismatch) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001459 Diag(CurAC ? CurAC->getBeginLoc() : NameLoc,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001460 diag::err_template_different_associated_constraints);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001461 Diag(PrevAC ? PrevAC->getBeginLoc() : PrevClassTemplate->getLocation(),
1462 diag::note_template_prev_declaration)
1463 << /*declaration*/ 0;
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001464 return true;
1465 }
1466
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001467 // C++ [temp.class]p4:
1468 // In a redeclaration, partial specialization, explicit
1469 // specialization or explicit instantiation of a class template,
1470 // the class-key shall agree in kind with the original class
1471 // template declaration (7.1.5.3).
1472 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001473 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001474 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001475 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001476 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001477 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001478 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001479 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001480 }
1481
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001482 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001483 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001484 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001485 // If we have a prior definition that is not visible, treat this as
1486 // simply making that previous definition visible.
1487 NamedDecl *Hidden = nullptr;
1488 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001489 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00001490 SkipBody->Previous = Def;
Richard Smithbe3980b2015-03-27 00:41:57 +00001491 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1492 assert(Tmpl && "original definition of a class template is not a "
1493 "class template?");
Richard Smith858e0e02017-05-11 23:11:16 +00001494 makeMergedDefinitionVisible(Hidden);
1495 makeMergedDefinitionVisible(Tmpl);
Richard Smithc4577662018-09-12 02:13:47 +00001496 } else {
1497 Diag(NameLoc, diag::err_redefinition) << Name;
1498 Diag(Def->getLocation(), diag::note_previous_definition);
1499 // FIXME: Would it make sense to try to "forget" the previous
1500 // definition, as part of error recovery?
1501 return true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001502 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001503 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001504 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001505 } else if (PrevDecl) {
1506 // C++ [temp]p5:
1507 // A class template shall not have the same name as any other
1508 // template, class, function, object, enumeration, enumerator,
1509 // namespace, or type in the same scope (3.3), except as specified
1510 // in (14.5.4).
1511 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1512 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001513 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001514 }
1515
Douglas Gregordba32632009-02-10 19:49:53 +00001516 // Check the template parameter list of this declaration, possibly
1517 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001518 // template declaration. Skip this check for a friend in a dependent
1519 // context, because the template parameter list might be dependent.
1520 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001521 CheckTemplateParameterList(
1522 TemplateParams,
Richard Smithc4577662018-09-12 02:13:47 +00001523 PrevClassTemplate
1524 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1525 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001526 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1527 SemanticContext->isDependentContext())
1528 ? TPC_ClassTemplateMember
Richard Smithc4577662018-09-12 02:13:47 +00001529 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1530 SkipBody))
Douglas Gregordba32632009-02-10 19:49:53 +00001531 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001532
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001533 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001534 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001535 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001536 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1537 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001538 : diag::err_member_decl_does_not_match)
1539 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001540 Invalid = true;
1541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001542 }
1543
Vassil Vassilev352e4412017-01-12 09:16:26 +00001544 // If this is a templated friend in a dependent context we should not put it
1545 // on the redecl chain. In some cases, the templated friend can be the most
1546 // recent declaration tricking the template instantiator to make substitutions
1547 // there.
1548 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1549 bool ShouldAddRedecl
1550 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1551
Mike Stump11289f42009-09-09 15:08:12 +00001552 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001553 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001554 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001555 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001556 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001557 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001558 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001559 NewClass->setTemplateParameterListsInfo(
1560 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1561 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001562
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001563 // Add alignment attributes if necessary; these attributes are checked when
1564 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00001565 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Eli Friedman0415f3e12012-08-08 21:08:34 +00001566 AddAlignmentAttributesForRecord(NewClass);
1567 AddMsStructLayoutForRecord(NewClass);
1568 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001569
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001570 // Attach the associated constraints when the declaration will not be part of
1571 // a decl chain.
1572 Expr *const ACtoAttach =
1573 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1574
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001575 ClassTemplateDecl *NewTemplate
1576 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1577 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001578 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001579
1580 if (ShouldAddRedecl)
1581 NewTemplate->setPreviousDecl(PrevClassTemplate);
1582
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001583 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001584
Douglas Gregor21823bf2011-12-20 18:11:52 +00001585 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001586 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001587
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001588 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001589 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001590 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001591 assert(T->isDependentType() && "Class template type is not dependent?");
1592 (void)T;
1593
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001594 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001595 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001596 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001597 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1598 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001599
Anders Carlsson137108d2009-03-26 01:24:28 +00001600 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001601 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001602 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001603
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001604 // Set the lexical context of these templates
1605 NewClass->setLexicalDeclContext(CurContext);
1606 NewTemplate->setLexicalDeclContext(CurContext);
1607
Richard Smithc4577662018-09-12 02:13:47 +00001608 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001609 NewClass->startDefinition();
1610
Erich Keanec480f302018-07-12 21:09:05 +00001611 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001612
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001613 if (PrevClassTemplate)
1614 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1615
Rafael Espindola385c0422012-07-13 18:04:45 +00001616 AddPushedVisibilityAttribute(NewClass);
1617
Richard Smith234ff472014-08-23 00:49:01 +00001618 if (TUK != TUK_Friend) {
1619 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1620 Scope *Outer = S;
1621 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1622 Outer = Outer->getParent();
1623 PushOnScopeChains(NewTemplate, Outer);
1624 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001625 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001626 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001627 NewClass->setAccess(PrevClassTemplate->getAccess());
1628 }
John McCall27b5c252009-09-14 21:59:20 +00001629
Richard Smith64017682013-07-17 23:53:16 +00001630 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001631
John McCall27b5c252009-09-14 21:59:20 +00001632 // Friend templates are visible in fairly strange ways.
1633 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001634 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001635 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001636 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1637 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001638 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001639 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001640
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001641 FriendDecl *Friend = FriendDecl::Create(
1642 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001643 Friend->setAccess(AS_public);
1644 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001645 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001646
Richard Smithbecb92d2017-10-10 22:33:17 +00001647 if (PrevClassTemplate)
1648 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1649
Douglas Gregordba32632009-02-10 19:49:53 +00001650 if (Invalid) {
1651 NewTemplate->setInvalidDecl();
1652 NewClass->setInvalidDecl();
1653 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001654
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001655 ActOnDocumentableDecl(NewTemplate);
1656
Richard Smithc4577662018-09-12 02:13:47 +00001657 if (SkipBody && SkipBody->ShouldSkip)
1658 return SkipBody->Previous;
1659
John McCall48871652010-08-21 09:40:31 +00001660 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001661}
1662
Richard Smith32918772017-02-14 00:25:28 +00001663namespace {
Erik Pilkington69770d32018-07-27 21:23:48 +00001664/// Tree transform to "extract" a transformed type from a class template's
1665/// constructor to a deduction guide.
1666class ExtractTypeForDeductionGuide
1667 : public TreeTransform<ExtractTypeForDeductionGuide> {
1668public:
1669 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
1670 ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1671
1672 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1673
1674 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1675 return TransformType(
1676 TLB,
1677 TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1678 }
1679};
1680
Richard Smith32918772017-02-14 00:25:28 +00001681/// Transform to convert portions of a constructor declaration into the
1682/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1683struct ConvertConstructorToDeductionGuideTransform {
1684 ConvertConstructorToDeductionGuideTransform(Sema &S,
1685 ClassTemplateDecl *Template)
1686 : SemaRef(S), Template(Template) {}
1687
1688 Sema &SemaRef;
1689 ClassTemplateDecl *Template;
1690
1691 DeclContext *DC = Template->getDeclContext();
1692 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1693 DeclarationName DeductionGuideName =
1694 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1695
1696 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1697
1698 // Index adjustment to apply to convert depth-1 template parameters into
1699 // depth-0 template parameters.
1700 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1701
1702 /// Transform a constructor declaration into a deduction guide.
Richard Smithbc491202017-02-17 20:05:37 +00001703 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1704 CXXConstructorDecl *CD) {
Richard Smith32918772017-02-14 00:25:28 +00001705 SmallVector<TemplateArgument, 16> SubstArgs;
1706
Richard Smithb4f96252017-02-21 06:30:38 +00001707 LocalInstantiationScope Scope(SemaRef);
1708
Richard Smith32918772017-02-14 00:25:28 +00001709 // C++ [over.match.class.deduct]p1:
1710 // -- For each constructor of the class template designated by the
1711 // template-name, a function template with the following properties:
1712
1713 // -- The template parameters are the template parameters of the class
1714 // template followed by the template parameters (including default
1715 // template arguments) of the constructor, if any.
1716 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1717 if (FTD) {
1718 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1719 SmallVector<NamedDecl *, 16> AllParams;
1720 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1721 AllParams.insert(AllParams.begin(),
1722 TemplateParams->begin(), TemplateParams->end());
1723 SubstArgs.reserve(InnerParams->size());
1724
1725 // Later template parameters could refer to earlier ones, so build up
1726 // a list of substituted template arguments as we go.
1727 for (NamedDecl *Param : *InnerParams) {
1728 MultiLevelTemplateArgumentList Args;
1729 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001730 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001731 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1732 if (!NewParam)
1733 return nullptr;
1734 AllParams.push_back(NewParam);
1735 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1736 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1737 }
1738 TemplateParams = TemplateParameterList::Create(
1739 SemaRef.Context, InnerParams->getTemplateLoc(),
1740 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1741 /*FIXME: RequiresClause*/ nullptr);
1742 }
1743
1744 // If we built a new template-parameter-list, track that we need to
1745 // substitute references to the old parameters into references to the
1746 // new ones.
1747 MultiLevelTemplateArgumentList Args;
1748 if (FTD) {
1749 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001750 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001751 }
1752
Richard Smithbc491202017-02-17 20:05:37 +00001753 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
Richard Smith32918772017-02-14 00:25:28 +00001754 .getAsAdjusted<FunctionProtoTypeLoc>();
1755 assert(FPTL && "no prototype for constructor declaration");
1756
1757 // Transform the type of the function, adjusting the return type and
1758 // replacing references to the old parameters with references to the
1759 // new ones.
1760 TypeLocBuilder TLB;
1761 SmallVector<ParmVarDecl*, 8> Params;
1762 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1763 if (NewType.isNull())
1764 return nullptr;
1765 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1766
Richard Smithbc491202017-02-17 20:05:37 +00001767 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001768 CD->getBeginLoc(), CD->getLocation(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001769 CD->getEndLoc());
Richard Smith32918772017-02-14 00:25:28 +00001770 }
1771
1772 /// Build a deduction guide with the specified parameter types.
1773 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1774 SourceLocation Loc = Template->getLocation();
1775
1776 // Build the requested type.
1777 FunctionProtoType::ExtProtoInfo EPI;
1778 EPI.HasTrailingReturn = true;
1779 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1780 DeductionGuideName, EPI);
1781 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1782
1783 FunctionProtoTypeLoc FPTL =
1784 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1785
1786 // Build the parameters, needed during deduction / substitution.
1787 SmallVector<ParmVarDecl*, 4> Params;
1788 for (auto T : ParamTypes) {
1789 ParmVarDecl *NewParam = ParmVarDecl::Create(
1790 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1791 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1792 NewParam->setScopeInfo(0, Params.size());
1793 FPTL.setParam(Params.size(), NewParam);
1794 Params.push_back(NewParam);
1795 }
1796
1797 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1798 Loc, Loc, Loc);
1799 }
1800
1801private:
1802 /// Transform a constructor template parameter into a deduction guide template
1803 /// parameter, rebuilding any internal references to earlier parameters and
1804 /// renumbering as we go.
1805 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1806 MultiLevelTemplateArgumentList &Args) {
1807 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1808 // TemplateTypeParmDecl's index cannot be changed after creation, so
1809 // substitute it directly.
1810 auto *NewTTP = TemplateTypeParmDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001811 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
1812 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
Richard Smith32918772017-02-14 00:25:28 +00001813 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1814 TTP->isParameterPack());
1815 if (TTP->hasDefaultArgument()) {
1816 TypeSourceInfo *InstantiatedDefaultArg =
1817 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1818 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1819 if (InstantiatedDefaultArg)
1820 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1821 }
Richard Smithb4f96252017-02-21 06:30:38 +00001822 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1823 NewTTP);
Richard Smith32918772017-02-14 00:25:28 +00001824 return NewTTP;
1825 }
1826
1827 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1828 return transformTemplateParameterImpl(TTP, Args);
1829
1830 return transformTemplateParameterImpl(
1831 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1832 }
1833 template<typename TemplateParmDecl>
1834 TemplateParmDecl *
1835 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1836 MultiLevelTemplateArgumentList &Args) {
1837 // Ask the template instantiator to do the heavy lifting for us, then adjust
1838 // the index of the parameter once it's done.
1839 auto *NewParam =
1840 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1841 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1842 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1843 return NewParam;
1844 }
1845
1846 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1847 FunctionProtoTypeLoc TL,
1848 SmallVectorImpl<ParmVarDecl*> &Params,
1849 MultiLevelTemplateArgumentList &Args) {
1850 SmallVector<QualType, 4> ParamTypes;
1851 const FunctionProtoType *T = TL.getTypePtr();
1852
1853 // -- The types of the function parameters are those of the constructor.
1854 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001855 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001856 if (!NewParam)
1857 return QualType();
1858 ParamTypes.push_back(NewParam->getType());
1859 Params.push_back(NewParam);
1860 }
1861
1862 // -- The return type is the class template specialization designated by
1863 // the template-name and template arguments corresponding to the
1864 // template parameters obtained from the class template.
1865 //
1866 // We use the injected-class-name type of the primary template instead.
1867 // This has the convenient property that it is different from any type that
1868 // the user can write in a deduction-guide (because they cannot enter the
1869 // context of the template), so implicit deduction guides can never collide
1870 // with explicit ones.
1871 QualType ReturnType = DeducedType;
1872 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1873
1874 // Resolving a wording defect, we also inherit the variadicness of the
1875 // constructor.
1876 FunctionProtoType::ExtProtoInfo EPI;
1877 EPI.Variadic = T->isVariadic();
1878 EPI.HasTrailingReturn = true;
1879
1880 QualType Result = SemaRef.BuildFunctionType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001881 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
Richard Smith32918772017-02-14 00:25:28 +00001882 if (Result.isNull())
1883 return QualType();
1884
1885 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1886 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1887 NewTL.setLParenLoc(TL.getLParenLoc());
1888 NewTL.setRParenLoc(TL.getRParenLoc());
1889 NewTL.setExceptionSpecRange(SourceRange());
1890 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1891 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1892 NewTL.setParam(I, Params[I]);
1893
1894 return Result;
1895 }
1896
1897 ParmVarDecl *
1898 transformFunctionTypeParam(ParmVarDecl *OldParam,
1899 MultiLevelTemplateArgumentList &Args) {
1900 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smith479ba8e2017-04-20 01:15:31 +00001901 TypeSourceInfo *NewDI;
Erik Pilkington69770d32018-07-27 21:23:48 +00001902 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
Richard Smith479ba8e2017-04-20 01:15:31 +00001903 // Expand out the one and only element in each inner pack.
1904 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1905 NewDI =
1906 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1907 OldParam->getLocation(), OldParam->getDeclName());
1908 if (!NewDI) return nullptr;
1909 NewDI =
1910 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1911 PackTL.getTypePtr()->getNumExpansions());
1912 } else
1913 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1914 OldParam->getDeclName());
Richard Smith32918772017-02-14 00:25:28 +00001915 if (!NewDI)
1916 return nullptr;
1917
Erik Pilkington69770d32018-07-27 21:23:48 +00001918 // Extract the type. This (for instance) replaces references to typedef
1919 // members of the current instantiations with the definitions of those
1920 // typedefs, avoiding triggering instantiation of the deduced type during
1921 // deduction.
1922 NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
Richard Smithc27b3d72017-02-14 01:49:59 +00001923
Richard Smith32918772017-02-14 00:25:28 +00001924 // Resolving a wording defect, we also inherit default arguments from the
1925 // constructor.
1926 ExprResult NewDefArg;
1927 if (OldParam->hasDefaultArg()) {
Erik Pilkington69770d32018-07-27 21:23:48 +00001928 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
Richard Smith32918772017-02-14 00:25:28 +00001929 if (NewDefArg.isInvalid())
1930 return nullptr;
1931 }
1932
1933 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1934 OldParam->getInnerLocStart(),
1935 OldParam->getLocation(),
1936 OldParam->getIdentifier(),
1937 NewDI->getType(),
1938 NewDI,
1939 OldParam->getStorageClass(),
1940 NewDefArg.get());
1941 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1942 OldParam->getFunctionScopeIndex());
Erik Pilkington69770d32018-07-27 21:23:48 +00001943 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
Richard Smith32918772017-02-14 00:25:28 +00001944 return NewParam;
1945 }
1946
1947 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1948 bool Explicit, TypeSourceInfo *TInfo,
1949 SourceLocation LocStart, SourceLocation Loc,
1950 SourceLocation LocEnd) {
Richard Smithbc491202017-02-17 20:05:37 +00001951 DeclarationNameInfo Name(DeductionGuideName, Loc);
Richard Smithefa919a2017-02-16 21:29:21 +00001952 ArrayRef<ParmVarDecl *> Params =
1953 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1954
Richard Smith32918772017-02-14 00:25:28 +00001955 // Build the implicit deduction guide template.
Richard Smithbc491202017-02-17 20:05:37 +00001956 auto *Guide =
1957 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1958 Name, TInfo->getType(), TInfo, LocEnd);
Richard Smith32918772017-02-14 00:25:28 +00001959 Guide->setImplicit();
Richard Smithefa919a2017-02-16 21:29:21 +00001960 Guide->setParams(Params);
1961
1962 for (auto *Param : Params)
1963 Param->setDeclContext(Guide);
Richard Smith32918772017-02-14 00:25:28 +00001964
1965 auto *GuideTemplate = FunctionTemplateDecl::Create(
1966 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1967 GuideTemplate->setImplicit();
1968 Guide->setDescribedFunctionTemplate(GuideTemplate);
1969
1970 if (isa<CXXRecordDecl>(DC)) {
1971 Guide->setAccess(AS_public);
1972 GuideTemplate->setAccess(AS_public);
1973 }
1974
1975 DC->addDecl(GuideTemplate);
1976 return GuideTemplate;
1977 }
1978};
1979}
1980
1981void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1982 SourceLocation Loc) {
1983 DeclContext *DC = Template->getDeclContext();
1984 if (DC->isDependentContext())
1985 return;
1986
1987 ConvertConstructorToDeductionGuideTransform Transform(
1988 *this, cast<ClassTemplateDecl>(Template));
1989 if (!isCompleteType(Loc, Transform.DeducedType))
1990 return;
1991
1992 // Check whether we've already declared deduction guides for this template.
1993 // FIXME: Consider storing a flag on the template to indicate this.
1994 auto Existing = DC->lookup(Transform.DeductionGuideName);
1995 for (auto *D : Existing)
1996 if (D->isImplicit())
1997 return;
1998
1999 // In case we were expanding a pack when we attempted to declare deduction
2000 // guides, turn off pack expansion for everything we're about to do.
2001 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2002 // Create a template instantiation record to track the "instantiation" of
2003 // constructors into deduction guides.
2004 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2005 // this substitution process actually fail?
2006 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
Volodymyr Sapsai2f649f32018-05-14 22:49:44 +00002007 if (BuildingDeductionGuides.isInvalid())
2008 return;
Richard Smith32918772017-02-14 00:25:28 +00002009
2010 // Convert declared constructors into deduction guide templates.
2011 // FIXME: Skip constructors for which deduction must necessarily fail (those
2012 // for which some class template parameter without a default argument never
2013 // appears in a deduced context).
2014 bool AddedAny = false;
Richard Smith32918772017-02-14 00:25:28 +00002015 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2016 D = D->getUnderlyingDecl();
2017 if (D->isInvalidDecl() || D->isImplicit())
2018 continue;
2019 D = cast<NamedDecl>(D->getCanonicalDecl());
2020
2021 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00002022 auto *CD =
2023 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00002024 // Class-scope explicit specializations (MS extension) do not result in
2025 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00002026 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00002027 continue;
2028
Richard Smithbc491202017-02-17 20:05:37 +00002029 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00002030 AddedAny = true;
Richard Smith32918772017-02-14 00:25:28 +00002031 }
2032
Faisal Vali81b756e2017-10-22 14:45:08 +00002033 // C++17 [over.match.class.deduct]
2034 // -- If C is not defined or does not declare any constructors, an
2035 // additional function template derived as above from a hypothetical
2036 // constructor C().
Richard Smith32918772017-02-14 00:25:28 +00002037 if (!AddedAny)
2038 Transform.buildSimpleDeductionGuide(None);
2039
Faisal Vali81b756e2017-10-22 14:45:08 +00002040 // -- An additional function template derived as above from a hypothetical
2041 // constructor C(C), called the copy deduction candidate.
2042 cast<CXXDeductionGuideDecl>(
2043 cast<FunctionTemplateDecl>(
2044 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2045 ->getTemplatedDecl())
2046 ->setIsCopyDeductionCandidate();
Richard Smith32918772017-02-14 00:25:28 +00002047}
2048
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002049/// Diagnose the presence of a default template argument on a
Douglas Gregored5731f2009-11-25 17:50:39 +00002050/// template parameter, which is ill-formed in certain contexts.
2051///
2052/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002053static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00002054 Sema::TemplateParamListContext TPC,
2055 SourceLocation ParamLoc,
2056 SourceRange DefArgRange) {
2057 switch (TPC) {
2058 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002059 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00002060 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002061 return false;
2062
2063 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002064 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002065 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00002066 // A default template-argument shall not be specified in a
2067 // function template declaration or a function template
2068 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00002069 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002070 // template-argument, that declaration shall be a definition and shall be
2071 // the only declaration of the function template in the translation unit.
2072 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002073 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002074 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2075 : diag::ext_template_parameter_default_in_function_template)
2076 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00002077 return false;
2078
2079 case Sema::TPC_ClassTemplateMember:
2080 // C++0x [temp.param]p9:
2081 // A default template-argument shall not be specified in the
2082 // template-parameter-lists of the definition of a member of a
2083 // class template that appears outside of the member's class.
2084 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2085 << DefArgRange;
2086 return true;
2087
David Majnemerba8f17a2013-06-25 22:08:55 +00002088 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002089 case Sema::TPC_FriendFunctionTemplate:
2090 // C++ [temp.param]p9:
2091 // A default template-argument shall not be specified in a
2092 // friend template declaration.
2093 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2094 << DefArgRange;
2095 return true;
2096
2097 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2098 // for friend function templates if there is only a single
2099 // declaration (and it is a definition). Strange!
2100 }
2101
David Blaikie8a40f702012-01-17 06:56:22 +00002102 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00002103}
2104
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002105/// Check for unexpanded parameter packs within the template parameters
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002106/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00002107static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2108 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002109 // A template template parameter which is a parameter pack is also a pack
2110 // expansion.
2111 if (TTP->isParameterPack())
2112 return false;
2113
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002114 TemplateParameterList *Params = TTP->getTemplateParameters();
2115 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2116 NamedDecl *P = Params->getParam(I);
2117 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002118 if (!NTTP->isParameterPack() &&
2119 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002120 NTTP->getTypeSourceInfo(),
2121 Sema::UPPC_NonTypeTemplateParameterType))
2122 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002123
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002124 continue;
2125 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002126
2127 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002128 = dyn_cast<TemplateTemplateParmDecl>(P))
2129 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2130 return true;
2131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002132
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002133 return false;
2134}
2135
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002136/// Checks the validity of a template parameter list, possibly
Douglas Gregordba32632009-02-10 19:49:53 +00002137/// considering the template parameter list from a previous
2138/// declaration.
2139///
2140/// If an "old" template parameter list is provided, it must be
2141/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2142/// template parameter list.
2143///
2144/// \param NewParams Template parameter list for a new template
2145/// declaration. This template parameter list will be updated with any
2146/// default arguments that are carried through from the previous
2147/// template parameter list.
2148///
2149/// \param OldParams If provided, template parameter list from a
2150/// previous declaration of the same template. Default template
2151/// arguments will be merged from the old template parameter list to
2152/// the new template parameter list.
2153///
Douglas Gregored5731f2009-11-25 17:50:39 +00002154/// \param TPC Describes the context in which we are checking the given
2155/// template parameter list.
2156///
Richard Smithc4577662018-09-12 02:13:47 +00002157/// \param SkipBody If we might have already made a prior merged definition
2158/// of this template visible, the corresponding body-skipping information.
2159/// Default argument redefinition is not an error when skipping such a body,
2160/// because (under the ODR) we can assume the default arguments are the same
2161/// as the prior merged definition.
2162///
Douglas Gregordba32632009-02-10 19:49:53 +00002163/// \returns true if an error occurred, false otherwise.
2164bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00002165 TemplateParameterList *OldParams,
Richard Smithc4577662018-09-12 02:13:47 +00002166 TemplateParamListContext TPC,
2167 SkipBodyInfo *SkipBody) {
Douglas Gregordba32632009-02-10 19:49:53 +00002168 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00002169
Douglas Gregordba32632009-02-10 19:49:53 +00002170 // C++ [temp.param]p10:
2171 // The set of default template-arguments available for use with a
2172 // template declaration or definition is obtained by merging the
2173 // default arguments from the definition (if in scope) and all
2174 // declarations in scope in the same way default function
2175 // arguments are (8.3.6).
2176 bool SawDefaultArgument = false;
2177 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00002178
Mike Stumpc89c8e32009-02-11 23:03:27 +00002179 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00002180 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00002181 if (OldParams)
2182 OldParam = OldParams->begin();
2183
Douglas Gregor0693def2011-01-27 01:40:17 +00002184 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00002185 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2186 NewParamEnd = NewParams->end();
2187 NewParam != NewParamEnd; ++NewParam) {
2188 // Variables used to diagnose redundant default arguments
2189 bool RedundantDefaultArg = false;
2190 SourceLocation OldDefaultLoc;
2191 SourceLocation NewDefaultLoc;
2192
David Blaikie651c73c2011-10-19 05:19:50 +00002193 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00002194 bool MissingDefaultArg = false;
2195
David Blaikie651c73c2011-10-19 05:19:50 +00002196 // Variable used to diagnose non-final parameter packs
2197 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00002198
Douglas Gregordba32632009-02-10 19:49:53 +00002199 if (TemplateTypeParmDecl *NewTypeParm
2200 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00002201 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002202 if (NewTypeParm->hasDefaultArgument() &&
2203 DiagnoseDefaultTemplateArgument(*this, TPC,
2204 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002205 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002206 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00002207 NewTypeParm->removeDefaultArgument();
2208
2209 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002210 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002211 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00002212 if (NewTypeParm->isParameterPack()) {
2213 assert(!NewTypeParm->hasDefaultArgument() &&
2214 "Parameter packs can't have a default argument!");
2215 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002216 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002217 NewTypeParm->hasDefaultArgument() &&
2218 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002219 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2220 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2221 SawDefaultArgument = true;
2222 RedundantDefaultArg = true;
2223 PreviousDefaultArgLoc = NewDefaultLoc;
2224 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2225 // Merge the default argument from the old declaration to the
2226 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002227 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002228 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2229 } else if (NewTypeParm->hasDefaultArgument()) {
2230 SawDefaultArgument = true;
2231 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2232 } else if (SawDefaultArgument)
2233 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002234 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00002235 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002236 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002237 if (!NewNonTypeParm->isParameterPack() &&
2238 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002239 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002240 UPPC_NonTypeTemplateParameterType)) {
2241 Invalid = true;
2242 continue;
2243 }
2244
Douglas Gregored5731f2009-11-25 17:50:39 +00002245 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002246 if (NewNonTypeParm->hasDefaultArgument() &&
2247 DiagnoseDefaultTemplateArgument(*this, TPC,
2248 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002249 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00002250 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002251 }
2252
Mike Stump12b8ce12009-08-04 21:02:39 +00002253 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002254 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002255 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002256 if (NewNonTypeParm->isParameterPack()) {
2257 assert(!NewNonTypeParm->hasDefaultArgument() &&
2258 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002259 if (!NewNonTypeParm->isPackExpansion())
2260 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002261 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002262 NewNonTypeParm->hasDefaultArgument() &&
2263 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002264 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2265 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2266 SawDefaultArgument = true;
2267 RedundantDefaultArg = true;
2268 PreviousDefaultArgLoc = NewDefaultLoc;
2269 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2270 // Merge the default argument from the old declaration to the
2271 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002272 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002273 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2274 } else if (NewNonTypeParm->hasDefaultArgument()) {
2275 SawDefaultArgument = true;
2276 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2277 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002278 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002279 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00002280 TemplateTemplateParmDecl *NewTemplateParm
2281 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002282
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002283 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002284 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002285 Invalid = true;
2286 continue;
2287 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002288
David Blaikie651c73c2011-10-19 05:19:50 +00002289 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002290 if (NewTemplateParm->hasDefaultArgument() &&
2291 DiagnoseDefaultTemplateArgument(*this, TPC,
2292 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002293 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002294 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002295
2296 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002297 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002298 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002299 if (NewTemplateParm->isParameterPack()) {
2300 assert(!NewTemplateParm->hasDefaultArgument() &&
2301 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002302 if (!NewTemplateParm->isPackExpansion())
2303 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002304 } else if (OldTemplateParm &&
2305 hasVisibleDefaultArgument(OldTemplateParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002306 NewTemplateParm->hasDefaultArgument() &&
2307 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002308 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2309 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002310 SawDefaultArgument = true;
2311 RedundantDefaultArg = true;
2312 PreviousDefaultArgLoc = NewDefaultLoc;
2313 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2314 // Merge the default argument from the old declaration to the
2315 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002316 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002317 PreviousDefaultArgLoc
2318 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002319 } else if (NewTemplateParm->hasDefaultArgument()) {
2320 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002321 PreviousDefaultArgLoc
2322 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002323 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002324 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002325 }
2326
Richard Smith1fde8ec2012-09-07 02:06:42 +00002327 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002328 // If a template parameter of a primary class template or alias template
2329 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002330 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002331 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2332 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002333 Diag((*NewParam)->getLocation(),
2334 diag::err_template_param_pack_must_be_last_template_parameter);
2335 Invalid = true;
2336 }
2337
Douglas Gregordba32632009-02-10 19:49:53 +00002338 if (RedundantDefaultArg) {
2339 // C++ [temp.param]p12:
2340 // A template-parameter shall not be given default arguments
2341 // by two different declarations in the same scope.
2342 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2343 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2344 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002345 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002346 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002347 // If a template-parameter of a class template has a default
2348 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002349 // have a default template-argument supplied or be a template parameter
2350 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002351 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002352 diag::err_template_param_default_arg_missing);
2353 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2354 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002355 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002356 }
2357
2358 // If we have an old template parameter list that we're merging
2359 // in, move on to the next parameter.
2360 if (OldParams)
2361 ++OldParam;
2362 }
2363
Douglas Gregor0693def2011-01-27 01:40:17 +00002364 // We were missing some default arguments at the end of the list, so remove
2365 // all of the default arguments.
2366 if (RemoveDefaultArguments) {
2367 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2368 NewParamEnd = NewParams->end();
2369 NewParam != NewParamEnd; ++NewParam) {
2370 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2371 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002372 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002373 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2374 NTTP->removeDefaultArgument();
2375 else
2376 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2377 }
2378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002379
Douglas Gregordba32632009-02-10 19:49:53 +00002380 return Invalid;
2381}
Douglas Gregord32e0282009-02-09 23:23:08 +00002382
John McCalla020a012010-10-20 05:44:58 +00002383namespace {
2384
2385/// A class which looks for a use of a certain level of template
2386/// parameter.
2387struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2388 typedef RecursiveASTVisitor<DependencyChecker> super;
2389
2390 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00002391
2392 // Whether we're looking for a use of a template parameter that makes the
2393 // overall construct type-dependent / a dependent type. This is strictly
2394 // best-effort for now; we may fail to match at all for a dependent type
2395 // in some cases if this is set.
2396 bool IgnoreNonTypeDependent;
2397
John McCalla020a012010-10-20 05:44:58 +00002398 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002399 SourceLocation MatchLoc;
2400
Richard Smith13894182017-04-13 21:37:24 +00002401 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2402 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2403 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002404
Richard Smith57aae072016-12-28 02:37:25 +00002405 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith13894182017-04-13 21:37:24 +00002406 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2407 NamedDecl *ND = Params->getParam(0);
2408 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2409 Depth = PD->getDepth();
2410 } else if (NonTypeTemplateParmDecl *PD =
2411 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2412 Depth = PD->getDepth();
2413 } else {
2414 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2415 }
2416 }
John McCalla020a012010-10-20 05:44:58 +00002417
Richard Smith6056d5e2014-02-09 00:54:43 +00002418 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith13894182017-04-13 21:37:24 +00002419 if (ParmDepth >= Depth) {
John McCalla020a012010-10-20 05:44:58 +00002420 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002421 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002422 return true;
2423 }
2424 return false;
2425 }
2426
Richard Smith57aae072016-12-28 02:37:25 +00002427 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2428 // Prune out non-type-dependent expressions if requested. This can
2429 // sometimes result in us failing to find a template parameter reference
2430 // (if a value-dependent expression creates a dependent type), but this
2431 // mode is best-effort only.
2432 if (auto *E = dyn_cast_or_null<Expr>(S))
2433 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2434 return true;
2435 return super::TraverseStmt(S, Q);
2436 }
2437
2438 bool TraverseTypeLoc(TypeLoc TL) {
2439 if (IgnoreNonTypeDependent && !TL.isNull() &&
2440 !TL.getType()->isDependentType())
2441 return true;
2442 return super::TraverseTypeLoc(TL);
2443 }
2444
Richard Smith6056d5e2014-02-09 00:54:43 +00002445 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2446 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2447 }
2448
John McCalla020a012010-10-20 05:44:58 +00002449 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002450 // For a best-effort search, keep looking until we find a location.
2451 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002452 }
2453
2454 bool TraverseTemplateName(TemplateName N) {
2455 if (TemplateTemplateParmDecl *PD =
2456 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002457 if (Matches(PD->getDepth()))
2458 return false;
John McCalla020a012010-10-20 05:44:58 +00002459 return super::TraverseTemplateName(N);
2460 }
2461
2462 bool VisitDeclRefExpr(DeclRefExpr *E) {
2463 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002464 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2465 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002466 return false;
John McCalla020a012010-10-20 05:44:58 +00002467 return super::VisitDeclRefExpr(E);
2468 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002469
2470 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2471 return TraverseType(T->getReplacementType());
2472 }
2473
2474 bool
2475 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2476 return TraverseTemplateArgument(T->getArgumentPack());
2477 }
2478
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002479 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2480 return TraverseType(T->getInjectedSpecializationType());
2481 }
John McCalla020a012010-10-20 05:44:58 +00002482};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002483} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002484
Douglas Gregor972fe532011-05-10 18:27:06 +00002485/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002486/// list.
2487static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002488DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002489 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002490 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002491 return Checker.Match;
2492}
2493
Douglas Gregor972fe532011-05-10 18:27:06 +00002494// Find the source range corresponding to the named type in the given
2495// nested-name-specifier, if any.
2496static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2497 QualType T,
2498 const CXXScopeSpec &SS) {
2499 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2500 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2501 if (const Type *CurType = NNS->getAsType()) {
2502 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2503 return NNSLoc.getTypeLoc().getSourceRange();
2504 } else
2505 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002506
Douglas Gregor972fe532011-05-10 18:27:06 +00002507 NNSLoc = NNSLoc.getPrefix();
2508 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002509
Douglas Gregor972fe532011-05-10 18:27:06 +00002510 return SourceRange();
2511}
2512
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002513/// Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002514/// specifier, returning the template parameter list that applies to the
2515/// name.
2516///
2517/// \param DeclStartLoc the start of the declaration that has a scope
2518/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002519///
Douglas Gregor972fe532011-05-10 18:27:06 +00002520/// \param DeclLoc The location of the declaration itself.
2521///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002522/// \param SS the scope specifier that will be matched to the given template
2523/// parameter lists. This scope specifier precedes a qualified name that is
2524/// being declared.
2525///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002526/// \param TemplateId The template-id following the scope specifier, if there
2527/// is one. Used to check for a missing 'template<>'.
2528///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002529/// \param ParamLists the template parameter lists, from the outermost to the
2530/// innermost template parameter lists.
2531///
John McCalle820e5e2010-04-13 20:37:33 +00002532/// \param IsFriend Whether to apply the slightly different rules for
2533/// matching template parameters to scope specifiers in friend
2534/// declarations.
2535///
Richard Smithf445f192017-02-09 21:04:43 +00002536/// \param IsMemberSpecialization will be set true if the scope specifier
2537/// denotes a fully-specialized type, and therefore this is a declaration of
2538/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002539///
Mike Stump11289f42009-09-09 15:08:12 +00002540/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002541/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002542/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002543/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002544/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002545/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002546TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2547 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002548 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002549 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002550 bool &IsMemberSpecialization, bool &Invalid) {
2551 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002552 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002553
Douglas Gregor972fe532011-05-10 18:27:06 +00002554 // The sequence of nested types to which we will match up the template
2555 // parameter lists. We first build this list by starting with the type named
2556 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002557 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002558 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002559 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002560 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002561 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2562 T = Context.getTypeDeclType(Record);
2563 else
2564 T = QualType(SS.getScopeRep()->getAsType(), 0);
2565 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002566
Douglas Gregor972fe532011-05-10 18:27:06 +00002567 // If we found an explicit specialization that prevents us from needing
2568 // 'template<>' headers, this will be set to the location of that
2569 // explicit specialization.
2570 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002571
Douglas Gregor972fe532011-05-10 18:27:06 +00002572 while (!T.isNull()) {
2573 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002574
Douglas Gregor972fe532011-05-10 18:27:06 +00002575 // Retrieve the parent of a record type.
2576 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2577 // If this type is an explicit specialization, we're done.
2578 if (ClassTemplateSpecializationDecl *Spec
2579 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002580 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002581 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2582 ExplicitSpecLoc = Spec->getLocation();
2583 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002584 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002585 } else if (Record->getTemplateSpecializationKind()
2586 == TSK_ExplicitSpecialization) {
2587 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002588 break;
2589 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002590
Douglas Gregor972fe532011-05-10 18:27:06 +00002591 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2592 T = Context.getTypeDeclType(Parent);
2593 else
2594 T = QualType();
2595 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002596 }
2597
Douglas Gregor972fe532011-05-10 18:27:06 +00002598 if (const TemplateSpecializationType *TST
2599 = T->getAs<TemplateSpecializationType>()) {
2600 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2601 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2602 T = Context.getTypeDeclType(Parent);
2603 else
2604 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002605 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002606 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002607 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002608
Douglas Gregor972fe532011-05-10 18:27:06 +00002609 // Look one step prior in a dependent template specialization type.
2610 if (const DependentTemplateSpecializationType *DependentTST
2611 = T->getAs<DependentTemplateSpecializationType>()) {
2612 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2613 T = QualType(NNS->getAsType(), 0);
2614 else
2615 T = QualType();
2616 continue;
2617 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002618
Douglas Gregor972fe532011-05-10 18:27:06 +00002619 // Look one step prior in a dependent name type.
2620 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2621 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2622 T = QualType(NNS->getAsType(), 0);
2623 else
2624 T = QualType();
2625 continue;
2626 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002627
Douglas Gregor972fe532011-05-10 18:27:06 +00002628 // Retrieve the parent of an enumeration type.
2629 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2630 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2631 // check here.
2632 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002633
Douglas Gregor972fe532011-05-10 18:27:06 +00002634 // Get to the parent type.
2635 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2636 T = Context.getTypeDeclType(Parent);
2637 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002638 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002639 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002640 }
Mike Stump11289f42009-09-09 15:08:12 +00002641
Douglas Gregor972fe532011-05-10 18:27:06 +00002642 T = QualType();
2643 }
2644 // Reverse the nested types list, since we want to traverse from the outermost
2645 // to the innermost while checking template-parameter-lists.
2646 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002647
Douglas Gregor972fe532011-05-10 18:27:06 +00002648 // C++0x [temp.expl.spec]p17:
2649 // A member or a member template may be nested within many
2650 // enclosing class templates. In an explicit specialization for
2651 // such a member, the member declaration shall be preceded by a
2652 // template<> for each enclosing class template that is
2653 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002654 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002655
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002656 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002657 if (SawNonEmptyTemplateParameterList) {
2658 Diag(DeclLoc, diag::err_specialize_member_of_template)
2659 << !Recovery << Range;
2660 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002661 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002662 return true;
2663 }
2664
2665 return false;
2666 };
2667
2668 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2669 // Check that we can have an explicit specialization here.
2670 if (CheckExplicitSpecialization(Range, true))
2671 return true;
2672
2673 // We don't have a template header, but we should.
2674 SourceLocation ExpectedTemplateLoc;
2675 if (!ParamLists.empty())
2676 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2677 else
2678 ExpectedTemplateLoc = DeclStartLoc;
2679
2680 Diag(DeclLoc, diag::err_template_spec_needs_header)
2681 << Range
2682 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2683 return false;
2684 };
2685
Douglas Gregor972fe532011-05-10 18:27:06 +00002686 unsigned ParamIdx = 0;
2687 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2688 ++TypeIdx) {
2689 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002690
Douglas Gregor972fe532011-05-10 18:27:06 +00002691 // Whether we expect a 'template<>' header.
2692 bool NeedEmptyTemplateHeader = false;
2693
2694 // Whether we expect a template header with parameters.
2695 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002696
Douglas Gregor972fe532011-05-10 18:27:06 +00002697 // For a dependent type, the set of template parameters that we
2698 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002699 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002700
Douglas Gregor373af9b2011-05-11 23:26:17 +00002701 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002702 // A member or a member template may be nested within many enclosing
2703 // class templates. In an explicit specialization for such a member, the
2704 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002705 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002706 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2707 if (ClassTemplatePartialSpecializationDecl *Partial
2708 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2709 ExpectedTemplateParams = Partial->getTemplateParameters();
2710 NeedNonemptyTemplateHeader = true;
2711 } else if (Record->isDependentType()) {
2712 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002713 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002714 ->getTemplateParameters();
2715 NeedNonemptyTemplateHeader = true;
2716 }
2717 } else if (ClassTemplateSpecializationDecl *Spec
2718 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2719 // C++0x [temp.expl.spec]p4:
2720 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002721 // in the same manner as members of normal classes, and not using
2722 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002723 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2724 NeedEmptyTemplateHeader = true;
2725 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002726 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002727 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002728 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002729 != TSK_ExplicitSpecialization &&
2730 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002731 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002732
Douglas Gregor373af9b2011-05-11 23:26:17 +00002733 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002734 }
2735 } else if (const TemplateSpecializationType *TST
2736 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002737 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002738 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002739 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002740 }
2741 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2742 // FIXME: We actually could/should check the template arguments here
2743 // against the corresponding template parameter list.
2744 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002745 }
2746
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002747 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002748 // In an explicit specialization declaration for a member of a class
2749 // template or a member template that ap- pears in namespace scope, the
2750 // member template and some of its enclosing class templates may remain
2751 // unspecialized, except that the declaration shall not explicitly
2752 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002753 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002754 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002755 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002756 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2757 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002758 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002759 } else
2760 SawNonEmptyTemplateParameterList = true;
2761 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002762
Douglas Gregor972fe532011-05-10 18:27:06 +00002763 if (NeedEmptyTemplateHeader) {
2764 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002765 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002766 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002767 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002768
2769 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002770 if (ParamLists[ParamIdx]->size() > 0) {
2771 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002772 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002773 diag::err_template_param_list_matches_nontemplate)
2774 << T
2775 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2776 ParamLists[ParamIdx]->getRAngleLoc())
2777 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2778 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002779 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002780 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002781
Douglas Gregor972fe532011-05-10 18:27:06 +00002782 // Consume this template header.
2783 ++ParamIdx;
2784 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002785 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002786
2787 if (!IsFriend)
2788 if (DiagnoseMissingExplicitSpecialization(
2789 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002790 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002791
Douglas Gregor972fe532011-05-10 18:27:06 +00002792 continue;
2793 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002794
Douglas Gregor972fe532011-05-10 18:27:06 +00002795 if (NeedNonemptyTemplateHeader) {
2796 // In friend declarations we can have template-ids which don't
2797 // depend on the corresponding template parameter lists. But
2798 // assume that empty parameter lists are supposed to match this
2799 // template-id.
2800 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002801 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002802 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002803 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002804 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002805 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002806 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002807
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002808 if (ParamIdx < ParamLists.size()) {
2809 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002810 if (ExpectedTemplateParams &&
2811 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2812 ExpectedTemplateParams,
2813 true, TPL_TemplateMatch))
2814 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002815
Douglas Gregor972fe532011-05-10 18:27:06 +00002816 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002817 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002818 TPC_ClassTemplateMember))
2819 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002820
Douglas Gregor972fe532011-05-10 18:27:06 +00002821 ++ParamIdx;
2822 continue;
2823 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002824
Douglas Gregor972fe532011-05-10 18:27:06 +00002825 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2826 << T
2827 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2828 Invalid = true;
2829 continue;
2830 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002831 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002832
Douglas Gregord8d297c2009-07-21 23:53:31 +00002833 // If there were at least as many template-ids as there were template
2834 // parameter lists, then there are no template parameter lists remaining for
2835 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002836 if (ParamIdx >= ParamLists.size()) {
2837 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002838 // We don't have a template header for the declaration itself, but we
2839 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002840 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2841 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002842
2843 // Fabricate an empty template parameter list for the invented header.
2844 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002845 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002846 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002847 }
2848
Craig Topperc3ec1492014-05-26 06:22:03 +00002849 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002850 }
Mike Stump11289f42009-09-09 15:08:12 +00002851
Douglas Gregord8d297c2009-07-21 23:53:31 +00002852 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002853 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002854 bool HasAnyExplicitSpecHeader = false;
2855 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002856 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002857 if (ParamLists[I]->size() == 0)
2858 HasAnyExplicitSpecHeader = true;
2859 else
2860 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002861 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002862
Douglas Gregor972fe532011-05-10 18:27:06 +00002863 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002864 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2865 : diag::err_template_spec_extra_headers)
2866 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2867 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002868
2869 // If there was a specialization somewhere, such that 'template<>' is
2870 // not required, and there were any 'template<>' headers, note where the
2871 // specialization occurred.
2872 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002873 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002874 diag::note_explicit_template_spec_does_not_need_header)
2875 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002876
Douglas Gregor972fe532011-05-10 18:27:06 +00002877 // We have a template parameter list with no corresponding scope, which
2878 // means that the resulting template declaration can't be instantiated
2879 // properly (we'll end up with dependent nodes when we shouldn't).
2880 if (!AllExplicitSpecHeaders)
2881 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002882 }
Mike Stump11289f42009-09-09 15:08:12 +00002883
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002884 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002885 // In an explicit specialization declaration for a member of a class
2886 // template or a member template that ap- pears in namespace scope, the
2887 // member template and some of its enclosing class templates may remain
2888 // unspecialized, except that the declaration shall not explicitly
2889 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002890 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002891 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002892 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2893 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002894 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002895
Douglas Gregord8d297c2009-07-21 23:53:31 +00002896 // Return the last template parameter list, which corresponds to the
2897 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002898 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002899}
2900
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002901void Sema::NoteAllFoundTemplates(TemplateName Name) {
2902 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2903 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002904 << (isa<FunctionTemplateDecl>(Template)
2905 ? 0
2906 : isa<ClassTemplateDecl>(Template)
2907 ? 1
2908 : isa<VarTemplateDecl>(Template)
2909 ? 2
2910 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2911 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002912 return;
2913 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002914
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002915 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002916 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002917 IEnd = OST->end();
2918 I != IEnd; ++I)
2919 Diag((*I)->getLocation(), diag::note_template_declared_here)
2920 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002921
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002922 return;
2923 }
2924}
2925
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002926static QualType
2927checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2928 const SmallVectorImpl<TemplateArgument> &Converted,
2929 SourceLocation TemplateLoc,
2930 TemplateArgumentListInfo &TemplateArgs) {
2931 ASTContext &Context = SemaRef.getASTContext();
2932 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002933 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002934 // Specializations of __make_integer_seq<S, T, N> are treated like
2935 // S<T, 0, ..., N-1>.
2936
2937 // C++14 [inteseq.intseq]p1:
2938 // T shall be an integer type.
2939 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2940 SemaRef.Diag(TemplateArgs[1].getLocation(),
2941 diag::err_integer_sequence_integral_element_type);
2942 return QualType();
2943 }
2944
2945 // C++14 [inteseq.make]p1:
2946 // If N is negative the program is ill-formed.
2947 TemplateArgument NumArgsArg = Converted[2];
2948 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2949 if (NumArgs < 0) {
2950 SemaRef.Diag(TemplateArgs[2].getLocation(),
2951 diag::err_integer_sequence_negative_length);
2952 return QualType();
2953 }
2954
2955 QualType ArgTy = NumArgsArg.getIntegralType();
2956 TemplateArgumentListInfo SyntheticTemplateArgs;
2957 // The type argument gets reused as the first template argument in the
2958 // synthetic template argument list.
2959 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2960 // Expand N into 0 ... N-1.
2961 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2962 I < NumArgs; ++I) {
2963 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002964 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2965 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002966 }
2967 // The first template argument will be reused as the template decl that
2968 // our synthetic template arguments will be applied to.
2969 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2970 TemplateLoc, SyntheticTemplateArgs);
2971 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002972
2973 case BTK__type_pack_element:
2974 // Specializations of
2975 // __type_pack_element<Index, T_1, ..., T_N>
2976 // are treated like T_Index.
2977 assert(Converted.size() == 2 &&
2978 "__type_pack_element should be given an index and a parameter pack");
2979
2980 // If the Index is out of bounds, the program is ill-formed.
2981 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2982 llvm::APSInt Index = IndexArg.getAsIntegral();
2983 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2984 "type std::size_t, and hence be non-negative");
2985 if (Index >= Ts.pack_size()) {
2986 SemaRef.Diag(TemplateArgs[0].getLocation(),
2987 diag::err_type_pack_element_out_of_bounds);
2988 return QualType();
2989 }
2990
2991 // We simply return the type at index `Index`.
2992 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2993 return Nth->getAsType();
2994 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002995 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2996}
2997
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002998/// Determine whether this alias template is "enable_if_t".
2999static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3000 return AliasTemplate->getName().equals("enable_if_t");
3001}
3002
3003/// Collect all of the separable terms in the given condition, which
3004/// might be a conjunction.
3005///
3006/// FIXME: The right answer is to convert the logical expression into
3007/// disjunctive normal form, so we can find the first failed term
3008/// within each possible clause.
3009static void collectConjunctionTerms(Expr *Clause,
3010 SmallVectorImpl<Expr *> &Terms) {
3011 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3012 if (BinOp->getOpcode() == BO_LAnd) {
3013 collectConjunctionTerms(BinOp->getLHS(), Terms);
3014 collectConjunctionTerms(BinOp->getRHS(), Terms);
3015 }
3016
3017 return;
3018 }
3019
3020 Terms.push_back(Clause);
3021}
3022
Douglas Gregorbb33f572017-07-05 20:20:15 +00003023// The ranges-v3 library uses an odd pattern of a top-level "||" with
3024// a left-hand side that is value-dependent but never true. Identify
3025// the idiom and ignore that term.
3026static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3027 // Top-level '||'.
3028 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3029 if (!BinOp) return Cond;
3030
3031 if (BinOp->getOpcode() != BO_LOr) return Cond;
3032
3033 // With an inner '==' that has a literal on the right-hand side.
3034 Expr *LHS = BinOp->getLHS();
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003035 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
Douglas Gregorbb33f572017-07-05 20:20:15 +00003036 if (!InnerBinOp) return Cond;
3037
3038 if (InnerBinOp->getOpcode() != BO_EQ ||
3039 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3040 return Cond;
3041
3042 // If the inner binary operation came from a macro expansion named
3043 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3044 // of the '||', which is the real, user-provided condition.
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003045 SourceLocation Loc = InnerBinOp->getExprLoc();
Douglas Gregorbb33f572017-07-05 20:20:15 +00003046 if (!Loc.isMacroID()) return Cond;
3047
3048 StringRef MacroName = PP.getImmediateMacroName(Loc);
3049 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3050 return BinOp->getRHS();
3051
3052 return Cond;
3053}
3054
Clement Courbetf44c6f42018-12-11 08:39:11 +00003055namespace {
3056
3057// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3058// within failing boolean expression, such as substituting template parameters
3059// for actual types.
3060class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3061public:
3062 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3063 : Policy(P) {}
3064
3065 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3066 const auto *DR = dyn_cast<DeclRefExpr>(E);
3067 if (DR && DR->getQualifier()) {
3068 // If this is a qualified name, expand the template arguments in nested
3069 // qualifiers.
3070 DR->getQualifier()->print(OS, Policy, true);
3071 // Then print the decl itself.
3072 const ValueDecl *VD = DR->getDecl();
3073 OS << VD->getName();
3074 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3075 // This is a template variable, print the expanded template arguments.
3076 printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3077 }
3078 return true;
Clement Courbet9d432e02018-12-04 07:59:57 +00003079 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003080 return false;
Clement Courbet9d432e02018-12-04 07:59:57 +00003081 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003082
3083private:
3084 const PrintingPolicy Policy;
3085};
3086
3087} // end anonymous namespace
Clement Courbet9d432e02018-12-04 07:59:57 +00003088
Douglas Gregor672281a2017-09-14 23:38:42 +00003089std::pair<Expr *, std::string>
Clement Courbetf44c6f42018-12-11 08:39:11 +00003090Sema::findFailedBooleanCondition(Expr *Cond) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003091 Cond = lookThroughRangesV3Condition(PP, Cond);
Douglas Gregorbb33f572017-07-05 20:20:15 +00003092
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003093 // Separate out all of the terms in a conjunction.
3094 SmallVector<Expr *, 4> Terms;
3095 collectConjunctionTerms(Cond, Terms);
3096
3097 // Determine which term failed.
3098 Expr *FailedCond = nullptr;
3099 for (Expr *Term : Terms) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003100 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3101
Clement Courbetd8720412018-12-10 08:53:17 +00003102 // Literals are uninteresting.
3103 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3104 isa<IntegerLiteral>(TermAsWritten))
3105 continue;
3106
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003107 // The initialization of the parameter from the argument is
3108 // a constant-evaluated context.
3109 EnterExpressionEvaluationContext ConstantEvaluated(
Douglas Gregor672281a2017-09-14 23:38:42 +00003110 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003111
3112 bool Succeeded;
Douglas Gregor672281a2017-09-14 23:38:42 +00003113 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003114 !Succeeded) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003115 FailedCond = TermAsWritten;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003116 break;
3117 }
3118 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003119 if (!FailedCond)
Clement Courbetd8720412018-12-10 08:53:17 +00003120 FailedCond = Cond->IgnoreParenImpCasts();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003121
3122 std::string Description;
3123 {
3124 llvm::raw_string_ostream Out(Description);
Clement Courbetf44c6f42018-12-11 08:39:11 +00003125 FailedBooleanConditionPrinterHelper Helper(getPrintingPolicy());
3126 FailedCond->printPretty(Out, &Helper, getPrintingPolicy());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003127 }
3128 return { FailedCond, Description };
3129}
3130
Douglas Gregordc572a32009-03-30 22:58:21 +00003131QualType Sema::CheckTemplateIdType(TemplateName Name,
3132 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003133 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00003134 DependentTemplateName *DTN
3135 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00003136 if (DTN && DTN->isIdentifier())
3137 // When building a template-id where the template-name is dependent,
3138 // assume the template is a type template. Either our assumption is
3139 // correct, or the code is ill-formed and will be diagnosed when the
3140 // dependent name is substituted.
3141 return Context.getDependentTemplateSpecializationType(ETK_None,
3142 DTN->getQualifier(),
3143 DTN->getIdentifier(),
3144 TemplateArgs);
3145
Douglas Gregordc572a32009-03-30 22:58:21 +00003146 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00003147 if (!Template || isa<FunctionTemplateDecl>(Template) ||
Faisal Valia534f072018-04-26 00:42:40 +00003148 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003149 // We might have a substituted template template parameter pack. If so,
3150 // build a template specialization type for it.
3151 if (Name.getAsSubstTemplateTemplateParmPack())
3152 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003153
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003154 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3155 << Name;
3156 NoteAllFoundTemplates(Name);
3157 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00003158 }
Douglas Gregordc572a32009-03-30 22:58:21 +00003159
Douglas Gregorc40290e2009-03-09 23:48:35 +00003160 // Check that the template argument list is well-formed for this
3161 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003162 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00003163 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003164 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00003165 return QualType();
3166
Douglas Gregorc40290e2009-03-09 23:48:35 +00003167 QualType CanonType;
3168
Douglas Gregor678d76c2011-07-01 01:22:09 +00003169 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00003170 if (TypeAliasTemplateDecl *AliasTemplate =
3171 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00003172 // Find the canonical type for this type alias template specialization.
3173 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3174 if (Pattern->isInvalidDecl())
3175 return QualType();
3176
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003177 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3178 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003179
3180 // Only substitute for the innermost template argument list.
3181 MultiLevelTemplateArgumentList TemplateArgLists;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003182 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00003183 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3184 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00003185 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003186
Richard Smith802c4b72012-08-23 06:16:52 +00003187 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003188 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003189 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003190 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00003191
Richard Smith3f1b5d02011-05-05 21:57:07 +00003192 CanonType = SubstType(Pattern->getUnderlyingType(),
3193 TemplateArgLists, AliasTemplate->getLocation(),
3194 AliasTemplate->getDeclName());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003195 if (CanonType.isNull()) {
3196 // If this was enable_if and we failed to find the nested type
3197 // within enable_if in a SFINAE context, dig out the specific
3198 // enable_if condition that failed and present that instead.
3199 if (isEnableIfAliasTemplate(AliasTemplate)) {
3200 if (auto DeductionInfo = isSFINAEContext()) {
3201 if (*DeductionInfo &&
3202 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3203 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3204 diag::err_typename_nested_not_found_enable_if &&
3205 TemplateArgs[0].getArgument().getKind()
3206 == TemplateArgument::Expression) {
3207 Expr *FailedCond;
3208 std::string FailedDescription;
3209 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00003210 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003211
3212 // Remove the old SFINAE diagnostic.
3213 PartialDiagnosticAt OldDiag =
3214 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3215 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3216
3217 // Add a new SFINAE diagnostic specifying which condition
3218 // failed.
3219 (*DeductionInfo)->addSFINAEDiagnostic(
3220 OldDiag.first,
3221 PDiag(diag::err_typename_nested_not_found_requirement)
3222 << FailedDescription
3223 << FailedCond->getSourceRange());
3224 }
3225 }
3226 }
3227
Richard Smith3f1b5d02011-05-05 21:57:07 +00003228 return QualType();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003229 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003230 } else if (Name.isDependent() ||
3231 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00003232 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003233 // This class template specialization is a dependent
3234 // type. Therefore, its canonical type is another class template
3235 // specialization type that contains all of the converted
3236 // arguments in canonical form. This ensures that, e.g., A<T> and
3237 // A<T, T> have identical types when A is declared as:
3238 //
3239 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003240 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00003241
3242 // This might work out to be a current instantiation, in which
3243 // case the canonical type needs to be the InjectedClassNameType.
3244 //
3245 // TODO: in theory this could be a simple hashtable lookup; most
3246 // changes to CurContext don't change the set of current
3247 // instantiations.
3248 if (isa<ClassTemplateDecl>(Template)) {
3249 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3250 // If we get out to a namespace, we're done.
3251 if (Ctx->isFileContext()) break;
3252
3253 // If this isn't a record, keep looking.
3254 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3255 if (!Record) continue;
3256
3257 // Look for one of the two cases with InjectedClassNameTypes
3258 // and check whether it's the same template.
3259 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3260 !Record->getDescribedClassTemplate())
3261 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003262
John McCall2408e322010-04-27 00:57:59 +00003263 // Fetch the injected class name type and check whether its
3264 // injected type is equal to the type we just built.
3265 QualType ICNT = Context.getTypeDeclType(Record);
3266 QualType Injected = cast<InjectedClassNameType>(ICNT)
3267 ->getInjectedSpecializationType();
3268
3269 if (CanonType != Injected->getCanonicalTypeInternal())
3270 continue;
3271
3272 // If so, the canonical type of this TST is the injected
3273 // class name type of the record we just found.
3274 assert(ICNT.isCanonical());
3275 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00003276 break;
3277 }
3278 }
Mike Stump11289f42009-09-09 15:08:12 +00003279 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00003280 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003281 // Find the class template specialization declaration that
3282 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003283 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003284 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00003285 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003286 if (!Decl) {
3287 // This is the first time we have referenced this class template
3288 // specialization. Create the canonical declaration and add it to
3289 // the set of specializations.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003290 Decl = ClassTemplateSpecializationDecl::Create(
3291 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3292 ClassTemplate->getDeclContext(),
3293 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3294 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003295 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00003296 if (ClassTemplate->isOutOfLine())
3297 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00003298 }
3299
Erich Keanea32910d2017-03-23 18:51:54 +00003300 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3301 MultiLevelTemplateArgumentList TemplateArgLists;
3302 TemplateArgLists.addOuterTemplateArguments(Converted);
3303 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3304 Decl);
3305 }
3306
Chandler Carruth2acfb222013-09-27 22:14:40 +00003307 // Diagnose uses of this specialization.
3308 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3309
Douglas Gregorc40290e2009-03-09 23:48:35 +00003310 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00003311 assert(isa<RecordType>(CanonType) &&
3312 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003313 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3314 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3315 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003316 }
Mike Stump11289f42009-09-09 15:08:12 +00003317
Douglas Gregorc40290e2009-03-09 23:48:35 +00003318 // Build the fully-sugared type for this class template
3319 // specialization, which refers back to the class template
3320 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00003321 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003322}
3323
John McCallfaf5fb42010-08-26 23:41:50 +00003324TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003325Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00003326 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3327 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00003328 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00003329 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00003330 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00003331 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003332 if (SS.isInvalid())
3333 return true;
3334
Richard Smith62559bd2017-02-01 21:36:38 +00003335 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3336 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3337
3338 // C++ [temp.res]p3:
3339 // A qualified-id that refers to a type and in which the
3340 // nested-name-specifier depends on a template-parameter (14.6.2)
3341 // shall be prefixed by the keyword typename to indicate that the
3342 // qualified-id denotes a type, forming an
3343 // elaborated-type-specifier (7.1.5.3).
3344 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00003345 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00003346 << SS.getScopeRep() << TemplateII->getName();
3347 // Recover as if 'typename' were specified.
3348 // FIXME: This is not quite correct recovery as we don't transform SS
3349 // into the corresponding dependent form (and we don't diagnose missing
3350 // 'template' keywords within SS as a result).
3351 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3352 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3353 TemplateArgsIn, RAngleLoc);
3354 }
3355
3356 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3357 // it's not actually allowed to be used as a type in most cases. Because
3358 // we annotate it before we know whether it's valid, we have to check for
3359 // this case here.
3360 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00003361 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3362 Diag(TemplateIILoc,
3363 TemplateKWLoc.isInvalid()
3364 ? diag::err_out_of_line_qualified_id_type_names_constructor
3365 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3366 << TemplateII << 0 /*injected-class-name used as template name*/
3367 << 1 /*if any keyword was present, it was 'template'*/;
3368 }
3369 }
3370
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003371 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00003372
Douglas Gregorc40290e2009-03-09 23:48:35 +00003373 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003374 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003375 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00003376
Douglas Gregor5a064722011-02-28 17:23:35 +00003377 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00003378 QualType T
3379 = Context.getDependentTemplateSpecializationType(ETK_None,
3380 DTN->getQualifier(),
3381 DTN->getIdentifier(),
3382 TemplateArgs);
3383 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00003384 TypeLocBuilder TLB;
3385 DependentTemplateSpecializationTypeLoc SpecTL
3386 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003387 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3388 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003389 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003390 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003391 SpecTL.setLAngleLoc(LAngleLoc);
3392 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003393 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3394 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3395 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3396 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003397
Richard Smith74f02342017-01-19 21:00:13 +00003398 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003399 if (Result.isNull())
3400 return true;
3401
Douglas Gregore7c20652011-03-02 00:47:37 +00003402 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003403 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00003404 TemplateSpecializationTypeLoc SpecTL
3405 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003406 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003407 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003408 SpecTL.setLAngleLoc(LAngleLoc);
3409 SpecTL.setRAngleLoc(RAngleLoc);
3410 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3411 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00003412
Abramo Bagnara4244b432012-01-27 08:46:19 +00003413 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3414 // constructor or destructor name (in such a case, the scope specifier
3415 // will be attached to the enclosing Decl or Expr node).
3416 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003417 // Create an elaborated-type-specifier containing the nested-name-specifier.
3418 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3419 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003420 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00003421 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3422 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003423
Douglas Gregore7c20652011-03-02 00:47:37 +00003424 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00003425}
John McCall06f6fe8d2009-09-04 01:14:41 +00003426
Douglas Gregore7c20652011-03-02 00:47:37 +00003427TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00003428 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00003429 SourceLocation TagLoc,
3430 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003431 SourceLocation TemplateKWLoc,
3432 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00003433 SourceLocation TemplateLoc,
3434 SourceLocation LAngleLoc,
3435 ASTTemplateArgsPtr TemplateArgsIn,
3436 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003437 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003438
Douglas Gregore7c20652011-03-02 00:47:37 +00003439 // Translate the parser's template argument list in our AST format.
3440 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3441 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003442
Douglas Gregore7c20652011-03-02 00:47:37 +00003443 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00003444 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00003445 ElaboratedTypeKeyword Keyword
3446 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00003447
Douglas Gregore7c20652011-03-02 00:47:37 +00003448 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3449 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00003450 DTN->getQualifier(),
3451 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00003452 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003453
3454 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00003455 TypeLocBuilder TLB;
3456 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003457 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3458 SpecTL.setElaboratedKeywordLoc(TagLoc);
3459 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003460 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003461 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003462 SpecTL.setLAngleLoc(LAngleLoc);
3463 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003464 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3465 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3466 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3467 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003468
3469 if (TypeAliasTemplateDecl *TAT =
3470 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3471 // C++0x [dcl.type.elab]p2:
3472 // If the identifier resolves to a typedef-name or the simple-template-id
3473 // resolves to an alias template specialization, the
3474 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003475 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3476 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003477 Diag(TAT->getLocation(), diag::note_declared_at);
3478 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003479
Douglas Gregore7c20652011-03-02 00:47:37 +00003480 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3481 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003482 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003483
Douglas Gregore7c20652011-03-02 00:47:37 +00003484 // Check the tag kind
3485 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003486 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003487
John McCalld8fe9af2009-09-08 17:47:29 +00003488 IdentifierInfo *Id = D->getIdentifier();
3489 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003490
Richard Trieucaa33d32011-06-10 03:11:26 +00003491 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003492 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003493 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003494 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003495 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003496 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003497 }
3498 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003499
Douglas Gregore7c20652011-03-02 00:47:37 +00003500 // Provide source-location information for the template specialization.
3501 TypeLocBuilder TLB;
3502 TemplateSpecializationTypeLoc SpecTL
3503 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003504 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003505 SpecTL.setTemplateNameLoc(TemplateLoc);
3506 SpecTL.setLAngleLoc(LAngleLoc);
3507 SpecTL.setRAngleLoc(RAngleLoc);
3508 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3509 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003510
Douglas Gregore7c20652011-03-02 00:47:37 +00003511 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003512 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003513 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3514 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003515 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003516 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3517 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003518}
3519
Larisse Voufo39a1e502013-08-06 01:03:05 +00003520static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3521 NamedDecl *PrevDecl,
3522 SourceLocation Loc,
3523 bool IsPartialSpecialization);
3524
3525static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003526
Richard Smith300e0c32013-09-24 04:49:23 +00003527static bool isTemplateArgumentTemplateParameter(
3528 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3529 switch (Arg.getKind()) {
3530 case TemplateArgument::Null:
3531 case TemplateArgument::NullPtr:
3532 case TemplateArgument::Integral:
3533 case TemplateArgument::Declaration:
3534 case TemplateArgument::Pack:
3535 case TemplateArgument::TemplateExpansion:
3536 return false;
3537
3538 case TemplateArgument::Type: {
3539 QualType Type = Arg.getAsType();
3540 const TemplateTypeParmType *TPT =
3541 Arg.getAsType()->getAs<TemplateTypeParmType>();
3542 return TPT && !Type.hasQualifiers() &&
3543 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3544 }
3545
3546 case TemplateArgument::Expression: {
3547 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3548 if (!DRE || !DRE->getDecl())
3549 return false;
3550 const NonTypeTemplateParmDecl *NTTP =
3551 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3552 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3553 }
3554
3555 case TemplateArgument::Template:
3556 const TemplateTemplateParmDecl *TTP =
3557 dyn_cast_or_null<TemplateTemplateParmDecl>(
3558 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3559 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3560 }
3561 llvm_unreachable("unexpected kind of template argument");
3562}
3563
3564static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3565 ArrayRef<TemplateArgument> Args) {
3566 if (Params->size() != Args.size())
3567 return false;
3568
3569 unsigned Depth = Params->getDepth();
3570
3571 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3572 TemplateArgument Arg = Args[I];
3573
3574 // If the parameter is a pack expansion, the argument must be a pack
3575 // whose only element is a pack expansion.
3576 if (Params->getParam(I)->isParameterPack()) {
3577 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3578 !Arg.pack_begin()->isPackExpansion())
3579 return false;
3580 Arg = Arg.pack_begin()->getPackExpansionPattern();
3581 }
3582
3583 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3584 return false;
3585 }
3586
3587 return true;
3588}
3589
Richard Smith4b55a9c2014-04-17 03:29:33 +00003590/// Convert the parser's template argument list representation into our form.
3591static TemplateArgumentListInfo
3592makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3593 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3594 TemplateId.RAngleLoc);
3595 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3596 TemplateId.NumArgs);
3597 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3598 return TemplateArgs;
3599}
3600
Richard Smith0e617ec2016-12-27 07:56:27 +00003601template<typename PartialSpecDecl>
3602static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3603 if (Partial->getDeclContext()->isDependentContext())
3604 return;
3605
3606 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3607 // for non-substitution-failure issues?
3608 TemplateDeductionInfo Info(Partial->getLocation());
3609 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3610 return;
3611
3612 auto *Template = Partial->getSpecializedTemplate();
3613 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003614 diag::ext_partial_spec_not_more_specialized_than_primary)
3615 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003616
3617 if (Info.hasSFINAEDiagnostic()) {
3618 PartialDiagnosticAt Diag = {SourceLocation(),
3619 PartialDiagnostic::NullDiagnostic()};
3620 Info.takeSFINAEDiagnostic(Diag);
3621 SmallString<128> SFINAEArgString;
3622 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3623 S.Diag(Diag.first,
3624 diag::note_partial_spec_not_more_specialized_than_primary)
3625 << SFINAEArgString;
3626 }
3627
3628 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3629}
3630
Richard Smith4e05eaa2017-02-16 00:36:47 +00003631static void
3632noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3633 const llvm::SmallBitVector &DeducibleParams) {
3634 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3635 if (!DeducibleParams[I]) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00003636 NamedDecl *Param = TemplateParams->getParam(I);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003637 if (Param->getDeclName())
3638 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3639 << Param->getDeclName();
3640 else
3641 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3642 << "(anonymous)";
3643 }
3644 }
3645}
3646
3647
Richard Smith57aae072016-12-28 02:37:25 +00003648template<typename PartialSpecDecl>
3649static void checkTemplatePartialSpecialization(Sema &S,
3650 PartialSpecDecl *Partial) {
3651 // C++1z [temp.class.spec]p8: (DR1495)
3652 // - The specialization shall be more specialized than the primary
3653 // template (14.5.5.2).
3654 checkMoreSpecializedThanPrimary(S, Partial);
3655
3656 // C++ [temp.class.spec]p8: (DR1315)
3657 // - Each template-parameter shall appear at least once in the
3658 // template-id outside a non-deduced context.
3659 // C++1z [temp.class.spec.match]p3 (P0127R2)
3660 // If the template arguments of a partial specialization cannot be
3661 // deduced because of the structure of its template-parameter-list
3662 // and the template-id, the program is ill-formed.
3663 auto *TemplateParams = Partial->getTemplateParameters();
3664 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3665 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3666 TemplateParams->getDepth(), DeducibleParams);
3667
3668 if (!DeducibleParams.all()) {
3669 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3670 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3671 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3672 << (NumNonDeducible > 1)
3673 << SourceRange(Partial->getLocation(),
3674 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003675 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003676 }
3677}
3678
3679void Sema::CheckTemplatePartialSpecialization(
3680 ClassTemplatePartialSpecializationDecl *Partial) {
3681 checkTemplatePartialSpecialization(*this, Partial);
3682}
3683
3684void Sema::CheckTemplatePartialSpecialization(
3685 VarTemplatePartialSpecializationDecl *Partial) {
3686 checkTemplatePartialSpecialization(*this, Partial);
3687}
3688
Richard Smith4e05eaa2017-02-16 00:36:47 +00003689void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3690 // C++1z [temp.param]p11:
3691 // A template parameter of a deduction guide template that does not have a
3692 // default-argument shall be deducible from the parameter-type-list of the
3693 // deduction guide template.
3694 auto *TemplateParams = TD->getTemplateParameters();
3695 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3696 MarkDeducedTemplateParameters(TD, DeducibleParams);
3697 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3698 // A parameter pack is deducible (to an empty pack).
3699 auto *Param = TemplateParams->getParam(I);
3700 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3701 DeducibleParams[I] = true;
3702 }
3703
3704 if (!DeducibleParams.all()) {
3705 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3706 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3707 << (NumNonDeducible > 1);
3708 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3709 }
3710}
3711
Larisse Voufo39a1e502013-08-06 01:03:05 +00003712DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003713 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003714 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003715 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003716 // D must be variable template id.
Faisal Vali2ab8c152017-12-30 04:15:27 +00003717 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003718 "Variable template specialization is declared with a template it.");
3719
3720 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003721 TemplateArgumentListInfo TemplateArgs =
3722 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003723 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3724 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3725 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003726
Richard Smithbeef3452014-01-16 23:39:20 +00003727 TemplateName Name = TemplateId->Template.get();
3728
3729 // The template-id must name a variable template.
3730 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003731 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3732 if (!VarTemplate) {
3733 NamedDecl *FnTemplate;
3734 if (auto *OTS = Name.getAsOverloadedTemplate())
3735 FnTemplate = *OTS->begin();
3736 else
3737 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3738 if (FnTemplate)
3739 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3740 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003741 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3742 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003743 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003744
3745 // Check for unexpanded parameter packs in any of the template arguments.
3746 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3747 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3748 UPPC_PartialSpecialization))
3749 return true;
3750
3751 // Check that the template argument list is well-formed for this
3752 // template.
3753 SmallVector<TemplateArgument, 4> Converted;
3754 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3755 false, Converted))
3756 return true;
3757
Larisse Voufo39a1e502013-08-06 01:03:05 +00003758 // Find the variable template (partial) specialization declaration that
3759 // corresponds to these arguments.
3760 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003761 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3762 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003763 return true;
3764
Richard Smith57aae072016-12-28 02:37:25 +00003765 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3766 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003767 bool InstantiationDependent;
3768 if (!Name.isDependent() &&
3769 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003770 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003771 InstantiationDependent)) {
3772 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3773 << VarTemplate->getDeclName();
3774 IsPartialSpecialization = false;
3775 }
Richard Smith300e0c32013-09-24 04:49:23 +00003776
3777 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3778 Converted)) {
3779 // C++ [temp.class.spec]p9b3:
3780 //
3781 // -- The argument list of the specialization shall not be identical
3782 // to the implicit argument list of the primary template.
3783 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3784 << /*variable template*/ 1
3785 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3786 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3787 // FIXME: Recover from this by treating the declaration as a redeclaration
3788 // of the primary template.
3789 return true;
3790 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003791 }
3792
Craig Topperc3ec1492014-05-26 06:22:03 +00003793 void *InsertPos = nullptr;
3794 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003795
3796 if (IsPartialSpecialization)
3797 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003798 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003799 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003800 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003801
Craig Topperc3ec1492014-05-26 06:22:03 +00003802 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003803
3804 // Check whether we can declare a variable template specialization in
3805 // the current scope.
3806 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3807 TemplateNameLoc,
3808 IsPartialSpecialization))
3809 return true;
3810
3811 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3812 // Since the only prior variable template specialization with these
3813 // arguments was referenced but not declared, reuse that
3814 // declaration node as our own, updating its source location and
3815 // the list of outer template parameters to reflect our new declaration.
3816 Specialization = PrevDecl;
3817 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003818 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003819 } else if (IsPartialSpecialization) {
3820 // Create a new class template partial specialization declaration node.
3821 VarTemplatePartialSpecializationDecl *PrevPartial =
3822 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003823 VarTemplatePartialSpecializationDecl *Partial =
3824 VarTemplatePartialSpecializationDecl::Create(
3825 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3826 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003827 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003828
3829 if (!PrevPartial)
3830 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3831 Specialization = Partial;
3832
3833 // If we are providing an explicit specialization of a member variable
3834 // template specialization, make a note of that.
3835 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003836 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003837
Richard Smith57aae072016-12-28 02:37:25 +00003838 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003839 } else {
3840 // Create a new class template specialization declaration node for
3841 // this explicit specialization or friend declaration.
3842 Specialization = VarTemplateSpecializationDecl::Create(
3843 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003844 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003845 Specialization->setTemplateArgsInfo(TemplateArgs);
3846
3847 if (!PrevDecl)
3848 VarTemplate->AddSpecialization(Specialization, InsertPos);
3849 }
3850
3851 // C++ [temp.expl.spec]p6:
3852 // If a template, a member template or the member of a class template is
3853 // explicitly specialized then that specialization shall be declared
3854 // before the first use of that specialization that would cause an implicit
3855 // instantiation to take place, in every translation unit in which such a
3856 // use occurs; no diagnostic is required.
3857 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3858 bool Okay = false;
3859 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3860 // Is there any previous explicit specialization declaration?
3861 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3862 Okay = true;
3863 break;
3864 }
3865 }
3866
3867 if (!Okay) {
3868 SourceRange Range(TemplateNameLoc, RAngleLoc);
3869 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3870 << Name << Range;
3871
3872 Diag(PrevDecl->getPointOfInstantiation(),
3873 diag::note_instantiation_required_here)
3874 << (PrevDecl->getTemplateSpecializationKind() !=
3875 TSK_ImplicitInstantiation);
3876 return true;
3877 }
3878 }
3879
3880 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3881 Specialization->setLexicalDeclContext(CurContext);
3882
3883 // Add the specialization into its lexical context, so that it can
3884 // be seen when iterating through the list of declarations in that
3885 // context. However, specializations are not found by name lookup.
3886 CurContext->addDecl(Specialization);
3887
3888 // Note that this is an explicit specialization.
3889 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3890
3891 if (PrevDecl) {
3892 // Check that this isn't a redefinition of this specialization,
3893 // merging with previous declarations.
3894 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00003895 forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003896 PrevSpec.addDecl(PrevDecl);
3897 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003898 } else if (Specialization->isStaticDataMember() &&
3899 Specialization->isOutOfLine()) {
3900 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003901 }
3902
3903 // Link instantiations of static data members back to the template from
3904 // which they were instantiated.
3905 if (Specialization->isStaticDataMember())
3906 Specialization->setInstantiationOfStaticDataMember(
3907 VarTemplate->getTemplatedDecl(),
3908 Specialization->getSpecializationKind());
3909
3910 return Specialization;
3911}
3912
3913namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003914/// A partial specialization whose template arguments have matched
Larisse Voufo39a1e502013-08-06 01:03:05 +00003915/// a given template-id.
3916struct PartialSpecMatchResult {
3917 VarTemplatePartialSpecializationDecl *Partial;
3918 TemplateArgumentList *Args;
3919};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003920} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003921
3922DeclResult
3923Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3924 SourceLocation TemplateNameLoc,
3925 const TemplateArgumentListInfo &TemplateArgs) {
3926 assert(Template && "A variable template id without template?");
3927
3928 // Check that the template argument list is well-formed for this template.
3929 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003930 if (CheckTemplateArgumentList(
3931 Template, TemplateNameLoc,
3932 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003933 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003934 return true;
3935
3936 // Find the variable template specialization declaration that
3937 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003938 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003939 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003940 Converted, InsertPos)) {
3941 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003942 // If we already have a variable template specialization, return it.
3943 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003944 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003945
3946 // This is the first time we have referenced this variable template
3947 // specialization. Create the canonical declaration and add it to
3948 // the set of specializations, based on the closest partial specialization
3949 // that it represents. That is,
3950 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3951 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003952 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003953 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3954 bool AmbiguousPartialSpec = false;
3955 typedef PartialSpecMatchResult MatchResult;
3956 SmallVector<MatchResult, 4> Matched;
3957 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003958 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3959 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003960
3961 // 1. Attempt to find the closest partial specialization that this
3962 // specializes, if any.
3963 // If any of the template arguments is dependent, then this is probably
3964 // a placeholder for an incomplete declarative context; which must be
3965 // complete by instantiation time. Thus, do not search through the partial
3966 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003967 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3968 // Perhaps better after unification of DeduceTemplateArguments() and
3969 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003970 bool InstantiationDependent = false;
3971 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3972 TemplateArgs, InstantiationDependent)) {
3973
3974 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3975 Template->getPartialSpecializations(PartialSpecs);
3976
3977 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3978 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3979 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3980
3981 if (TemplateDeductionResult Result =
3982 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3983 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003984 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003985 FailedCandidates.addCandidate().set(
3986 DeclAccessPair::make(Template, AS_public), Partial,
3987 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003988 (void)Result;
3989 } else {
3990 Matched.push_back(PartialSpecMatchResult());
3991 Matched.back().Partial = Partial;
3992 Matched.back().Args = Info.take();
3993 }
3994 }
3995
Larisse Voufo39a1e502013-08-06 01:03:05 +00003996 if (Matched.size() >= 1) {
3997 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3998 if (Matched.size() == 1) {
3999 // -- If exactly one matching specialization is found, the
4000 // instantiation is generated from that specialization.
4001 // We don't need to do anything for this.
4002 } else {
4003 // -- If more than one matching specialization is found, the
4004 // partial order rules (14.5.4.2) are used to determine
4005 // whether one of the specializations is more specialized
4006 // than the others. If none of the specializations is more
4007 // specialized than all of the other matching
4008 // specializations, then the use of the variable template is
4009 // ambiguous and the program is ill-formed.
4010 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4011 PEnd = Matched.end();
4012 P != PEnd; ++P) {
4013 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4014 PointOfInstantiation) ==
4015 P->Partial)
4016 Best = P;
4017 }
4018
4019 // Determine if the best partial specialization is more specialized than
4020 // the others.
4021 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4022 PEnd = Matched.end();
4023 P != PEnd; ++P) {
4024 if (P != Best && getMoreSpecializedPartialSpecialization(
4025 P->Partial, Best->Partial,
4026 PointOfInstantiation) != Best->Partial) {
4027 AmbiguousPartialSpec = true;
4028 break;
4029 }
4030 }
4031 }
4032
4033 // Instantiate using the best variable template partial specialization.
4034 InstantiationPattern = Best->Partial;
4035 InstantiationArgs = Best->Args;
4036 } else {
4037 // -- If no match is found, the instantiation is generated
4038 // from the primary template.
4039 // InstantiationPattern = Template->getTemplatedDecl();
4040 }
4041 }
4042
Larisse Voufo39a1e502013-08-06 01:03:05 +00004043 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00004044 // Note that we do not instantiate a definition until we see an odr-use
4045 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00004046 // FIXME: LateAttrs et al.?
4047 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4048 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4049 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4050 if (!Decl)
4051 return true;
4052
4053 if (AmbiguousPartialSpec) {
4054 // Partial ordering did not produce a clear winner. Complain.
4055 Decl->setInvalidDecl();
4056 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4057 << Decl;
4058
4059 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00004060 for (MatchResult P : Matched)
4061 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4062 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4063 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004064 return true;
4065 }
4066
4067 if (VarTemplatePartialSpecializationDecl *D =
4068 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4069 Decl->setInstantiationOf(D, InstantiationArgs);
4070
Richard Smith6739a102016-05-05 00:56:12 +00004071 checkSpecializationVisibility(TemplateNameLoc, Decl);
4072
Larisse Voufo39a1e502013-08-06 01:03:05 +00004073 assert(Decl && "No variable template specialization?");
4074 return Decl;
4075}
4076
4077ExprResult
4078Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4079 const DeclarationNameInfo &NameInfo,
4080 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4081 const TemplateArgumentListInfo *TemplateArgs) {
4082
4083 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4084 *TemplateArgs);
4085 if (Decl.isInvalid())
4086 return ExprError();
4087
4088 VarDecl *Var = cast<VarDecl>(Decl.get());
4089 if (!Var->getTemplateSpecializationKind())
4090 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4091 NameInfo.getLoc());
4092
4093 // Build an ordinary singleton decl ref.
4094 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00004095 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004096}
4097
Richard Smithecad88d2018-04-26 01:08:00 +00004098void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4099 SourceLocation Loc) {
4100 Diag(Loc, diag::err_template_missing_args)
4101 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4102 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4103 Diag(TD->getLocation(), diag::note_template_decl_here)
4104 << TD->getTemplateParameters()->getSourceRange();
4105 }
4106}
4107
John McCalldadc5752010-08-24 06:29:42 +00004108ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004109 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00004110 LookupResult &R,
4111 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004112 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00004113 // FIXME: Can we do any checking at this point? I guess we could check the
4114 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00004115 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00004116 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00004117 // foo<int> could identify a single function unambiguously
4118 // This approach does NOT work, since f<int>(1);
4119 // gets resolved prior to resorting to overload resolution
4120 // i.e., template<class T> void f(double);
4121 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00004122
4123 // These should be filtered out by our callers.
4124 assert(!R.empty() && "empty lookup results when building templateid");
4125 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4126
Richard Smith04100942018-04-26 02:10:22 +00004127 // Non-function templates require a template argument list.
4128 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4129 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4130 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4131 return ExprError();
4132 }
4133 }
4134
Richard Smith0bf96f92018-04-25 22:58:55 +00004135 auto AnyDependentArguments = [&]() -> bool {
4136 bool InstantiationDependent;
4137 return TemplateArgs &&
4138 TemplateSpecializationType::anyDependentTemplateArguments(
4139 *TemplateArgs, InstantiationDependent);
4140 };
4141
Larisse Voufo39a1e502013-08-06 01:03:05 +00004142 // In C++1y, check variable template ids.
Richard Smith0bf96f92018-04-25 22:58:55 +00004143 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
Richard Smithd7d11ef2014-02-03 20:09:56 +00004144 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4145 R.getAsSingle<VarTemplateDecl>(),
4146 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004147 }
4148
John McCall58cc69d2010-01-27 01:50:18 +00004149 // We don't want lookup warnings at this point.
4150 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004151
John McCalle66edc12009-11-24 19:00:30 +00004152 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00004153 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00004154 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004155 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004156 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004157 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00004158 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00004159
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004160 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00004161}
4162
John McCalle66edc12009-11-24 19:00:30 +00004163// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00004164ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004165Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004166 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004167 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004168 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004169
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004170 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00004171 DeclContext *DC;
4172 if (!(DC = computeDeclContext(SS, false)) ||
4173 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00004174 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00004175 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004176
Douglas Gregor786123d2010-05-21 23:18:07 +00004177 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004178 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +00004179 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4180 /*Entering*/false, MemberOfUnknownSpecialization,
4181 TemplateKWLoc))
4182 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004183
John McCalle66edc12009-11-24 19:00:30 +00004184 if (R.isAmbiguous())
4185 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004186
John McCalle66edc12009-11-24 19:00:30 +00004187 if (R.empty()) {
Richard Smith79810042018-05-11 02:43:08 +00004188 Diag(NameInfo.getLoc(), diag::err_no_member)
4189 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004190 return ExprError();
4191 }
4192
4193 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004194 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00004195 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00004196 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004197 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4198 return ExprError();
4199 }
4200
Abramo Bagnara7945c982012-01-27 09:46:47 +00004201 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00004202}
4203
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004204/// Form a dependent template name.
Douglas Gregorb67535d2009-03-31 00:43:58 +00004205///
4206/// This action forms a dependent template name given the template
4207/// name and its (presumably dependent) scope specifier. For
4208/// example, given "MetaFun::template apply", the scope specifier \p
4209/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4210/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00004212 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004213 SourceLocation TemplateKWLoc,
Richard Smithc08b6932018-04-27 02:00:13 +00004214 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00004215 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00004216 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00004217 TemplateTy &Result,
4218 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004219 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4220 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004221 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004222 diag::warn_cxx98_compat_template_outside_of_template :
4223 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004224 << FixItHint::CreateRemoval(TemplateKWLoc);
4225
Craig Topperc3ec1492014-05-26 06:22:03 +00004226 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00004227 if (SS.isSet())
4228 LookupCtx = computeDeclContext(SS, EnteringContext);
4229 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00004230 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00004231 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00004232 // C++0x [temp.names]p5:
4233 // If a name prefixed by the keyword template is not the name of
4234 // a template, the program is ill-formed. [Note: the keyword
4235 // template may not be applied to non-template members of class
4236 // templates. -end note ] [ Note: as is the case with the
4237 // typename prefix, the template prefix is allowed in cases
4238 // where it is not strictly necessary; i.e., when the
4239 // nested-name-specifier or the expression on the left of the ->
4240 // or . is not dependent on a template-parameter, or the use
4241 // does not appear in the scope of a template. -end note]
4242 //
4243 // Note: C++03 was more strict here, because it banned the use of
4244 // the "template" keyword prior to a template-name that was not a
4245 // dependent name. C++ DR468 relaxed this requirement (the
4246 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00004247 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00004248 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00004249 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00004250 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00004251 MemberOfUnknownSpecialization);
Richard Smith79810042018-05-11 02:43:08 +00004252 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
Douglas Gregorbb119652010-06-16 23:00:59 +00004253 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00004254 } else if (TNK == TNK_Non_template) {
Richard Smith79810042018-05-11 02:43:08 +00004255 // Do the lookup again to determine if this is a "nothing found" case or
4256 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4257 // need to do this.
4258 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004259 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
Richard Smith79810042018-05-11 02:43:08 +00004260 LookupOrdinaryName);
4261 bool MOUS;
4262 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
4263 MOUS, TemplateKWLoc))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004264 Diag(Name.getBeginLoc(), diag::err_no_member)
Richard Smith79810042018-05-11 02:43:08 +00004265 << DNI.getName() << LookupCtx << SS.getRange();
Douglas Gregorbb119652010-06-16 23:00:59 +00004266 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00004267 } else {
4268 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00004269 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4270 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
Faisal Vali2ab8c152017-12-30 04:15:27 +00004271 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4272 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
Richard Smithfd3dae02017-01-20 00:20:39 +00004273 // C++14 [class.qual]p2:
4274 // In a lookup in which function names are not ignored and the
4275 // nested-name-specifier nominates a class C, if the name specified
4276 // [...] is the injected-class-name of C, [...] the name is instead
4277 // considered to name the constructor
4278 //
4279 // We don't get here if naming the constructor would be valid, so we
4280 // just reject immediately and recover by treating the
4281 // injected-class-name as naming the template.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004282 Diag(Name.getBeginLoc(),
Richard Smithfd3dae02017-01-20 00:20:39 +00004283 diag::ext_out_of_line_qualified_id_type_names_constructor)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004284 << Name.Identifier
4285 << 0 /*injected-class-name used as template name*/
4286 << 1 /*'template' keyword was used*/;
Richard Smithfd3dae02017-01-20 00:20:39 +00004287 }
Douglas Gregorbb119652010-06-16 23:00:59 +00004288 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004289 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00004290 }
4291
Aaron Ballman4a979672014-01-03 13:56:08 +00004292 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293
Douglas Gregor3cf81312009-11-03 23:16:33 +00004294 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00004295 case UnqualifiedIdKind::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00004297 Name.Identifier));
4298 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
Faisal Vali2ab8c152017-12-30 04:15:27 +00004300 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00004301 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00004302 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00004303 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00004304
Faisal Vali2ab8c152017-12-30 04:15:27 +00004305 case UnqualifiedIdKind::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00004306 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00004307
Douglas Gregor3cf81312009-11-03 23:16:33 +00004308 default:
4309 break;
4310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004311
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004312 Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4313 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4314 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004315 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004316}
4317
Mike Stump11289f42009-09-09 15:08:12 +00004318bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004319 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004320 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00004321 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00004322 QualType ArgType;
4323 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00004324
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004325 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004326 switch(Arg.getKind()) {
4327 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004328 // C++ [temp.arg.type]p1:
4329 // A template-argument for a template-parameter which is a
4330 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00004331 ArgType = Arg.getAsType();
4332 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004333 break;
Richard Smith77a9c602018-02-28 03:02:23 +00004334 case TemplateArgument::Template:
4335 case TemplateArgument::TemplateExpansion: {
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004336 // We have a template type parameter but the template argument
4337 // is a template without any arguments.
4338 SourceRange SR = AL.getSourceRange();
Richard Smith77a9c602018-02-28 03:02:23 +00004339 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
Richard Smithecad88d2018-04-26 01:08:00 +00004340 diagnoseMissingTemplateArguments(Name, SR.getEnd());
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004341 return true;
4342 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004343 case TemplateArgument::Expression: {
4344 // We have a template type parameter but the template argument is an
4345 // expression; see if maybe it is missing the "typename" keyword.
4346 CXXScopeSpec SS;
4347 DeclarationNameInfo NameInfo;
4348
4349 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4350 SS.Adopt(ArgExpr->getQualifierLoc());
4351 NameInfo = ArgExpr->getNameInfo();
4352 } else if (DependentScopeDeclRefExpr *ArgExpr =
4353 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4354 SS.Adopt(ArgExpr->getQualifierLoc());
4355 NameInfo = ArgExpr->getNameInfo();
4356 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4357 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004358 if (ArgExpr->isImplicitAccess()) {
4359 SS.Adopt(ArgExpr->getQualifierLoc());
4360 NameInfo = ArgExpr->getMemberNameInfo();
4361 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004362 }
4363
Reid Kleckner377c1592014-06-10 23:29:48 +00004364 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004365 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4366 LookupParsedName(Result, CurScope, &SS);
4367
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004368 if (Result.getAsSingle<TypeDecl>() ||
4369 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00004370 LookupResult::NotFoundInCurrentInstantiation) {
4371 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004372 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00004373 Diag(Loc, getLangOpts().MSVCCompat
4374 ? diag::ext_ms_template_type_arg_missing_typename
4375 : diag::err_template_arg_must_be_type_suggest)
4376 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004377 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00004378
4379 // Recover by synthesizing a type using the location information that we
4380 // already have.
4381 ArgType =
4382 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4383 TypeLocBuilder TLB;
4384 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4385 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4386 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4387 TL.setNameLoc(NameInfo.getLoc());
4388 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4389
4390 // Overwrite our input TemplateArgumentLoc so that we can recover
4391 // properly.
4392 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4393 TemplateArgumentLocInfo(TSI));
4394
4395 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004396 }
4397 }
4398 // fallthrough
Galina Kistanova3779cb32017-06-07 06:25:05 +00004399 LLVM_FALLTHROUGH;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004400 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004401 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004402 // We have a template type parameter but the template argument
4403 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00004404 SourceRange SR = AL.getSourceRange();
4405 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004406 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00004407
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004408 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004409 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004410 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004411
Reid Kleckner377c1592014-06-10 23:29:48 +00004412 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004413 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004414
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004415 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00004416 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004417
Douglas Gregore46db902011-06-17 22:11:49 +00004418 // Objective-C ARC:
4419 // If an explicitly-specified template argument type is a lifetime type
4420 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004421 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00004422 ArgType->isObjCLifetimeType() &&
4423 !ArgType.getObjCLifetime()) {
4424 Qualifiers Qs;
4425 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4426 ArgType = Context.getQualifiedType(ArgType, Qs);
4427 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004428
Douglas Gregore46db902011-06-17 22:11:49 +00004429 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004430 return false;
4431}
4432
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004433/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004434/// the given template type parameter.
4435///
4436/// \param SemaRef the semantic analysis object for which we are performing
4437/// the substitution.
4438///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004440/// for.
4441///
4442/// \param TemplateLoc the location of the template name that started the
4443/// template-id we are checking.
4444///
4445/// \param RAngleLoc the location of the right angle bracket ('>') that
4446/// terminates the template-id.
4447///
4448/// \param Param the template template parameter whose default we are
4449/// substituting into.
4450///
4451/// \param Converted the list of template arguments provided for template
4452/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004453/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00004454static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004455SubstDefaultTemplateArgument(Sema &SemaRef,
4456 TemplateDecl *Template,
4457 SourceLocation TemplateLoc,
4458 SourceLocation RAngleLoc,
4459 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00004460 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00004461 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004462
4463 // If the argument type is dependent, instantiate it now based
4464 // on the previously-computed template arguments.
Erik Pilkingtonba88e212018-11-12 21:31:06 +00004465 if (ArgType->getType()->isInstantiationDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004466 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004467 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004468 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004469 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004470 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004471
David Majnemer8b622692016-07-03 21:17:51 +00004472 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004473
4474 // Only substitute for the innermost template argument list.
4475 MultiLevelTemplateArgumentList TemplateArgLists;
4476 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4477 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4478 TemplateArgLists.addOuterTemplateArguments(None);
4479
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004480 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004481 ArgType =
4482 SemaRef.SubstType(ArgType, TemplateArgLists,
4483 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004484 }
4485
4486 return ArgType;
4487}
4488
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004489/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004490/// the given non-type template parameter.
4491///
4492/// \param SemaRef the semantic analysis object for which we are performing
4493/// the substitution.
4494///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004495/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004496/// for.
4497///
4498/// \param TemplateLoc the location of the template name that started the
4499/// template-id we are checking.
4500///
4501/// \param RAngleLoc the location of the right angle bracket ('>') that
4502/// terminates the template-id.
4503///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004504/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004505/// substituting into.
4506///
4507/// \param Converted the list of template arguments provided for template
4508/// parameters that precede \p Param in the template parameter list.
4509///
4510/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004511static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004512SubstDefaultTemplateArgument(Sema &SemaRef,
4513 TemplateDecl *Template,
4514 SourceLocation TemplateLoc,
4515 SourceLocation RAngleLoc,
4516 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004517 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004518 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004519 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004520 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004521 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004522 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004523
David Majnemer8b622692016-07-03 21:17:51 +00004524 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004525
4526 // Only substitute for the innermost template argument list.
4527 MultiLevelTemplateArgumentList TemplateArgLists;
4528 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4529 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4530 TemplateArgLists.addOuterTemplateArguments(None);
4531
Faisal Valid143a0c2017-04-01 21:30:49 +00004532 EnterExpressionEvaluationContext ConstantEvaluated(
4533 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004534 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004535}
4536
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004537/// Substitute template arguments into the default template argument for
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004538/// the given template template parameter.
4539///
4540/// \param SemaRef the semantic analysis object for which we are performing
4541/// the substitution.
4542///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004543/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004544/// for.
4545///
4546/// \param TemplateLoc the location of the template name that started the
4547/// template-id we are checking.
4548///
4549/// \param RAngleLoc the location of the right angle bracket ('>') that
4550/// terminates the template-id.
4551///
4552/// \param Param the template template parameter whose default we are
4553/// substituting into.
4554///
4555/// \param Converted the list of template arguments provided for template
4556/// parameters that precede \p Param in the template parameter list.
4557///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004558/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004559/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004560///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004561/// \returns the substituted template argument, or NULL if an error occurred.
4562static TemplateName
4563SubstDefaultTemplateArgument(Sema &SemaRef,
4564 TemplateDecl *Template,
4565 SourceLocation TemplateLoc,
4566 SourceLocation RAngleLoc,
4567 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004568 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004569 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004570 Sema::InstantiatingTemplate Inst(
4571 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4572 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004573 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004574 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575
David Majnemer8b622692016-07-03 21:17:51 +00004576 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004577
4578 // Only substitute for the innermost template argument list.
4579 MultiLevelTemplateArgumentList TemplateArgLists;
4580 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4581 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4582 TemplateArgLists.addOuterTemplateArguments(None);
4583
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004584 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004585 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004586 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004587 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004588 QualifierLoc =
4589 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004590 if (!QualifierLoc)
4591 return TemplateName();
4592 }
David Majnemer89189202013-08-28 23:48:32 +00004593
4594 return SemaRef.SubstTemplateName(
4595 QualifierLoc,
4596 Param->getDefaultArgument().getArgument().getAsTemplate(),
4597 Param->getDefaultArgument().getTemplateNameLoc(),
4598 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004599}
4600
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004601/// If the given template parameter has a default template
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004602/// argument, substitute into that default template argument and
4603/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004604TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004605Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4606 SourceLocation TemplateLoc,
4607 SourceLocation RAngleLoc,
4608 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004609 SmallVectorImpl<TemplateArgument>
4610 &Converted,
4611 bool &HasDefaultArg) {
4612 HasDefaultArg = false;
4613
4614 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004615 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004616 return TemplateArgumentLoc();
4617
Richard Smithc87b9382013-07-04 01:01:24 +00004618 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004619 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004620 TemplateLoc,
4621 RAngleLoc,
4622 TypeParm,
4623 Converted);
4624 if (DI)
4625 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4626
4627 return TemplateArgumentLoc();
4628 }
4629
4630 if (NonTypeTemplateParmDecl *NonTypeParm
4631 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004632 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004633 return TemplateArgumentLoc();
4634
Richard Smithc87b9382013-07-04 01:01:24 +00004635 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004636 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004637 TemplateLoc,
4638 RAngleLoc,
4639 NonTypeParm,
4640 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004641 if (Arg.isInvalid())
4642 return TemplateArgumentLoc();
4643
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004644 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004645 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4646 }
4647
4648 TemplateTemplateParmDecl *TempTempParm
4649 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004650 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004651 return TemplateArgumentLoc();
4652
Richard Smithc87b9382013-07-04 01:01:24 +00004653 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004654 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004655 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004656 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004657 RAngleLoc,
4658 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004659 Converted,
4660 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004661 if (TName.isNull())
4662 return TemplateArgumentLoc();
4663
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004664 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004665 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004666 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4667}
4668
Richard Smith11255ec2017-01-18 19:19:22 +00004669/// Convert a template-argument that we parsed as a type into a template, if
4670/// possible. C++ permits injected-class-names to perform dual service as
4671/// template template arguments and as template type arguments.
4672static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4673 // Extract and step over any surrounding nested-name-specifier.
4674 NestedNameSpecifierLoc QualLoc;
4675 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4676 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4677 return TemplateArgumentLoc();
4678
4679 QualLoc = ETLoc.getQualifierLoc();
4680 TLoc = ETLoc.getNamedTypeLoc();
4681 }
4682
4683 // If this type was written as an injected-class-name, it can be used as a
4684 // template template argument.
4685 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4686 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4687 QualLoc, InjLoc.getNameLoc());
4688
4689 // If this type was written as an injected-class-name, it may have been
4690 // converted to a RecordType during instantiation. If the RecordType is
4691 // *not* wrapped in a TemplateSpecializationType and denotes a class
4692 // template specialization, it must have come from an injected-class-name.
4693 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4694 if (auto *CTSD =
4695 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4696 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4697 QualLoc, RecLoc.getNameLoc());
4698
4699 return TemplateArgumentLoc();
4700}
4701
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004702/// Check that the given template argument corresponds to the given
Douglas Gregorda0fb532009-11-11 19:31:23 +00004703/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004704///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004705/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004706/// checked.
4707///
Richard Trieu15b66532015-01-24 02:48:32 +00004708/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004709///
4710/// \param Template The template in which the template argument resides.
4711///
4712/// \param TemplateLoc The location of the template name for the template
4713/// whose argument list we're matching.
4714///
4715/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4716/// the template argument list.
4717///
4718/// \param ArgumentPackIndex The index into the argument pack where this
4719/// argument will be placed. Only valid if the parameter is a parameter pack.
4720///
4721/// \param Converted The checked, converted argument will be added to the
4722/// end of this small vector.
4723///
4724/// \param CTAK Describes how we arrived at this particular template argument:
4725/// explicitly written, deduced, etc.
4726///
4727/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004728bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004729 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004730 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004731 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004732 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004733 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004734 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004735 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004736 // Check template type parameters.
4737 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004738 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004739
Douglas Gregoreebed722009-11-11 19:41:09 +00004740 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004741 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004742 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004743 // with the template arguments we've seen thus far. But if the
4744 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004745 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004746 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4747 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004748
Richard Smith5d331022018-03-08 01:07:33 +00004749 // FIXME: Do we need to substitute into parameters here if they're
4750 // instantiation-dependent but not dependent?
Peter Collingbourne01687632010-12-10 17:08:53 +00004751 if (NTTPType->isDependentType() &&
4752 !isa<TemplateTemplateParmDecl>(Template) &&
4753 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004754 // Do substitution on the type of the non-type template parameter.
4755 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004756 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004757 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004758 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004759 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760
4761 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004762 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004763 NTTPType = SubstType(NTTPType,
4764 MultiLevelTemplateArgumentList(TemplateArgs),
4765 NTTP->getLocation(),
4766 NTTP->getDeclName());
4767 // If that worked, check the non-type template parameter type
4768 // for validity.
4769 if (!NTTPType.isNull())
4770 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4771 NTTP->getLocation());
4772 if (NTTPType.isNull())
4773 return true;
4774 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004775
Douglas Gregorda0fb532009-11-11 19:31:23 +00004776 switch (Arg.getArgument().getKind()) {
4777 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004778 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004779
Douglas Gregorda0fb532009-11-11 19:31:23 +00004780 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004781 TemplateArgument Result;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004782 unsigned CurSFINAEErrors = NumSFINAEErrors;
John Wiegley01296292011-04-08 18:41:53 +00004783 ExprResult Res =
4784 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4785 Result, CTAK);
4786 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004787 return true;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004788 // If the current template argument causes an error, give up now.
4789 if (CurSFINAEErrors < NumSFINAEErrors)
4790 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004791
Richard Trieu15b66532015-01-24 02:48:32 +00004792 // If the resulting expression is new, then use it in place of the
4793 // old expression in the template argument.
4794 if (Res.get() != Arg.getArgument().getAsExpr()) {
4795 TemplateArgument TA(Res.get());
4796 Arg = TemplateArgumentLoc(TA, Res.get());
4797 }
4798
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004799 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004800 break;
4801 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004802
Douglas Gregorda0fb532009-11-11 19:31:23 +00004803 case TemplateArgument::Declaration:
4804 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004805 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004806 // We've already checked this template argument, so just copy
4807 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004808 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004809 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004810
Douglas Gregorda0fb532009-11-11 19:31:23 +00004811 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004812 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004813 // We were given a template template argument. It may not be ill-formed;
4814 // see below.
4815 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004816 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4817 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004818 // We have a template argument such as \c T::template X, which we
4819 // parsed as a template template argument. However, since we now
4820 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004821 // template name into an expression.
4822
4823 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4824 Arg.getTemplateNameLoc());
4825
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004826 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004827 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004828 // FIXME: the template-template arg was a DependentTemplateName,
4829 // so it was provided with a template keyword. However, its source
4830 // location is not stored in the template argument structure.
4831 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004832 ExprResult E = DependentScopeDeclRefExpr::Create(
4833 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4834 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004835
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004836 // If we parsed the template argument as a pack expansion, create a
4837 // pack expansion expression.
4838 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004839 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004840 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004841 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004843
Douglas Gregorda0fb532009-11-11 19:31:23 +00004844 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004845 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004846 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004847 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004848
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004849 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004850 break;
4851 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004852
Douglas Gregorda0fb532009-11-11 19:31:23 +00004853 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004854 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004855 // therefore cannot be a non-type template argument.
4856 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4857 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004858
Douglas Gregorda0fb532009-11-11 19:31:23 +00004859 Diag(Param->getLocation(), diag::note_template_param_here);
4860 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004861
Douglas Gregorda0fb532009-11-11 19:31:23 +00004862 case TemplateArgument::Type: {
4863 // We have a non-type template parameter but the template
4864 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004865
Douglas Gregorda0fb532009-11-11 19:31:23 +00004866 // C++ [temp.arg]p2:
4867 // In a template-argument, an ambiguity between a type-id and
4868 // an expression is resolved to a type-id, regardless of the
4869 // form of the corresponding template-parameter.
4870 //
4871 // We warn specifically about this case, since it can be rather
4872 // confusing for users.
4873 QualType T = Arg.getArgument().getAsType();
4874 SourceRange SR = Arg.getSourceRange();
4875 if (T->isFunctionType())
4876 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4877 else
4878 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4879 Diag(Param->getLocation(), diag::note_template_param_here);
4880 return true;
4881 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004882
Douglas Gregorda0fb532009-11-11 19:31:23 +00004883 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004884 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004885 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004886
Douglas Gregorda0fb532009-11-11 19:31:23 +00004887 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004888 }
4889
4890
Douglas Gregorda0fb532009-11-11 19:31:23 +00004891 // Check template template parameters.
4892 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004893
Richard Smith5d331022018-03-08 01:07:33 +00004894 TemplateParameterList *Params = TempParm->getTemplateParameters();
4895 if (TempParm->isExpandedParameterPack())
4896 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
4897
Douglas Gregorda0fb532009-11-11 19:31:23 +00004898 // Substitute into the template parameter list of the template
4899 // template parameter, since previously-supplied template arguments
4900 // may appear within the template template parameter.
Richard Smith5d331022018-03-08 01:07:33 +00004901 //
4902 // FIXME: Skip this if the parameters aren't instantiation-dependent.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004903 {
4904 // Set up a template instantiation context.
4905 LocalInstantiationScope Scope(*this);
4906 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004907 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004908 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004909 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004910 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911
David Majnemer8b622692016-07-03 21:17:51 +00004912 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Richard Smith5d331022018-03-08 01:07:33 +00004913 Params = SubstTemplateParams(Params, CurContext,
4914 MultiLevelTemplateArgumentList(TemplateArgs));
4915 if (!Params)
Douglas Gregorda0fb532009-11-11 19:31:23 +00004916 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004918
Richard Smith11255ec2017-01-18 19:19:22 +00004919 // C++1z [temp.local]p1: (DR1004)
4920 // When [the injected-class-name] is used [...] as a template-argument for
4921 // a template template-parameter [...] it refers to the class template
4922 // itself.
4923 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4924 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4925 Arg.getTypeSourceInfo()->getTypeLoc());
4926 if (!ConvertedArg.getArgument().isNull())
4927 Arg = ConvertedArg;
4928 }
4929
Douglas Gregorda0fb532009-11-11 19:31:23 +00004930 switch (Arg.getArgument().getKind()) {
4931 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004932 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004933
Douglas Gregorda0fb532009-11-11 19:31:23 +00004934 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004935 case TemplateArgument::TemplateExpansion:
Richard Smith5d331022018-03-08 01:07:33 +00004936 if (CheckTemplateTemplateArgument(Params, Arg))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004937 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004938
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004939 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004940 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004941
Douglas Gregorda0fb532009-11-11 19:31:23 +00004942 case TemplateArgument::Expression:
4943 case TemplateArgument::Type:
4944 // We have a template template parameter but the template
4945 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004946 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004947 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004948 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004949
Douglas Gregorda0fb532009-11-11 19:31:23 +00004950 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004951 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004952 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004953 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004954 case TemplateArgument::NullPtr:
4955 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004956
Douglas Gregorda0fb532009-11-11 19:31:23 +00004957 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004958 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004959 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004960
Douglas Gregorda0fb532009-11-11 19:31:23 +00004961 return false;
4962}
4963
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004964/// Check whether the template parameter is a pack expansion, and if so,
Richard Smith1fde8ec2012-09-07 02:06:42 +00004965/// determine the number of parameters produced by that expansion. For instance:
4966///
4967/// \code
4968/// template<typename ...Ts> struct A {
4969/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4970/// };
4971/// \endcode
4972///
4973/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4974/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004975static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004976 if (NonTypeTemplateParmDecl *NTTP
4977 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4978 if (NTTP->isExpandedParameterPack())
4979 return NTTP->getNumExpansionTypes();
4980 }
4981
4982 if (TemplateTemplateParmDecl *TTP
4983 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4984 if (TTP->isExpandedParameterPack())
4985 return TTP->getNumExpansionTemplateParameters();
4986 }
4987
David Blaikie7a30dc52013-02-21 01:47:18 +00004988 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00004989}
4990
Richard Smith35c1df52015-06-17 20:16:32 +00004991/// Diagnose a missing template argument.
4992template<typename TemplateParmDecl>
4993static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4994 TemplateDecl *TD,
4995 const TemplateParmDecl *D,
4996 TemplateArgumentListInfo &Args) {
4997 // Dig out the most recent declaration of the template parameter; there may be
4998 // declarations of the template that are more recent than TD.
4999 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5000 ->getTemplateParameters()
5001 ->getParam(D->getIndex()));
5002
5003 // If there's a default argument that's not visible, diagnose that we're
5004 // missing a module import.
5005 llvm::SmallVector<Module*, 8> Modules;
5006 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5007 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5008 D->getDefaultArgumentLoc(), Modules,
5009 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00005010 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00005011 return true;
5012 }
5013
5014 // FIXME: If there's a more recent default argument that *is* visible,
5015 // diagnose that it was declared too late.
5016
Richard Smith4a8f3512018-07-19 19:00:37 +00005017 TemplateParameterList *Params = TD->getTemplateParameters();
5018
5019 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5020 << /*not enough args*/0
5021 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5022 << TD;
5023 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5024 << Params->getSourceRange();
5025 return true;
Richard Smith35c1df52015-06-17 20:16:32 +00005026}
5027
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005028/// Check that the given template argument list is well-formed
Douglas Gregord32e0282009-02-09 23:23:08 +00005029/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00005030bool Sema::CheckTemplateArgumentList(
5031 TemplateDecl *Template, SourceLocation TemplateLoc,
5032 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5033 SmallVectorImpl<TemplateArgument> &Converted,
5034 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00005035 // Make a copy of the template arguments for processing. Only make the
5036 // changes at the end when successful in matching the arguments to the
5037 // template.
5038 TemplateArgumentListInfo NewArgs = TemplateArgs;
5039
Erich Keaneaf0795b2017-10-24 01:39:56 +00005040 // Make sure we get the template parameter list from the most
5041 // recentdeclaration, since that is the only one that has is guaranteed to
5042 // have all the default template argument information.
5043 TemplateParameterList *Params =
5044 cast<TemplateDecl>(Template->getMostRecentDecl())
5045 ->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00005046
Richard Trieu15b66532015-01-24 02:48:32 +00005047 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00005048
Mike Stump11289f42009-09-09 15:08:12 +00005049 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00005050 // [...] The type and form of each template-argument specified in
5051 // a template-id shall match the type and form specified for the
5052 // corresponding parameter declared by the template in its
5053 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00005054 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005055 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00005056 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00005057 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00005058 for (TemplateParameterList::iterator Param = Params->begin(),
5059 ParamEnd = Params->end();
5060 Param != ParamEnd; /* increment in loop */) {
5061 // If we have an expanded parameter pack, make sure we don't have too
5062 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00005063 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005064 if (*Expansions == ArgumentPack.size()) {
5065 // We're done with this parameter pack. Pack up its arguments and add
5066 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00005067 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00005068 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005069 ArgumentPack.clear();
5070
Richard Smith1fde8ec2012-09-07 02:06:42 +00005071 // This argument is assigned to the next parameter.
5072 ++Param;
5073 continue;
5074 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5075 // Not enough arguments for this parameter pack.
5076 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
Richard Smith4a8f3512018-07-19 19:00:37 +00005077 << /*not enough args*/0
Richard Smith0c062b42017-01-14 02:19:59 +00005078 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00005079 << Template;
5080 Diag(Template->getLocation(), diag::note_template_decl_here)
5081 << Params->getSourceRange();
5082 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005083 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005084 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005085
Richard Smith1fde8ec2012-09-07 02:06:42 +00005086 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00005087 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00005088 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005089 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005090 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00005091 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005092
Richard Smith96d71c32014-11-12 23:38:38 +00005093 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00005094 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00005095 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5096 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00005097 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00005098 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00005099 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00005100 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00005101 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00005102 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00005103 Diag((*Param)->getLocation(), diag::note_template_param_here);
5104 return true;
5105 }
5106
Richard Smith1fde8ec2012-09-07 02:06:42 +00005107 // We're now done with this argument.
5108 ++ArgIdx;
5109
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005110 if ((*Param)->isTemplateParameterPack()) {
5111 // The template parameter was a template parameter pack, so take the
5112 // deduced argument and place it on the argument pack. Note that we
5113 // stay on the same template parameter so that we can deduce more
5114 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00005115 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005116 } else {
5117 // Move to the next template parameter.
5118 ++Param;
5119 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005120
Richard Smith96d71c32014-11-12 23:38:38 +00005121 // If we just saw a pack expansion into a non-pack, then directly convert
5122 // the remaining arguments, because we don't know what parameters they'll
5123 // match up with.
5124 if (PackExpansionIntoNonPack) {
5125 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005126 // If we were part way through filling in an expanded parameter pack,
5127 // fall back to just producing individual arguments.
5128 Converted.insert(Converted.end(),
5129 ArgumentPack.begin(), ArgumentPack.end());
5130 ArgumentPack.clear();
5131 }
5132
5133 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00005134 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00005135 ++ArgIdx;
5136 }
5137
Richard Smith1fde8ec2012-09-07 02:06:42 +00005138 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00005139 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005140
Douglas Gregor84d49a22009-11-11 21:54:23 +00005141 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005142 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005143
Douglas Gregor2f157c92011-06-03 02:59:40 +00005144 // If we're checking a partial template argument list, we're done.
5145 if (PartialTemplateArgs) {
5146 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00005147 Converted.push_back(
5148 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5149
Richard Smith1fde8ec2012-09-07 02:06:42 +00005150 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00005151 }
5152
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005153 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005154 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00005155 if ((*Param)->isTemplateParameterPack()) {
5156 assert(!getExpandedPackSize(*Param) &&
5157 "Should have dealt with this already");
5158
5159 // A non-expanded parameter pack before the end of the parameter list
5160 // only occurs for an ill-formed template parameter list, unless we've
5161 // got a partial argument list for a function template, so just bail out.
5162 if (Param + 1 != ParamEnd)
5163 return true;
5164
Benjamin Kramercce63472015-08-05 09:40:22 +00005165 Converted.push_back(
5166 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005167 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00005168
5169 ++Param;
5170 continue;
5171 }
5172
Douglas Gregor8e072612012-02-03 07:34:46 +00005173 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00005174 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005175
Douglas Gregor84d49a22009-11-11 21:54:23 +00005176 // Retrieve the default template argument from the template
5177 // parameter. For each kind of template parameter, we substitute the
5178 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005179 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00005180 // the default argument.
5181 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005182 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005183 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5184 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005185
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005186 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005187 Template,
5188 TemplateLoc,
5189 RAngleLoc,
5190 TTP,
5191 Converted);
5192 if (!ArgType)
5193 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005194
Douglas Gregor84d49a22009-11-11 21:54:23 +00005195 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5196 ArgType);
5197 } else if (NonTypeTemplateParmDecl *NTTP
5198 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005199 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005200 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5201 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005202
John McCalldadc5752010-08-24 06:29:42 +00005203 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005204 TemplateLoc,
5205 RAngleLoc,
5206 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005207 Converted);
5208 if (E.isInvalid())
5209 return true;
5210
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005211 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00005212 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5213 } else {
5214 TemplateTemplateParmDecl *TempParm
5215 = cast<TemplateTemplateParmDecl>(*Param);
5216
Richard Smith95d83952015-06-10 20:36:34 +00005217 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00005218 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5219 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005220
Douglas Gregordf846d12011-03-02 18:46:51 +00005221 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00005222 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005223 TemplateLoc,
5224 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005225 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00005226 Converted,
5227 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005228 if (Name.isNull())
5229 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005230
Douglas Gregor9d802122011-03-02 17:09:35 +00005231 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5232 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00005233 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005234
Douglas Gregor84d49a22009-11-11 21:54:23 +00005235 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00005236 // the default template argument. We're not actually instantiating a
5237 // template here, we just create this object to put a note into the
5238 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00005239 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5240 SourceRange(TemplateLoc, RAngleLoc));
5241 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005242 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005243
Douglas Gregor84d49a22009-11-11 21:54:23 +00005244 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00005245 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005246 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005247 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005248
Richard Trieu15b66532015-01-24 02:48:32 +00005249 // Core issue 150 (assumed resolution): if this is a template template
5250 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00005251 // template definition.
5252 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00005253 NewArgs.addArgument(Arg);
5254
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005255 // Move to the next template parameter and argument.
5256 ++Param;
5257 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00005258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005259
Richard Smith07f79912014-06-06 16:00:50 +00005260 // If we're performing a partial argument substitution, allow any trailing
5261 // pack expansions; they might be empty. This can happen even if
5262 // PartialTemplateArgs is false (the list of arguments is complete but
5263 // still dependent).
5264 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5265 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00005266 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5267 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00005268 }
5269
Douglas Gregor8e072612012-02-03 07:34:46 +00005270 // If we have any leftover arguments, then there were too many arguments.
5271 // Complain and fail.
Richard Smith4a8f3512018-07-19 19:00:37 +00005272 if (ArgIdx < NumArgs) {
5273 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5274 << /*too many args*/1
5275 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5276 << Template
5277 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5278 Diag(Template->getLocation(), diag::note_template_decl_here)
5279 << Params->getSourceRange();
5280 return true;
5281 }
Richard Trieu15b66532015-01-24 02:48:32 +00005282
5283 // No problems found with the new argument list, propagate changes back
5284 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00005285 if (UpdateArgsWithConversions)
5286 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005287
Richard Smith1fde8ec2012-09-07 02:06:42 +00005288 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00005289}
5290
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005291namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005292 class UnnamedLocalNoLinkageFinder
5293 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005294 {
5295 Sema &S;
5296 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005297
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005298 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005299
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005300 public:
5301 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5302
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005303 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00005304 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005305 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005306
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005307#define TYPE(Class, Parent) \
5308 bool Visit##Class##Type(const Class##Type *);
5309#define ABSTRACT_TYPE(Class, Parent) \
5310 bool Visit##Class##Type(const Class##Type *) { return false; }
5311#define NON_CANONICAL_TYPE(Class, Parent) \
5312 bool Visit##Class##Type(const Class##Type *) { return false; }
5313#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005314
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005315 bool VisitTagDecl(const TagDecl *Tag);
5316 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5317 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005318} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005319
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005320bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005321 return false;
5322}
5323
5324bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5325 return Visit(T->getElementType());
5326}
5327
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005328bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005329 return Visit(T->getPointeeType());
5330}
5331
5332bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005333 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005334 return Visit(T->getPointeeType());
5335}
5336
5337bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005338 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005339 return Visit(T->getPointeeType());
5340}
5341
5342bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005343 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005344 return Visit(T->getPointeeType());
5345}
5346
5347bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005348 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005349 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5350}
5351
5352bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005353 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005354 return Visit(T->getElementType());
5355}
5356
5357bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005358 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005359 return Visit(T->getElementType());
5360}
5361
5362bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005363 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005364 return Visit(T->getElementType());
5365}
5366
5367bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005368 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005369 return Visit(T->getElementType());
5370}
5371
5372bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005373 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005374 return Visit(T->getElementType());
5375}
5376
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005377bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5378 const DependentAddressSpaceType *T) {
5379 return Visit(T->getPointeeType());
5380}
5381
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005382bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5383 return Visit(T->getElementType());
5384}
5385
Erich Keanef702b022018-07-13 19:46:04 +00005386bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5387 const DependentVectorType *T) {
5388 return Visit(T->getElementType());
5389}
5390
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005391bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5392 return Visit(T->getElementType());
5393}
5394
5395bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5396 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005397 for (const auto &A : T->param_types()) {
5398 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005399 return true;
5400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005401
Alp Toker314cc812014-01-25 16:55:45 +00005402 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005403}
5404
5405bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5406 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00005407 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005408}
5409
5410bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5411 const UnresolvedUsingType*) {
5412 return false;
5413}
5414
5415bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5416 return false;
5417}
5418
5419bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5420 return Visit(T->getUnderlyingType());
5421}
5422
5423bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5424 return false;
5425}
5426
Alexis Hunte852b102011-05-24 22:41:36 +00005427bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5428 const UnaryTransformType*) {
5429 return false;
5430}
5431
Richard Smith30482bc2011-02-20 03:19:35 +00005432bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5433 return Visit(T->getDeducedType());
5434}
5435
Richard Smith600b5262017-01-26 20:40:47 +00005436bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5437 const DeducedTemplateSpecializationType *T) {
5438 return Visit(T->getDeducedType());
5439}
5440
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005441bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5442 return VisitTagDecl(T->getDecl());
5443}
5444
5445bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5446 return VisitTagDecl(T->getDecl());
5447}
5448
5449bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5450 const TemplateTypeParmType*) {
5451 return false;
5452}
5453
Douglas Gregorada4b792011-01-14 02:55:32 +00005454bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5455 const SubstTemplateTypeParmPackType *) {
5456 return false;
5457}
5458
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005459bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5460 const TemplateSpecializationType*) {
5461 return false;
5462}
5463
5464bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5465 const InjectedClassNameType* T) {
5466 return VisitTagDecl(T->getDecl());
5467}
5468
5469bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5470 const DependentNameType* T) {
5471 return VisitNestedNameSpecifier(T->getQualifier());
5472}
5473
5474bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5475 const DependentTemplateSpecializationType* T) {
5476 return VisitNestedNameSpecifier(T->getQualifier());
5477}
5478
Douglas Gregord2fa7662010-12-20 02:24:11 +00005479bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5480 const PackExpansionType* T) {
5481 return Visit(T->getPattern());
5482}
5483
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005484bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5485 return false;
5486}
5487
5488bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5489 const ObjCInterfaceType *) {
5490 return false;
5491}
5492
5493bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5494 const ObjCObjectPointerType *) {
5495 return false;
5496}
5497
Eli Friedman0dfb8892011-10-06 23:00:33 +00005498bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5499 return Visit(T->getValueType());
5500}
5501
Xiuli Pan9c14e282016-01-09 12:53:17 +00005502bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5503 return false;
5504}
5505
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005506bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5507 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005508 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005509 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005510 diag::warn_cxx98_compat_template_arg_local_type :
5511 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005512 << S.Context.getTypeDeclType(Tag) << SR;
5513 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005514 }
5515
John McCall5ea95772013-03-09 00:54:27 +00005516 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005517 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005518 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005519 diag::warn_cxx98_compat_template_arg_unnamed_type :
5520 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005521 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5522 return true;
5523 }
5524
5525 return false;
5526}
5527
5528bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5529 NestedNameSpecifier *NNS) {
5530 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5531 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005532
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005533 switch (NNS->getKind()) {
5534 case NestedNameSpecifier::Identifier:
5535 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005536 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005537 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005538 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005539 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005540
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005541 case NestedNameSpecifier::TypeSpec:
5542 case NestedNameSpecifier::TypeSpecWithTemplate:
5543 return Visit(QualType(NNS->getAsType(), 0));
5544 }
David Blaikie8a40f702012-01-17 06:56:22 +00005545 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005546}
5547
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005548/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00005549/// template type parameter.
5550///
5551/// This routine implements the semantics of C++ [temp.arg.type]. It
5552/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005553bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005554 TypeSourceInfo *ArgInfo) {
5555 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005556 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005557 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005558
5559 if (Arg->isVariablyModifiedType()) {
5560 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005561 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005562 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005563 }
5564
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005565 // C++03 [temp.arg.type]p2:
5566 // A local type, a type with no linkage, an unnamed type or a type
5567 // compounded from any of these types shall not be used as a
5568 // template-argument for a template type-parameter.
5569 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005570 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005571 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005572 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005573 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5574 (void)Finder.Visit(Context.getCanonicalType(Arg));
5575 }
5576
Douglas Gregord32e0282009-02-09 23:23:08 +00005577 return false;
5578}
5579
Douglas Gregor20fdef32012-04-10 17:08:25 +00005580enum NullPointerValueKind {
5581 NPV_NotNullPointer,
5582 NPV_NullPointer,
5583 NPV_Error
5584};
5585
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005586/// Determine whether the given template argument is a null pointer
Douglas Gregor20fdef32012-04-10 17:08:25 +00005587/// value of the appropriate type.
5588static NullPointerValueKind
5589isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
Reid Klecknercd016d82017-07-07 22:04:29 +00005590 QualType ParamType, Expr *Arg,
5591 Decl *Entity = nullptr) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005592 if (Arg->isValueDependent() || Arg->isTypeDependent())
5593 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005594
Reid Klecknercd016d82017-07-07 22:04:29 +00005595 // dllimport'd entities aren't constant but are available inside of template
5596 // arguments.
5597 if (Entity && Entity->hasAttr<DLLImportAttr>())
5598 return NPV_NotNullPointer;
5599
Richard Smithdb0ac552015-12-18 22:40:25 +00005600 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005601 llvm_unreachable(
5602 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005603
David Majnemer5c734ad2014-08-14 00:49:23 +00005604 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005605 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005606
Douglas Gregor20fdef32012-04-10 17:08:25 +00005607 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005608 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5609 if (ArgRV.isInvalid())
5610 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005611 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005612
Douglas Gregor20fdef32012-04-10 17:08:25 +00005613 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005614 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005615 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005616 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005617 EvalResult.HasSideEffects) {
5618 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005619
Douglas Gregor350880c2012-04-10 19:03:30 +00005620 // If our only note is the usual "invalid subexpression" note, just point
5621 // the caret at its location rather than producing an essentially
5622 // redundant note.
5623 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5624 diag::note_invalid_subexpr_in_const_expr) {
5625 DiagLoc = Notes[0].first;
5626 Notes.clear();
5627 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005628
Douglas Gregor350880c2012-04-10 19:03:30 +00005629 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5630 << Arg->getType() << Arg->getSourceRange();
5631 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5632 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005633
Douglas Gregor350880c2012-04-10 19:03:30 +00005634 S.Diag(Param->getLocation(), diag::note_template_param_here);
5635 return NPV_Error;
5636 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005637
Douglas Gregor20fdef32012-04-10 17:08:25 +00005638 // C++11 [temp.arg.nontype]p1:
5639 // - an address constant expression of type std::nullptr_t
5640 if (Arg->getType()->isNullPtrType())
5641 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005642
Douglas Gregor20fdef32012-04-10 17:08:25 +00005643 // - a constant expression that evaluates to a null pointer value (4.10); or
5644 // - a constant expression that evaluates to a null member pointer value
5645 // (4.11); or
5646 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5647 (EvalResult.Val.isMemberPointer() &&
5648 !EvalResult.Val.getMemberPointerDecl())) {
5649 // If our expression has an appropriate type, we've succeeded.
5650 bool ObjCLifetimeConversion;
5651 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5652 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5653 ObjCLifetimeConversion))
5654 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005655
Douglas Gregor20fdef32012-04-10 17:08:25 +00005656 // The types didn't match, but we know we got a null pointer; complain,
5657 // then recover as if the types were correct.
5658 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5659 << Arg->getType() << ParamType << Arg->getSourceRange();
5660 S.Diag(Param->getLocation(), diag::note_template_param_here);
5661 return NPV_NullPointer;
5662 }
5663
5664 // If we don't have a null pointer value, but we do have a NULL pointer
5665 // constant, suggest a cast to the appropriate type.
5666 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5667 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5668 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005669 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005670 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
Alp Tokerb6cc5922014-05-03 03:45:55 +00005671 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005672 S.Diag(Param->getLocation(), diag::note_template_param_here);
5673 return NPV_NullPointer;
5674 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005675
Douglas Gregor20fdef32012-04-10 17:08:25 +00005676 // FIXME: If we ever want to support general, address-constant expressions
5677 // as non-type template arguments, we should return the ExprResult here to
5678 // be interpreted by the caller.
5679 return NPV_NotNullPointer;
5680}
5681
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005682/// Checks whether the given template argument is compatible with its
David Majnemer61c39a12013-08-23 05:39:39 +00005683/// template parameter.
5684static bool CheckTemplateArgumentIsCompatibleWithParameter(
5685 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5686 Expr *Arg, QualType ArgType) {
5687 bool ObjCLifetimeConversion;
5688 if (ParamType->isPointerType() &&
5689 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5690 S.IsQualificationConversion(ArgType, ParamType, false,
5691 ObjCLifetimeConversion)) {
5692 // For pointer-to-object types, qualification conversions are
5693 // permitted.
5694 } else {
5695 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5696 if (!ParamRef->getPointeeType()->isFunctionType()) {
5697 // C++ [temp.arg.nontype]p5b3:
5698 // For a non-type template-parameter of type reference to
5699 // object, no conversions apply. The type referred to by the
5700 // reference may be more cv-qualified than the (otherwise
5701 // identical) type of the template- argument. The
5702 // template-parameter is bound directly to the
5703 // template-argument, which shall be an lvalue.
5704
5705 // FIXME: Other qualifiers?
5706 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5707 unsigned ArgQuals = ArgType.getCVRQualifiers();
5708
5709 if ((ParamQuals | ArgQuals) != ParamQuals) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005710 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005711 diag::err_template_arg_ref_bind_ignores_quals)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005712 << ParamType << Arg->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005713 S.Diag(Param->getLocation(), diag::note_template_param_here);
5714 return true;
5715 }
5716 }
5717 }
5718
5719 // At this point, the template argument refers to an object or
5720 // function with external linkage. We now need to check whether the
5721 // argument and parameter types are compatible.
5722 if (!S.Context.hasSameUnqualifiedType(ArgType,
5723 ParamType.getNonReferenceType())) {
5724 // We can't perform this conversion or binding.
5725 if (ParamType->isReferenceType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005726 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
5727 << ParamType << ArgIn->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005728 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005729 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
5730 << ArgIn->getType() << ParamType << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005731 S.Diag(Param->getLocation(), diag::note_template_param_here);
5732 return true;
5733 }
5734 }
5735
5736 return false;
5737}
5738
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005739/// Checks whether the given template argument is the address
Douglas Gregorccb07762009-02-11 19:52:55 +00005740/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005742CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5743 NonTypeTemplateParmDecl *Param,
5744 QualType ParamType,
5745 Expr *ArgIn,
5746 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005747 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005748 Expr *Arg = ArgIn;
5749 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005750
Douglas Gregorb242683d2010-04-01 18:32:35 +00005751 bool AddressTaken = false;
5752 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005753 if (S.getLangOpts().MicrosoftExt) {
5754 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5755 // dereference and address-of operators.
5756 Arg = Arg->IgnoreParenCasts();
5757
5758 bool ExtWarnMSTemplateArg = false;
5759 UnaryOperatorKind FirstOpKind;
5760 SourceLocation FirstOpLoc;
5761 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5762 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5763 if (UnOpKind == UO_Deref)
5764 ExtWarnMSTemplateArg = true;
5765 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5766 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5767 if (!AddrOpLoc.isValid()) {
5768 FirstOpKind = UnOpKind;
5769 FirstOpLoc = UnOp->getOperatorLoc();
5770 }
5771 } else
5772 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005773 }
David Majnemer61c39a12013-08-23 05:39:39 +00005774 if (FirstOpLoc.isValid()) {
5775 if (ExtWarnMSTemplateArg)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005776 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
5777 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005778
David Majnemer61c39a12013-08-23 05:39:39 +00005779 if (FirstOpKind == UO_AddrOf)
5780 AddressTaken = true;
5781 else if (Arg->getType()->isPointerType()) {
5782 // We cannot let pointers get dereferenced here, that is obviously not a
5783 // constant expression.
5784 assert(FirstOpKind == UO_Deref);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005785 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5786 << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005787 }
5788 }
5789 } else {
5790 // See through any implicit casts we added to fix the type.
5791 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005792
David Majnemer61c39a12013-08-23 05:39:39 +00005793 // C++ [temp.arg.nontype]p1:
5794 //
5795 // A template-argument for a non-type, non-template
5796 // template-parameter shall be one of: [...]
5797 //
5798 // -- the address of an object or function with external
5799 // linkage, including function templates and function
5800 // template-ids but excluding non-static class members,
5801 // expressed as & id-expression where the & is optional if
5802 // the name refers to a function or array, or if the
5803 // corresponding template-parameter is a reference; or
5804
5805 // In C++98/03 mode, give an extension warning on any extra parentheses.
5806 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5807 bool ExtraParens = false;
5808 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5809 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005810 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005811 S.getLangOpts().CPlusPlus11
5812 ? diag::warn_cxx98_compat_template_arg_extra_parens
5813 : diag::ext_template_arg_extra_parens)
5814 << Arg->getSourceRange();
5815 ExtraParens = true;
5816 }
5817
5818 Arg = Parens->getSubExpr();
5819 }
5820
5821 while (SubstNonTypeTemplateParmExpr *subst =
5822 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5823 Arg = subst->getReplacement()->IgnoreImpCasts();
5824
5825 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5826 if (UnOp->getOpcode() == UO_AddrOf) {
5827 Arg = UnOp->getSubExpr();
5828 AddressTaken = true;
5829 AddrOpLoc = UnOp->getOperatorLoc();
5830 }
5831 }
5832
5833 while (SubstNonTypeTemplateParmExpr *subst =
5834 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5835 Arg = subst->getReplacement()->IgnoreImpCasts();
5836 }
John McCall7c454bb2011-07-15 05:09:51 +00005837
David Majnemer07910d62014-06-26 07:48:46 +00005838 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5839 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5840
5841 // If our parameter has pointer type, check for a null template value.
5842 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
Reid Klecknercd016d82017-07-07 22:04:29 +00005843 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5844 Entity)) {
David Majnemer07910d62014-06-26 07:48:46 +00005845 case NPV_NullPointer:
5846 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005847 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5848 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005849 return false;
5850
5851 case NPV_Error:
5852 return true;
5853
5854 case NPV_NotNullPointer:
5855 break;
5856 }
5857 }
5858
Chandler Carruth724a8a12010-01-31 10:01:20 +00005859 // Stop checking the precise nature of the argument if it is value dependent,
5860 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005861 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005862 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005863 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005864 }
David Majnemer61c39a12013-08-23 05:39:39 +00005865
5866 if (isa<CXXUuidofExpr>(Arg)) {
5867 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5868 ArgIn, Arg, ArgType))
5869 return true;
5870
5871 Converted = TemplateArgument(ArgIn);
5872 return false;
5873 }
5874
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005875 if (!DRE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005876 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5877 << Arg->getSourceRange();
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005878 S.Diag(Param->getLocation(), diag::note_template_param_here);
5879 return true;
5880 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00005881
Douglas Gregorccb07762009-02-11 19:52:55 +00005882 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00005883 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005884 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
5885 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005886 S.Diag(Param->getLocation(), diag::note_template_param_here);
5887 return true;
5888 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005889
5890 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00005891 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005892 if (!Method->isStatic()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005893 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
5894 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005895 S.Diag(Param->getLocation(), diag::note_template_param_here);
5896 return true;
5897 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005898 }
Mike Stump11289f42009-09-09 15:08:12 +00005899
Richard Smith9380e0e2012-04-04 21:11:30 +00005900 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5901 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00005902
Richard Smith9380e0e2012-04-04 21:11:30 +00005903 // A non-type template argument must refer to an object or function.
5904 if (!Func && !Var) {
5905 // We found something, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005906 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
5907 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005908 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5909 return true;
5910 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005911
Richard Smith9380e0e2012-04-04 21:11:30 +00005912 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00005913 if (Entity->getFormalLinkage() == InternalLinkage) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005914 S.Diag(Arg->getBeginLoc(),
5915 S.getLangOpts().CPlusPlus11
5916 ? diag::warn_cxx98_compat_template_arg_object_internal
5917 : diag::ext_template_arg_object_internal)
5918 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005919 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5920 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00005921 } else if (!Entity->hasLinkage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005922 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
5923 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005924 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5925 << !Func;
5926 return true;
5927 }
5928
5929 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005930 // If the template parameter has pointer type, the function decays.
5931 if (ParamType->isPointerType() && !AddressTaken)
5932 ArgType = S.Context.getPointerType(Func->getType());
5933 else if (AddressTaken && ParamType->isReferenceType()) {
5934 // If we originally had an address-of operator, but the
5935 // parameter has reference type, complain and (if things look
5936 // like they will work) drop the address-of operator.
5937 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5938 ParamType.getNonReferenceType())) {
5939 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5940 << ParamType;
5941 S.Diag(Param->getLocation(), diag::note_template_param_here);
5942 return true;
5943 }
5944
5945 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5946 << ParamType
5947 << FixItHint::CreateRemoval(AddrOpLoc);
5948 S.Diag(Param->getLocation(), diag::note_template_param_here);
5949
5950 ArgType = Func->getType();
5951 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005952 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005953 // A value of reference type is not an object.
5954 if (Var->getType()->isReferenceType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005955 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
5956 << Var->getType() << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005957 S.Diag(Param->getLocation(), diag::note_template_param_here);
5958 return true;
5959 }
5960
Richard Smith9380e0e2012-04-04 21:11:30 +00005961 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005962 if (Var->getTLSKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005963 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
5964 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005965 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5966 return true;
5967 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005968
5969 // If the template parameter has pointer type, we must have taken
5970 // the address of this object.
5971 if (ParamType->isReferenceType()) {
5972 if (AddressTaken) {
5973 // If we originally had an address-of operator, but the
5974 // parameter has reference type, complain and (if things look
5975 // like they will work) drop the address-of operator.
5976 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5977 ParamType.getNonReferenceType())) {
5978 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5979 << ParamType;
5980 S.Diag(Param->getLocation(), diag::note_template_param_here);
5981 return true;
5982 }
5983
5984 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5985 << ParamType
5986 << FixItHint::CreateRemoval(AddrOpLoc);
5987 S.Diag(Param->getLocation(), diag::note_template_param_here);
5988
5989 ArgType = Var->getType();
5990 }
5991 } else if (!AddressTaken && ParamType->isPointerType()) {
5992 if (Var->getType()->isArrayType()) {
5993 // Array-to-pointer decay.
5994 ArgType = S.Context.getArrayDecayedType(Var->getType());
5995 } else {
5996 // If the template parameter has pointer type but the address of
5997 // this object was not taken, complain and (possibly) recover by
5998 // taking the address of the entity.
5999 ArgType = S.Context.getPointerType(Var->getType());
6000 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006001 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6002 << ParamType;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006003 S.Diag(Param->getLocation(), diag::note_template_param_here);
6004 return true;
6005 }
6006
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006007 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6008 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
Douglas Gregorb242683d2010-04-01 18:32:35 +00006009
6010 S.Diag(Param->getLocation(), diag::note_template_param_here);
6011 }
6012 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006013 }
Mike Stump11289f42009-09-09 15:08:12 +00006014
David Majnemer61c39a12013-08-23 05:39:39 +00006015 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6016 Arg, ArgType))
6017 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006018
6019 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00006020 Converted =
6021 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006022 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00006023 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006024}
6025
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006026/// Checks whether the given template argument is a pointer to
Douglas Gregorccb07762009-02-11 19:52:55 +00006027/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00006028static bool CheckTemplateArgumentPointerToMember(Sema &S,
6029 NonTypeTemplateParmDecl *Param,
6030 QualType ParamType,
6031 Expr *&ResultArg,
6032 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006033 bool Invalid = false;
6034
Douglas Gregor20fdef32012-04-10 17:08:25 +00006035 Expr *Arg = ResultArg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006036 bool ObjCLifetimeConversion;
Douglas Gregorccb07762009-02-11 19:52:55 +00006037
6038 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006039 //
Douglas Gregorccb07762009-02-11 19:52:55 +00006040 // A template-argument for a non-type, non-template
6041 // template-parameter shall be one of: [...]
6042 //
6043 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00006044 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00006045
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006046 // In C++98/03 mode, give an extension warning on any extra parentheses.
6047 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6048 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006049 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00006050 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006051 S.Diag(Arg->getBeginLoc(),
6052 S.getLangOpts().CPlusPlus11
6053 ? diag::warn_cxx98_compat_template_arg_extra_parens
6054 : diag::ext_template_arg_extra_parens)
6055 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006056 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00006057 }
6058
6059 Arg = Parens->getSubExpr();
6060 }
6061
John McCall7c454bb2011-07-15 05:09:51 +00006062 while (SubstNonTypeTemplateParmExpr *subst =
6063 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6064 Arg = subst->getReplacement()->IgnoreImpCasts();
6065
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006066 // A pointer-to-member constant written &Class::member.
6067 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00006068 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006069 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6070 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00006071 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006072 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006073 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006074 // A constant of pointer-to-member type.
6075 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006076 ValueDecl *VD = DRE->getDecl();
6077 if (VD->getType()->isMemberPointerType()) {
6078 if (isa<NonTypeTemplateParmDecl>(VD)) {
6079 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6080 Converted = TemplateArgument(Arg);
6081 } else {
6082 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6083 Converted = TemplateArgument(VD, ParamType);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006084 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00006085 return Invalid;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006086 }
6087 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006088
Craig Topperc3ec1492014-05-26 06:22:03 +00006089 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006091
Reid Klecknercd016d82017-07-07 22:04:29 +00006092 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6093
6094 // Check for a null pointer value.
6095 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6096 Entity)) {
6097 case NPV_Error:
6098 return true;
6099 case NPV_NullPointer:
6100 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6101 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6102 /*isNullPtr*/true);
6103 return false;
6104 case NPV_NotNullPointer:
6105 break;
6106 }
6107
6108 if (S.IsQualificationConversion(ResultArg->getType(),
6109 ParamType.getNonReferenceType(), false,
6110 ObjCLifetimeConversion)) {
6111 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6112 ResultArg->getValueKind())
6113 .get();
6114 } else if (!S.Context.hasSameUnqualifiedType(
6115 ResultArg->getType(), ParamType.getNonReferenceType())) {
6116 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006117 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
Reid Klecknercd016d82017-07-07 22:04:29 +00006118 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6119 S.Diag(Param->getLocation(), diag::note_template_param_here);
6120 return true;
6121 }
6122
Douglas Gregorccb07762009-02-11 19:52:55 +00006123 if (!DRE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006124 return S.Diag(Arg->getBeginLoc(),
Douglas Gregor20fdef32012-04-10 17:08:25 +00006125 diag::err_template_arg_not_pointer_to_member_form)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006126 << Arg->getSourceRange();
Douglas Gregorccb07762009-02-11 19:52:55 +00006127
David Majnemer3ac84e62013-10-22 21:56:38 +00006128 if (isa<FieldDecl>(DRE->getDecl()) ||
6129 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6130 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006131 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00006132 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00006133 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6134 "Only non-static member pointers can make it here");
6135
6136 // Okay: this is the address of a non-static member, and therefore
6137 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00006138 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00006139 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00006140 } else {
6141 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00006142 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00006143 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006144 return Invalid;
6145 }
6146
6147 // We found something else, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006148 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6149 << Arg->getSourceRange();
Douglas Gregor20fdef32012-04-10 17:08:25 +00006150 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00006151 return true;
6152}
6153
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006154/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006155/// non-type template parameter.
6156///
Douglas Gregor463421d2009-03-03 04:44:36 +00006157/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00006158/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00006159/// returns the converted template argument. \p ParamType is the
6160/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00006161ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00006162 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00006163 TemplateArgument &Converted,
6164 CheckTemplateArgumentKind CTAK) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006165 SourceLocation StartLoc = Arg->getBeginLoc();
Douglas Gregorc40290e2009-03-09 23:48:35 +00006166
Richard Smith5f274382016-09-28 23:55:27 +00006167 // If the parameter type somehow involves auto, deduce the type now.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006168 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
Richard Smith4ae5ec82017-02-22 20:01:55 +00006169 // During template argument deduction, we allow 'decltype(auto)' to
6170 // match an arbitrary dependent argument.
6171 // FIXME: The language rules don't say what happens in this case.
6172 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6173 // expression is merely instantiation-dependent; is this enough?
6174 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6175 auto *AT = dyn_cast<AutoType>(ParamType);
6176 if (AT && AT->isDecltypeAuto()) {
6177 Converted = TemplateArgument(Arg);
6178 return Arg;
6179 }
6180 }
6181
Richard Smith87d263e2016-12-25 08:05:23 +00006182 // When checking a deduced template argument, deduce from its type even if
6183 // the type is dependent, in order to check the types of non-type template
6184 // arguments line up properly in partial ordering.
6185 Optional<unsigned> Depth;
6186 if (CTAK != CTAK_Specified)
6187 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00006188 if (DeduceAutoType(
6189 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00006190 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00006191 Diag(Arg->getExprLoc(),
6192 diag::err_non_type_template_parm_type_deduction_failure)
6193 << Param->getDeclName() << Param->getType() << Arg->getType()
6194 << Arg->getSourceRange();
6195 Diag(Param->getLocation(), diag::note_template_param_here);
6196 return ExprError();
6197 }
6198 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6199 // an error. The error message normally references the parameter
6200 // declaration, but here we'll pass the argument location because that's
6201 // where the parameter type is deduced.
6202 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6203 if (ParamType.isNull()) {
6204 Diag(Param->getLocation(), diag::note_template_param_here);
6205 return ExprError();
6206 }
6207 }
6208
Richard Smithd663fdd2014-12-17 20:42:37 +00006209 // We should have already dropped all cv-qualifiers by now.
6210 assert(!ParamType.hasQualifiers() &&
6211 "non-type template parameter type cannot be qualified");
6212
6213 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00006214 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00006215 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00006216 // FIXME: If either type is dependent, we skip the check. This isn't
6217 // correct, since during deduction we're supposed to have replaced each
6218 // template parameter with some unique (non-dependent) placeholder.
6219 // FIXME: If the argument type contains 'auto', we carry on and fail the
6220 // type check in order to force specific types to be more specialized than
6221 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6222 // work.
6223 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6224 !Arg->getType()->getContainedAutoType()) {
6225 Converted = TemplateArgument(Arg);
6226 return Arg;
6227 }
6228 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6229 // we should actually be checking the type of the template argument in P,
6230 // not the type of the template argument deduced from A, against the
6231 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00006232 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00006233 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00006234 << ParamType.getUnqualifiedType();
6235 Diag(Param->getLocation(), diag::note_template_param_here);
6236 return ExprError();
6237 }
6238
Richard Smith87d263e2016-12-25 08:05:23 +00006239 // If either the parameter has a dependent type or the argument is
6240 // type-dependent, there's nothing we can check now.
6241 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6242 // FIXME: Produce a cloned, canonical expression?
6243 Converted = TemplateArgument(Arg);
6244 return Arg;
6245 }
6246
Richard Smithe5945872017-01-06 22:52:53 +00006247 // The initialization of the parameter from the argument is
6248 // a constant-evaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006249 EnterExpressionEvaluationContext ConstantEvaluated(
6250 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smithe5945872017-01-06 22:52:53 +00006251
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006252 if (getLangOpts().CPlusPlus17) {
6253 // C++17 [temp.arg.nontype]p1:
Richard Smith410cc892014-11-26 03:26:53 +00006254 // A template-argument for a non-type template parameter shall be
6255 // a converted constant expression of the type of the template-parameter.
6256 APValue Value;
6257 ExprResult ArgResult = CheckConvertedConstantExpression(
6258 Arg, ParamType, Value, CCEK_TemplateArg);
6259 if (ArgResult.isInvalid())
6260 return ExprError();
6261
Richard Smith52e624f2016-12-21 21:42:57 +00006262 // For a value-dependent argument, CheckConvertedConstantExpression is
6263 // permitted (and expected) to be unable to determine a value.
6264 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00006265 Converted = TemplateArgument(ArgResult.get());
6266 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00006267 }
6268
Richard Smithd663fdd2014-12-17 20:42:37 +00006269 QualType CanonParamType = Context.getCanonicalType(ParamType);
6270
Richard Smith410cc892014-11-26 03:26:53 +00006271 // Convert the APValue to a TemplateArgument.
6272 switch (Value.getKind()) {
6273 case APValue::Uninitialized:
6274 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006275 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006276 break;
6277 case APValue::Int:
6278 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006279 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00006280 break;
6281 case APValue::MemberPointer: {
6282 assert(ParamType->isMemberPointerType());
6283
6284 // FIXME: We need TemplateArgument representation and mangling for these.
6285 if (!Value.getMemberPointerPath().empty()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006286 Diag(Arg->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00006287 diag::err_template_arg_member_ptr_base_derived_not_supported)
6288 << Value.getMemberPointerDecl() << ParamType
6289 << Arg->getSourceRange();
6290 return ExprError();
6291 }
6292
6293 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00006294 Converted = VD ? TemplateArgument(VD, CanonParamType)
6295 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006296 break;
6297 }
6298 case APValue::LValue: {
6299 // For a non-type template-parameter of pointer or reference type,
6300 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00006301 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6302 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00006303 // -- a temporary object
6304 // -- a string literal
6305 // -- the result of a typeid expression, or
Eric Christopher0d2c56a2017-03-31 01:45:39 +00006306 // -- a predefined __func__ variable
Richard Smith410cc892014-11-26 03:26:53 +00006307 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6308 if (isa<CXXUuidofExpr>(E)) {
Nico Weberd60bbce2018-05-17 15:26:37 +00006309 Converted = TemplateArgument(ArgResult.get());
Richard Smith410cc892014-11-26 03:26:53 +00006310 break;
6311 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006312 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6313 << Arg->getSourceRange();
Richard Smith410cc892014-11-26 03:26:53 +00006314 return ExprError();
6315 }
6316 auto *VD = const_cast<ValueDecl *>(
6317 Value.getLValueBase().dyn_cast<const ValueDecl *>());
6318 // -- a subobject
6319 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6320 VD && VD->getType()->isArrayType() &&
6321 Value.getLValuePath()[0].ArrayIndex == 0 &&
6322 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6323 // Per defect report (no number yet):
6324 // ... other than a pointer to the first element of a complete array
6325 // object.
6326 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6327 Value.isLValueOnePastTheEnd()) {
6328 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6329 << Value.getAsString(Context, ParamType);
6330 return ExprError();
6331 }
Richard Smithd663fdd2014-12-17 20:42:37 +00006332 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00006333 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00006334 assert((!VD || !ParamType->isNullPtrType()) &&
6335 "non-null value of type nullptr_t?");
6336 Converted = VD ? TemplateArgument(VD, CanonParamType)
6337 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006338 break;
6339 }
6340 case APValue::AddrLabelDiff:
6341 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6342 case APValue::Float:
6343 case APValue::ComplexInt:
6344 case APValue::ComplexFloat:
6345 case APValue::Vector:
6346 case APValue::Array:
6347 case APValue::Struct:
6348 case APValue::Union:
6349 llvm_unreachable("invalid kind for template argument");
6350 }
6351
6352 return ArgResult.get();
6353 }
6354
Douglas Gregor86560402009-02-10 23:36:10 +00006355 // C++ [temp.arg.nontype]p5:
6356 // The following conversions are performed on each expression used
6357 // as a non-type template-argument. If a non-type
6358 // template-argument cannot be converted to the type of the
6359 // corresponding template-parameter then the program is
6360 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00006361 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00006362 // C++11:
6363 // -- for a non-type template-parameter of integral or
6364 // enumeration type, conversions permitted in a converted
6365 // constant expression are applied.
6366 //
6367 // C++98:
6368 // -- for a non-type template-parameter of integral or
6369 // enumeration type, integral promotions (4.5) and integral
6370 // conversions (4.7) are applied.
6371
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006372 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00006373 // C++ [temp.arg.nontype]p1:
6374 // A template-argument for a non-type, non-template template-parameter
6375 // shall be one of:
6376 //
6377 // -- for a non-type template-parameter of integral or enumeration
6378 // type, a converted constant expression of the type of the
6379 // template-parameter; or
6380 llvm::APSInt Value;
6381 ExprResult ArgResult =
6382 CheckConvertedConstantExpression(Arg, ParamType, Value,
6383 CCEK_TemplateArg);
6384 if (ArgResult.isInvalid())
6385 return ExprError();
6386
Richard Smith01bfa682016-12-27 02:02:09 +00006387 // We can't check arbitrary value-dependent arguments.
6388 if (ArgResult.get()->isValueDependent()) {
6389 Converted = TemplateArgument(ArgResult.get());
6390 return ArgResult;
6391 }
6392
Richard Smithf8379a02012-01-18 23:55:52 +00006393 // Widen the argument value to sizeof(parameter type). This is almost
6394 // always a no-op, except when the parameter type is bool. In
6395 // that case, this may extend the argument from 1 bit to 8 bits.
6396 QualType IntegerType = ParamType;
6397 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6398 IntegerType = Enum->getDecl()->getIntegerType();
6399 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6400
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006401 Converted = TemplateArgument(Context, Value,
6402 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00006403 return ArgResult;
6404 }
6405
Richard Smith08b12f12011-10-27 22:11:44 +00006406 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6407 if (ArgResult.isInvalid())
6408 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006409 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00006410
6411 QualType ArgType = Arg->getType();
6412
Douglas Gregor86560402009-02-10 23:36:10 +00006413 // C++ [temp.arg.nontype]p1:
6414 // A template-argument for a non-type, non-template
6415 // template-parameter shall be one of:
6416 //
6417 // -- an integral constant-expression of integral or enumeration
6418 // type; or
6419 // -- the name of a non-type template-parameter; or
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006420 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00006421 if (!ArgType->isIntegralOrEnumerationType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006422 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6423 << ArgType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006424 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006425 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00006426 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00006427 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6428 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006429
Douglas Gregore2b37442012-05-04 22:38:52 +00006430 public:
6431 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00006432
6433 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6434 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00006435 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6436 }
6437 } Diagnoser(ArgType);
6438
6439 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006440 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00006441 if (!Arg)
6442 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006443 }
6444
Richard Smithd663fdd2014-12-17 20:42:37 +00006445 // From here on out, all we care about is the unqualified form
6446 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006447 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00006448
6449 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00006450 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00006451 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00006452 } else if (ParamType->isBooleanType()) {
6453 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006454 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006455 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6456 !ParamType->isEnumeralType()) {
6457 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006458 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006459 } else {
6460 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006461 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6462 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006463 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006464 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006465 }
6466
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006467 // Add the value of this argument to the list of converted
6468 // arguments. We use the bitwidth and signedness of the template
6469 // parameter.
6470 if (Arg->isValueDependent()) {
6471 // The argument is value-dependent. Create a new
6472 // TemplateArgument with the converted expression.
6473 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006474 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006475 }
6476
Douglas Gregor52aba872009-03-14 00:20:21 +00006477 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00006478 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00006479 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00006480
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006481 if (ParamType->isBooleanType()) {
6482 // Value must be zero or one.
6483 Value = Value != 0;
6484 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6485 if (Value.getBitWidth() != AllowedBits)
6486 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006487 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006488 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006489 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006490
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006491 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006492 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006493 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006494 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006495 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006496 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00006497
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006498 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006499 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006500 && (OldValue.isSigned() && OldValue.isNegative())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006501 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6502 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6503 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006504 Diag(Param->getLocation(), diag::note_template_param_here);
6505 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006506
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006507 // Complain if we overflowed the template parameter's type.
6508 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006509 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006510 RequiredBits = OldValue.getActiveBits();
6511 else if (OldValue.isUnsigned())
6512 RequiredBits = OldValue.getActiveBits() + 1;
6513 else
6514 RequiredBits = OldValue.getMinSignedBits();
6515 if (RequiredBits > AllowedBits) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006516 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6517 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6518 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006519 Diag(Param->getLocation(), diag::note_template_param_here);
6520 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006521 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006522
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006523 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006524 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006525 ? Context.getCanonicalType(ParamType)
6526 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006527 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006528 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006529
Richard Smith08b12f12011-10-27 22:11:44 +00006530 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006531 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6532
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006533 // Handle pointer-to-function, reference-to-function, and
6534 // pointer-to-member-function all in (roughly) the same way.
6535 if (// -- For a non-type template-parameter of type pointer to
6536 // function, only the function-to-pointer conversion (4.3) is
6537 // applied. If the template-argument represents a set of
6538 // overloaded functions (or a pointer to such), the matching
6539 // function is selected from the set (13.4).
6540 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006541 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006542 // -- For a non-type template-parameter of type reference to
6543 // function, no conversions apply. If the template-argument
6544 // represents a set of overloaded functions, the matching
6545 // function is selected from the set (13.4).
6546 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006547 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006548 // -- For a non-type template-parameter of type pointer to
6549 // member function, no conversions apply. If the
6550 // template-argument represents a set of overloaded member
6551 // functions, the matching member function is selected from
6552 // the set (13.4).
6553 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006554 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006555 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006556
Douglas Gregor064fdb22010-04-14 23:11:21 +00006557 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006558 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006559 true,
6560 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006561 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006562 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006563
6564 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6565 ArgType = Arg->getType();
6566 } else
John Wiegley01296292011-04-08 18:41:53 +00006567 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006569
John Wiegley01296292011-04-08 18:41:53 +00006570 if (!ParamType->isMemberPointerType()) {
6571 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6572 ParamType,
6573 Arg, Converted))
6574 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006575 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006576 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006577
Douglas Gregor20fdef32012-04-10 17:08:25 +00006578 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6579 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006580 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006581 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006582 }
6583
Chris Lattner696197c2009-02-20 21:37:53 +00006584 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006585 // -- for a non-type template-parameter of type pointer to
6586 // object, qualification conversions (4.4) and the
6587 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006588 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006589 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006590 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006591
John Wiegley01296292011-04-08 18:41:53 +00006592 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6593 ParamType,
6594 Arg, Converted))
6595 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006596 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006597 }
Mike Stump11289f42009-09-09 15:08:12 +00006598
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006599 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006600 // -- For a non-type template-parameter of type reference to
6601 // object, no conversions apply. The type referred to by the
6602 // reference may be more cv-qualified than the (otherwise
6603 // identical) type of the template-argument. The
6604 // template-parameter is bound directly to the
6605 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006606 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006607 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006608
Douglas Gregor064fdb22010-04-14 23:11:21 +00006609 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006610 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6611 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006612 true,
6613 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006614 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006615 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006616
6617 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6618 ArgType = Arg->getType();
6619 } else
John Wiegley01296292011-04-08 18:41:53 +00006620 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006621 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006622
John Wiegley01296292011-04-08 18:41:53 +00006623 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6624 ParamType,
6625 Arg, Converted))
6626 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006627 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006628 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006629
Douglas Gregor20fdef32012-04-10 17:08:25 +00006630 // Deal with parameters of type std::nullptr_t.
6631 if (ParamType->isNullPtrType()) {
6632 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6633 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006634 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006635 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006636
Douglas Gregor20fdef32012-04-10 17:08:25 +00006637 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6638 case NPV_NotNullPointer:
6639 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6640 << Arg->getType() << ParamType;
6641 Diag(Param->getLocation(), diag::note_template_param_here);
6642 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006643
Douglas Gregor20fdef32012-04-10 17:08:25 +00006644 case NPV_Error:
6645 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006646
Douglas Gregor20fdef32012-04-10 17:08:25 +00006647 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006648 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006649 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6650 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006651 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006652 }
6653 }
6654
Douglas Gregor0e558532009-02-11 16:16:59 +00006655 // -- For a non-type template-parameter of type pointer to data
6656 // member, qualification conversions (4.4) are applied.
6657 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6658
Douglas Gregor20fdef32012-04-10 17:08:25 +00006659 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6660 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006661 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006662 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006663}
6664
Richard Smith26b86ea2016-12-31 21:41:23 +00006665static void DiagnoseTemplateParameterListArityMismatch(
6666 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6667 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6668
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006669/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006670/// template template parameter.
6671///
6672/// This routine implements the semantics of C++ [temp.arg.template].
6673/// It returns true if an error occurred, and false otherwise.
Richard Smith5d331022018-03-08 01:07:33 +00006674bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6675 TemplateArgumentLoc &Arg) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006676 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006677 TemplateDecl *Template = Name.getAsTemplateDecl();
6678 if (!Template) {
6679 // Any dependent template name is fine.
6680 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6681 return false;
6682 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006683
Richard Smith26b86ea2016-12-31 21:41:23 +00006684 if (Template->isInvalidDecl())
6685 return true;
6686
Richard Smith3f1b5d02011-05-05 21:57:07 +00006687 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006688 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006689 // the name of a class template or an alias template, expressed as an
6690 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006691 // primary class templates are considered when matching the
6692 // template template argument with the corresponding parameter;
6693 // partial specializations are not considered even if their
6694 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006695 //
6696 // Note that we also allow template template parameters here, which
6697 // will happen when we are dealing with, e.g., class template
6698 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006699 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006700 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006701 !isa<TypeAliasTemplateDecl>(Template) &&
6702 !isa<BuiltinTemplateDecl>(Template)) {
6703 assert(isa<FunctionTemplateDecl>(Template) &&
6704 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006705 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006706 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6707 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006708 }
6709
Richard Smith26b86ea2016-12-31 21:41:23 +00006710 // C++1z [temp.arg.template]p3: (DR 150)
6711 // A template-argument matches a template template-parameter P when P
6712 // is at least as specialized as the template-argument A.
6713 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6714 // Quick check for the common case:
6715 // If P contains a parameter pack, then A [...] matches P if each of A's
6716 // template parameters matches the corresponding template parameter in
6717 // the template-parameter-list of P.
6718 if (TemplateParameterListsAreEqual(
6719 Template->getTemplateParameters(), Params, false,
6720 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6721 return false;
6722
6723 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6724 Arg.getLocation()))
6725 return false;
6726 // FIXME: Produce better diagnostics for deduction failures.
6727 }
6728
Douglas Gregor85e0f662009-02-10 00:24:35 +00006729 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006730 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006731 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006732 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006733 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006734}
6735
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006736/// Given a non-type template argument that refers to a
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006737/// declaration and the type of its corresponding non-type template
6738/// parameter, produce an expression that properly refers to that
6739/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006740ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006741Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6742 QualType ParamType,
6743 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006744 // C++ [temp.param]p8:
6745 //
6746 // A non-type template-parameter of type "array of T" or
6747 // "function returning T" is adjusted to be of type "pointer to
6748 // T" or "pointer to function returning T", respectively.
6749 if (ParamType->isArrayType())
6750 ParamType = Context.getArrayDecayedType(ParamType);
6751 else if (ParamType->isFunctionType())
6752 ParamType = Context.getPointerType(ParamType);
6753
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006754 // For a NULL non-type template argument, return nullptr casted to the
6755 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006756 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006757 return ImpCastExprToType(
6758 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6759 ParamType,
6760 ParamType->getAs<MemberPointerType>()
6761 ? CK_NullToMemberPointer
6762 : CK_NullToPointer);
6763 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006764 assert(Arg.getKind() == TemplateArgument::Declaration &&
6765 "Only declaration template arguments permitted here");
6766
George Burgess IV00f70bd2018-03-01 05:43:23 +00006767 ValueDecl *VD = Arg.getAsDecl();
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006768
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006769 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006770 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6771 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006772 // If the value is a class member, we might have a pointer-to-member.
6773 // Determine whether the non-type template template parameter is of
6774 // pointer-to-member type. If so, we need to build an appropriate
6775 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6776 // would refer to the member itself.
6777 if (ParamType->isMemberPointerType()) {
6778 QualType ClassType
6779 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6780 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006781 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006782 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006783 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006784 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006785
6786 // The actual value-ness of this is unimportant, but for
6787 // internal consistency's sake, references to instance methods
6788 // are r-values.
6789 ExprValueKind VK = VK_LValue;
6790 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6791 VK = VK_RValue;
6792
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006793 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006794 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006795 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006796 Loc,
6797 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006798 if (RefExpr.isInvalid())
6799 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006800
John McCalle3027922010-08-25 11:45:40 +00006801 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006802
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006803 // We might need to perform a trailing qualification conversion, since
6804 // the element type on the parameter could be more qualified than the
6805 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006806 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006807 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006808 ParamType.getUnqualifiedType(), false,
6809 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006810 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006811
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006812 assert(!RefExpr.isInvalid() &&
6813 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006814 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006815 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006816 }
6817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006818
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006819 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006820
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006821 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006822 // When the non-type template parameter is a pointer, take the
6823 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006824 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006825 if (RefExpr.isInvalid())
6826 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006827
Richard Smithfc6fca12017-01-28 00:38:35 +00006828 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6829 (T->isFunctionType() || T->isArrayType())) {
6830 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006831 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006832 if (RefExpr.isInvalid())
6833 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006834
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006835 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006837
Douglas Gregorb242683d2010-04-01 18:32:35 +00006838 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006839 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006840 }
6841
John McCall7decc9e2010-11-18 06:31:45 +00006842 ExprValueKind VK = VK_RValue;
6843
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006844 // If the non-type template parameter has reference type, qualify the
6845 // resulting declaration reference with the extra qualifiers on the
6846 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006847 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6848 VK = VK_LValue;
6849 T = Context.getQualifiedType(T,
6850 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006851 } else if (isa<FunctionDecl>(VD)) {
6852 // References to functions are always lvalues.
6853 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006854 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006855
John McCall7decc9e2010-11-18 06:31:45 +00006856 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006857}
6858
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006859/// Construct a new expression that refers to the given
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006860/// integral template argument with the given source-location
6861/// information.
6862///
6863/// This routine takes care of the mapping from an integral template
6864/// argument (which may have any integral type) to the appropriate
6865/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006866ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006867Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6868 SourceLocation Loc) {
6869 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006870 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006871 QualType OrigT = Arg.getIntegralType();
6872
6873 // If this is an enum type that we're instantiating, we need to use an integer
6874 // type the same size as the enumerator. We don't want to build an
6875 // IntegerLiteral with enum type. The integer type of an enum type can be of
6876 // any integral type with C++11 enum classes, make sure we create the right
6877 // type of literal for it.
6878 QualType T = OrigT;
6879 if (const EnumType *ET = OrigT->getAs<EnumType>())
6880 T = ET->getDecl()->getIntegerType();
6881
6882 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006883 if (T->isAnyCharacterType()) {
6884 CharacterLiteral::CharacterKind Kind;
6885 if (T->isWideCharType())
6886 Kind = CharacterLiteral::Wide;
Richard Smith3a8244d2018-05-01 05:02:45 +00006887 else if (T->isChar8Type() && getLangOpts().Char8)
6888 Kind = CharacterLiteral::UTF8;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006889 else if (T->isChar16Type())
6890 Kind = CharacterLiteral::UTF16;
6891 else if (T->isChar32Type())
6892 Kind = CharacterLiteral::UTF32;
6893 else
6894 Kind = CharacterLiteral::Ascii;
6895
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006896 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6897 Kind, T, Loc);
6898 } else if (T->isBooleanType()) {
6899 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6900 T, Loc);
6901 } else if (T->isNullPtrType()) {
6902 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6903 } else {
6904 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00006905 }
6906
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006907 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00006908 // FIXME: This is a hack. We need a better way to handle substituted
6909 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00006910 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6911 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006912 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00006913 Loc, Loc);
6914 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006915
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006916 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006917}
6918
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006919/// Match two template parameters within template parameter lists.
Douglas Gregor641040a2011-01-12 23:45:44 +00006920static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6921 bool Complain,
6922 Sema::TemplateParameterListEqualKind Kind,
6923 SourceLocation TemplateArgLoc) {
6924 // Check the actual kind (type, non-type, template).
6925 if (Old->getKind() != New->getKind()) {
6926 if (Complain) {
6927 unsigned NextDiag = diag::err_template_param_different_kind;
6928 if (TemplateArgLoc.isValid()) {
6929 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6930 NextDiag = diag::note_template_param_different_kind;
6931 }
6932 S.Diag(New->getLocation(), NextDiag)
6933 << (Kind != Sema::TPL_TemplateMatch);
6934 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6935 << (Kind != Sema::TPL_TemplateMatch);
6936 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006937
Douglas Gregor641040a2011-01-12 23:45:44 +00006938 return false;
6939 }
6940
Richard Smith26b86ea2016-12-31 21:41:23 +00006941 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006942 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006943 // template template parameter, the template template parameter can have
6944 // a parameter pack where the template template argument does not.
6945 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6946 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6947 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006948 if (Complain) {
6949 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6950 if (TemplateArgLoc.isValid()) {
6951 S.Diag(TemplateArgLoc,
6952 diag::err_template_arg_template_params_mismatch);
6953 NextDiag = diag::note_template_parameter_pack_non_pack;
6954 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006955
Douglas Gregor641040a2011-01-12 23:45:44 +00006956 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6957 : isa<NonTypeTemplateParmDecl>(New)? 1
6958 : 2;
6959 S.Diag(New->getLocation(), NextDiag)
6960 << ParamKind << New->isParameterPack();
6961 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6962 << ParamKind << Old->isParameterPack();
6963 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006964
Douglas Gregor641040a2011-01-12 23:45:44 +00006965 return false;
6966 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967
Douglas Gregor641040a2011-01-12 23:45:44 +00006968 // For non-type template parameters, check the type of the parameter.
6969 if (NonTypeTemplateParmDecl *OldNTTP
6970 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6971 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006972
Douglas Gregor641040a2011-01-12 23:45:44 +00006973 // If we are matching a template template argument to a template
6974 // template parameter and one of the non-type template parameter types
Richard Smith13894182017-04-13 21:37:24 +00006975 // is dependent, then we must wait until template instantiation time
6976 // to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00006977 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith13894182017-04-13 21:37:24 +00006978 (OldNTTP->getType()->isDependentType() ||
6979 NewNTTP->getType()->isDependentType()))
Douglas Gregor641040a2011-01-12 23:45:44 +00006980 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006981
Douglas Gregor641040a2011-01-12 23:45:44 +00006982 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6983 if (Complain) {
6984 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6985 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006986 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00006987 diag::err_template_arg_template_params_mismatch);
6988 NextDiag = diag::note_template_nontype_parm_different_type;
6989 }
6990 S.Diag(NewNTTP->getLocation(), NextDiag)
6991 << NewNTTP->getType()
6992 << (Kind != Sema::TPL_TemplateMatch);
6993 S.Diag(OldNTTP->getLocation(),
6994 diag::note_template_nontype_parm_prev_declaration)
6995 << OldNTTP->getType();
6996 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006997
Douglas Gregor641040a2011-01-12 23:45:44 +00006998 return false;
6999 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007000
Douglas Gregor641040a2011-01-12 23:45:44 +00007001 return true;
7002 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007003
Douglas Gregor641040a2011-01-12 23:45:44 +00007004 // For template template parameters, check the template parameter types.
7005 // The template parameter lists of template template
7006 // parameters must agree.
7007 if (TemplateTemplateParmDecl *OldTTP
7008 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007009 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00007010 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7011 OldTTP->getTemplateParameters(),
7012 Complain,
7013 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007014 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00007015 : Kind),
7016 TemplateArgLoc);
7017 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007018
Douglas Gregor641040a2011-01-12 23:45:44 +00007019 return true;
7020}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007021
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007022/// Diagnose a known arity mismatch when comparing template argument
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007023/// lists.
7024static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007025void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007026 TemplateParameterList *New,
7027 TemplateParameterList *Old,
7028 Sema::TemplateParameterListEqualKind Kind,
7029 SourceLocation TemplateArgLoc) {
7030 unsigned NextDiag = diag::err_template_param_list_different_arity;
7031 if (TemplateArgLoc.isValid()) {
7032 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7033 NextDiag = diag::note_template_param_list_different_arity;
7034 }
7035 S.Diag(New->getTemplateLoc(), NextDiag)
7036 << (New->size() > Old->size())
7037 << (Kind != Sema::TPL_TemplateMatch)
7038 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7039 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7040 << (Kind != Sema::TPL_TemplateMatch)
7041 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7042}
7043
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007044/// Determine whether the given template parameter lists are
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007045/// equivalent.
7046///
Mike Stump11289f42009-09-09 15:08:12 +00007047/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007048/// source code as part of a new template declaration.
7049///
7050/// \param Old The old template parameter list, typically found via
7051/// name lookup of the template declared with this template parameter
7052/// list.
7053///
7054/// \param Complain If true, this routine will produce a diagnostic if
7055/// the template parameter lists are not equivalent.
7056///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007057/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00007058///
7059/// \param TemplateArgLoc If this source location is valid, then we
7060/// are actually checking the template parameter list of a template
7061/// argument (New) against the template parameter list of its
7062/// corresponding template template parameter (Old). We produce
7063/// slightly different diagnostics in this scenario.
7064///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007065/// \returns True if the template parameter lists are equal, false
7066/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00007067bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007068Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7069 TemplateParameterList *Old,
7070 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007071 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00007072 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007073 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7074 if (Complain)
7075 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7076 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007077
7078 return false;
7079 }
7080
Douglas Gregor641040a2011-01-12 23:45:44 +00007081 // C++0x [temp.arg.template]p3:
7082 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007083 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00007084 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007085 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007086 // template-parameter-list of P. [...]
7087 TemplateParameterList::iterator NewParm = New->begin();
7088 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007089 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007090 OldParmEnd = Old->end();
7091 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00007092 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7093 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007094 if (NewParm == NewParmEnd) {
7095 if (Complain)
7096 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7097 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007098
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007099 return false;
7100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007101
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007102 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7103 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007104 return false;
7105
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007106 ++NewParm;
7107 continue;
7108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007109
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007110 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007111 // [...] When P's template- parameter-list contains a template parameter
7112 // pack (14.5.3), the template parameter pack will match zero or more
7113 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007114 // template-parameter-list of A with the same type and form as the
7115 // template parameter pack in P (ignoring whether those template
7116 // parameters are template parameter packs).
7117 for (; NewParm != NewParmEnd; ++NewParm) {
7118 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7119 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007120 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007121 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007123
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007124 // Make sure we exhausted all of the arguments.
7125 if (NewParm != NewParmEnd) {
7126 if (Complain)
7127 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7128 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007129
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007130 return false;
7131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007132
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007133 return true;
7134}
7135
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007136/// Check whether a template can be declared within this scope.
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007137///
7138/// If the template declaration is valid in this scope, returns
7139/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00007140bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007141Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00007142 if (!S)
7143 return false;
7144
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007145 // Find the nearest enclosing declaration scope.
7146 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7147 (S->getFlags() & Scope::TemplateParamScope) != 0)
7148 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00007149
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007150 // C++ [temp]p4:
7151 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007152 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00007153 if (Ctx && Ctx->isExternCContext()) {
7154 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7155 << TemplateParams->getSourceRange();
7156 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7157 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7158 return true;
7159 }
Richard Smith8df390f2016-09-08 23:14:54 +00007160 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007161
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007162 // C++ [temp]p2:
7163 // A template-declaration can appear only as a namespace scope or
7164 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00007165 if (Ctx) {
7166 if (Ctx->isFileContext())
7167 return false;
7168 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7169 // C++ [temp.mem]p2:
7170 // A local class shall not have member templates.
7171 if (RD->isLocalClass())
7172 return Diag(TemplateParams->getTemplateLoc(),
7173 diag::err_template_inside_local_class)
7174 << TemplateParams->getSourceRange();
7175 else
7176 return false;
7177 }
7178 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007179
Mike Stump11289f42009-09-09 15:08:12 +00007180 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007181 diag::err_template_outside_namespace_or_class_scope)
7182 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007183}
Douglas Gregor67a65642009-02-17 23:15:12 +00007184
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007185/// Determine what kind of template specialization the given declaration
Douglas Gregor54888652009-10-07 00:13:32 +00007186/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007187static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00007188 if (!D)
7189 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007190
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007191 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7192 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00007193 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7194 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007195 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7196 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007197
Douglas Gregor54888652009-10-07 00:13:32 +00007198 return TSK_Undeclared;
7199}
7200
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007201/// Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007202/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00007203///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007204/// This routine determines whether a template specialization can be declared
7205/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00007206///
7207/// \param S the semantic analysis object for which this check is being
7208/// performed.
7209///
7210/// \param Specialized the entity being specialized or instantiated, which
7211/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007212/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00007213/// member class).
7214///
7215/// \param PrevDecl the previous declaration of this entity, if any.
7216///
7217/// \param Loc the location of the explicit specialization or instantiation of
7218/// this entity.
7219///
7220/// \param IsPartialSpecialization whether this is a partial specialization of
7221/// a class template.
7222///
Douglas Gregor54888652009-10-07 00:13:32 +00007223/// \returns true if there was an error that we cannot recover from, false
7224/// otherwise.
7225static bool CheckTemplateSpecializationScope(Sema &S,
7226 NamedDecl *Specialized,
7227 NamedDecl *PrevDecl,
7228 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007229 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00007230 // Keep these "kind" numbers in sync with the %select statements in the
7231 // various diagnostics emitted by this routine.
7232 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007233 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007234 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007235 else if (isa<VarTemplateDecl>(Specialized))
7236 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007237 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007238 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007239 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007240 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007241 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00007242 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007243 else if (isa<RecordDecl>(Specialized))
7244 EntityKind = 7;
7245 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7246 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00007247 else {
Richard Smith7d137e32012-03-23 03:33:32 +00007248 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007249 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007250 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00007251 return true;
7252 }
7253
Douglas Gregorf47b9112009-02-25 22:02:03 +00007254 // C++ [temp.expl.spec]p2:
Richard Smithc660c8f2018-03-16 13:36:56 +00007255 // An explicit specialization may be declared in any scope in which
7256 // the corresponding primary template may be defined.
Sebastian Redl50c68252010-08-31 00:36:30 +00007257 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00007258 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007259 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007260 return true;
7261 }
Douglas Gregore4b05162009-10-07 17:21:34 +00007262
7263 // C++ [temp.class.spec]p6:
Richard Smithc660c8f2018-03-16 13:36:56 +00007264 // A class template partial specialization may be declared in any
7265 // scope in which the primary template may be defined.
7266 DeclContext *SpecializedContext =
7267 Specialized->getDeclContext()->getRedeclContext();
7268 DeclContext *DC = S.CurContext->getRedeclContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00007269
Richard Smithc660c8f2018-03-16 13:36:56 +00007270 // Make sure that this redeclaration (or definition) occurs in the same
7271 // scope or an enclosing namespace.
7272 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7273 : DC->Equals(SpecializedContext))) {
Richard Smitha98f8fc2013-12-07 05:09:50 +00007274 if (isa<TranslationUnitDecl>(SpecializedContext))
7275 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7276 << EntityKind << Specialized;
Richard Smithc660c8f2018-03-16 13:36:56 +00007277 else {
7278 auto *ND = cast<NamedDecl>(SpecializedContext);
Alexey Bataev0068cb22015-03-20 07:21:46 +00007279 int Diag = diag::err_template_spec_redecl_out_of_scope;
Richard Smithc660c8f2018-03-16 13:36:56 +00007280 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
Alexey Bataev0068cb22015-03-20 07:21:46 +00007281 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7282 S.Diag(Loc, Diag) << EntityKind << Specialized
Richard Smithc660c8f2018-03-16 13:36:56 +00007283 << ND << isa<CXXRecordDecl>(ND);
7284 }
Richard Smitha98f8fc2013-12-07 05:09:50 +00007285
7286 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007287
Richard Smithc660c8f2018-03-16 13:36:56 +00007288 // Don't allow specializing in the wrong class during error recovery.
7289 // Otherwise, things can go horribly wrong.
7290 if (DC->isRecord())
7291 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007292 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007293
Douglas Gregorf47b9112009-02-25 22:02:03 +00007294 return false;
7295}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007296
Richard Smith57aae072016-12-28 02:37:25 +00007297static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7298 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00007299 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007300 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007301 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00007302 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007303 return E->getSourceRange();
7304 return Checker.MatchLoc;
7305}
7306
7307static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7308 if (!TL.getType()->isDependentType())
7309 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007310 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007311 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00007312 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007313 return TL.getSourceRange();
7314 return Checker.MatchLoc;
7315}
7316
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007317/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007318/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007319static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007320 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7321 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007322 for (unsigned I = 0; I != NumArgs; ++I) {
7323 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007324 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007325 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7326 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007327 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007328
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007329 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007330 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007331
Eli Friedmanb826a002012-09-26 02:36:12 +00007332 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007333 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00007334
7335 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007336
Douglas Gregor98318c22011-01-03 21:37:45 +00007337 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007338 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7339 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00007340
7341 // Strip off any implicit casts we added as part of type checking.
7342 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7343 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007344
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007345 // C++ [temp.class.spec]p8:
7346 // A non-type argument is non-specialized if it is the name of a
7347 // non-type parameter. All other non-type arguments are
7348 // specialized.
7349 //
7350 // Below, we check the two conditions that only apply to
7351 // specialized non-type arguments, so skip any non-specialized
7352 // arguments.
7353 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00007354 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007355 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007356
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007357 // C++ [temp.class.spec]p9:
7358 // Within the argument list of a class template partial
7359 // specialization, the following restrictions apply:
7360 // -- A partially specialized non-type argument expression
7361 // shall not involve a template parameter of the partial
7362 // specialization except when the argument expression is a
7363 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00007364 // -- The type of a template parameter corresponding to a
7365 // specialized non-type argument shall not be dependent on a
7366 // parameter of the specialization.
7367 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7368 // We implement a compromise between the original rules and DR1315:
7369 // -- A specialized non-type template argument shall not be
7370 // type-dependent and the corresponding template parameter
7371 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00007372 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00007373 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00007374 if (ParamUseRange.isValid()) {
7375 if (IsDefaultArgument) {
7376 S.Diag(TemplateNameLoc,
7377 diag::err_dependent_non_type_arg_in_partial_spec);
7378 S.Diag(ParamUseRange.getBegin(),
7379 diag::note_dependent_non_type_default_arg_in_partial_spec)
7380 << ParamUseRange;
7381 } else {
7382 S.Diag(ParamUseRange.getBegin(),
7383 diag::err_dependent_non_type_arg_in_partial_spec)
7384 << ParamUseRange;
7385 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007386 return true;
7387 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007388
Richard Smith6056d5e2014-02-09 00:54:43 +00007389 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00007390 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00007391 if (ParamUseRange.isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007392 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
Richard Smith6056d5e2014-02-09 00:54:43 +00007393 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007394 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00007395 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00007396 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7397 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007398 return true;
7399 }
7400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007401
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007402 return false;
7403}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007404
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007405/// Check the non-type template arguments of a class template
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007406/// partial specialization according to C++ [temp.class.spec]p9.
7407///
Richard Smith6056d5e2014-02-09 00:54:43 +00007408/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00007409/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00007410/// template.
7411/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00007412/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00007413/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007414///
Richard Smith6056d5e2014-02-09 00:54:43 +00007415/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00007416bool Sema::CheckTemplatePartialSpecializationArgs(
7417 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7418 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7419 // We have to be conservative when checking a template in a dependent
7420 // context.
7421 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7422 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007423
Richard Smith57aae072016-12-28 02:37:25 +00007424 TemplateParameterList *TemplateParams =
7425 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007426 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7427 NonTypeTemplateParmDecl *Param
7428 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7429 if (!Param)
7430 continue;
7431
Richard Smith57aae072016-12-28 02:37:25 +00007432 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7433 Param, &TemplateArgs[I],
7434 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007435 return true;
7436 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007437
7438 return false;
7439}
7440
Erich Keanec480f302018-07-12 21:09:05 +00007441DeclResult Sema::ActOnClassTemplateSpecialization(
7442 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7443 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7444 const ParsedAttributesView &Attr,
7445 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007446 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007447
Richard Smith4b55a9c2014-04-17 03:29:33 +00007448 CXXScopeSpec &SS = TemplateId.SS;
7449
Abramo Bagnara60804e12011-03-18 15:16:37 +00007450 // NOTE: KWLoc is the location of the tag keyword. This will instead
7451 // store the location of the outermost template keyword in the declaration.
7452 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007453 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7454 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7455 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7456 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007457
Douglas Gregor67a65642009-02-17 23:15:12 +00007458 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007459 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007460 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007461 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7462
7463 if (!ClassTemplate) {
7464 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007465 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007466 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7467 return true;
7468 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007469
Richard Smithf445f192017-02-09 21:04:43 +00007470 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007471 bool isPartialSpecialization = false;
7472
Douglas Gregorf47b9112009-02-25 22:02:03 +00007473 // Check the validity of the template headers that introduce this
7474 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007475 // FIXME: We probably shouldn't complain about these headers for
7476 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007477 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007478 TemplateParameterList *TemplateParams =
7479 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007480 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007481 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007482 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007483 if (Invalid)
7484 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007485
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007486 if (TemplateParams && TemplateParams->size() > 0) {
7487 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007488
Douglas Gregorec9518b2010-12-21 08:14:57 +00007489 if (TUK == TUK_Friend) {
7490 Diag(KWLoc, diag::err_partial_specialization_friend)
7491 << SourceRange(LAngleLoc, RAngleLoc);
7492 return true;
7493 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007494
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007495 // C++ [temp.class.spec]p10:
7496 // The template parameter list of a specialization shall not
7497 // contain default template argument values.
7498 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7499 Decl *Param = TemplateParams->getParam(I);
7500 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7501 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007502 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007503 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007504 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007505 }
7506 } else if (NonTypeTemplateParmDecl *NTTP
7507 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7508 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007509 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007510 diag::err_default_arg_in_partial_spec)
7511 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007512 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007513 }
7514 } else {
7515 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007516 if (TTP->hasDefaultArgument()) {
7517 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007518 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007519 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007520 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007521 }
7522 }
7523 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007524 } else if (TemplateParams) {
7525 if (TUK == TUK_Friend)
7526 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007527 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007528 SourceRange(TemplateParams->getTemplateLoc(),
7529 TemplateParams->getRAngleLoc()))
7530 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007531 } else {
7532 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007533 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007534
Douglas Gregor67a65642009-02-17 23:15:12 +00007535 // Check that the specialization uses the same tag kind as the
7536 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007537 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7538 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007539 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007540 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007541 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007542 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007543 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007544 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007545 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007546 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007547 diag::note_previous_use);
7548 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7549 }
7550
Douglas Gregorc40290e2009-03-09 23:48:35 +00007551 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007552 TemplateArgumentListInfo TemplateArgs =
7553 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007554
Douglas Gregor14406932011-01-03 20:35:03 +00007555 // Check for unexpanded parameter packs in any of the template arguments.
7556 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007557 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007558 UPPC_PartialSpecialization))
7559 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007560
Douglas Gregor67a65642009-02-17 23:15:12 +00007561 // Check that the template argument list is well-formed for this
7562 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007563 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007564 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7565 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007566 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007567
Douglas Gregor2373c592009-05-31 09:31:02 +00007568 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007569 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007570 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007571 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7572 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007573 return true;
7574
Richard Smith57aae072016-12-28 02:37:25 +00007575 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7576 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007577 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007578 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007579 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007580 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007581 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7582 << ClassTemplate->getDeclName();
7583 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007584 }
7585 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007586
Craig Topperc3ec1492014-05-26 06:22:03 +00007587 void *InsertPos = nullptr;
7588 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007589
7590 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007591 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007592 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007593 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007594 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007595
Craig Topperc3ec1492014-05-26 06:22:03 +00007596 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007597
Douglas Gregorf47b9112009-02-25 22:02:03 +00007598 // Check whether we can declare a class template specialization in
7599 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007600 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007601 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7602 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007603 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007604 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007605
Douglas Gregor15301382009-07-30 17:40:51 +00007606 // The canonical type
7607 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007608 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007609 // Build the canonical type that describes the converted template
7610 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007611 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7612 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007613 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007614
7615 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007616 ClassTemplate->getInjectedClassNameSpecialization())) {
7617 // C++ [temp.class.spec]p9b3:
7618 //
7619 // -- The argument list of the specialization shall not be identical
7620 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007621 //
7622 // This rule has since been removed, because it's redundant given DR1495,
7623 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007624 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007625 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007626 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007627 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7628 ClassTemplate->getIdentifier(),
7629 TemplateNameLoc,
7630 Attr,
7631 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007632 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007633 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007634 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007635 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007636 }
Douglas Gregor15301382009-07-30 17:40:51 +00007637
Douglas Gregor2373c592009-05-31 09:31:02 +00007638 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007639 ClassTemplatePartialSpecializationDecl *PrevPartial
7640 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007641 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007642 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007643 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007644 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007645 TemplateParams,
7646 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007647 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007648 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007649 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007650 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00007651 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007652 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007653 Partial->setTemplateParameterListsInfo(
7654 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007655 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007656
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007657 if (!PrevPartial)
7658 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007659 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007660
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007661 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007662 // template specialization, make a note of that.
7663 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7664 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007665
Richard Smith57aae072016-12-28 02:37:25 +00007666 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007667 } else {
7668 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007669 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007670 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007671 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007672 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007673 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007674 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007675 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007676 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007677 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007678 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007679 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007680 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007681 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007682
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007683 if (!PrevDecl)
7684 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007685
David Majnemer678f50b2015-11-18 19:49:19 +00007686 if (CurContext->isDependentContext()) {
David Majnemer678f50b2015-11-18 19:49:19 +00007687 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7688 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007689 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007690 } else {
7691 CanonType = Context.getTypeDeclType(Specialization);
7692 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007693 }
7694
Douglas Gregor06db9f52009-10-12 20:18:28 +00007695 // C++ [temp.expl.spec]p6:
7696 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007697 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007698 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007699 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007700 // use occurs; no diagnostic is required.
7701 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007702 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007703 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007704 // Is there any previous explicit specialization declaration?
7705 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7706 Okay = true;
7707 break;
7708 }
7709 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007710
Douglas Gregorc854c662010-02-26 06:03:23 +00007711 if (!Okay) {
7712 SourceRange Range(TemplateNameLoc, RAngleLoc);
7713 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7714 << Context.getTypeDeclType(Specialization) << Range;
7715
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007716 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007717 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007718 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007719 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007720 return true;
7721 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007723
Douglas Gregor2208a292009-09-26 20:57:03 +00007724 // If this is not a friend, note that this is an explicit specialization.
7725 if (TUK != TUK_Friend)
7726 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007727
7728 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007729 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007730 RecordDecl *Def = Specialization->getDefinition();
7731 NamedDecl *Hidden = nullptr;
7732 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7733 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00007734 SkipBody->Previous = Def;
Richard Smith858e0e02017-05-11 23:11:16 +00007735 makeMergedDefinitionVisible(Hidden);
Richard Smithc7e6ff02015-05-18 20:36:47 +00007736 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007737 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007738 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007739 Diag(Def->getLocation(), diag::note_previous_definition);
7740 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007741 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007742 }
7743 }
7744
Erich Keanec480f302018-07-12 21:09:05 +00007745 ProcessDeclAttributeList(S, Specialization, Attr);
John McCall659a3372010-12-18 03:30:47 +00007746
Richard Smith034b94a2012-08-17 03:20:55 +00007747 // Add alignment attributes if necessary; these attributes are checked when
7748 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00007749 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Richard Smith034b94a2012-08-17 03:20:55 +00007750 AddAlignmentAttributesForRecord(Specialization);
7751 AddMsStructLayoutForRecord(Specialization);
7752 }
7753
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007754 if (ModulePrivateLoc.isValid())
7755 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7756 << (isPartialSpecialization? 1 : 0)
7757 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007758
Douglas Gregord56a91e2009-02-26 22:19:44 +00007759 // Build the fully-sugared type for this class template
7760 // specialization as the user wrote in the specialization
7761 // itself. This means that we'll pretty-print the type retrieved
7762 // from the specialization's declaration the way that the user
7763 // actually wrote the specialization, rather than formatting the
7764 // name based on the "canonical" representation used to store the
7765 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007766 TypeSourceInfo *WrittenTy
7767 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7768 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007769 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007770 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007771 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007772 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007773
Douglas Gregor1e249f82009-02-25 22:18:32 +00007774 // C++ [temp.expl.spec]p9:
7775 // A template explicit specialization is in the scope of the
7776 // namespace in which the template was defined.
7777 //
7778 // We actually implement this paragraph where we set the semantic
7779 // context (in the creation of the ClassTemplateSpecializationDecl),
7780 // but we also maintain the lexical context where the actual
7781 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007782 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007783
Douglas Gregor67a65642009-02-17 23:15:12 +00007784 // We may be starting the definition of this specialization.
Richard Smithc4577662018-09-12 02:13:47 +00007785 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregor67a65642009-02-17 23:15:12 +00007786 Specialization->startDefinition();
7787
Douglas Gregor2208a292009-09-26 20:57:03 +00007788 if (TUK == TUK_Friend) {
7789 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7790 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007791 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007792 /*FIXME:*/KWLoc);
7793 Friend->setAccess(AS_public);
7794 CurContext->addDecl(Friend);
7795 } else {
7796 // Add the specialization into its lexical context, so that it can
7797 // be seen when iterating through the list of declarations in that
7798 // context. However, specializations are not found by name lookup.
7799 CurContext->addDecl(Specialization);
7800 }
Richard Smithc4577662018-09-12 02:13:47 +00007801
7802 if (SkipBody && SkipBody->ShouldSkip)
7803 return SkipBody->Previous;
7804
John McCall48871652010-08-21 09:40:31 +00007805 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007806}
Douglas Gregor333489b2009-03-27 23:10:48 +00007807
John McCall48871652010-08-21 09:40:31 +00007808Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007809 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007810 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007811 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007812 ActOnDocumentableDecl(NewDecl);
7813 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007814}
7815
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007816/// Strips various properties off an implicit instantiation
John McCall4f7ced62010-02-11 01:33:53 +00007817/// that has just been explicitly specialized.
7818static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007819 D->dropAttr<DLLImportAttr>();
7820 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007821
Nico Webere4974382014-12-19 23:52:45 +00007822 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007823 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007824}
7825
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007826/// Compute the diagnostic location for an explicit instantiation
Nico Webera8f80b32012-01-09 19:52:25 +00007827// declaration or definition.
7828static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007829 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007830 // Explicit instantiations following a specialization have no effect and
7831 // hence no PointOfInstantiation. In that case, walk decl backwards
7832 // until a valid name loc is found.
7833 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007834 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7835 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007836 PrevDiagLoc = Prev->getLocation();
7837 }
7838 assert(PrevDiagLoc.isValid() &&
7839 "Explicit instantiation without point of instantiation?");
7840 return PrevDiagLoc;
7841}
7842
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007843/// Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007844/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007845/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007846/// new specialization/instantiation will have any effect.
7847///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007848/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007849/// instantiation.
7850///
7851/// \param NewTSK the kind of the new explicit specialization or instantiation.
7852///
7853/// \param PrevDecl the previous declaration of the entity.
7854///
7855/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7856///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007857/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007858/// declaration was instantiated (either implicitly or explicitly).
7859///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007860/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007861/// specialization or instantiation has no effect and should be ignored.
7862///
7863/// \returns true if there was an error that should prevent the introduction of
7864/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007865bool
7866Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7867 TemplateSpecializationKind NewTSK,
7868 NamedDecl *PrevDecl,
7869 TemplateSpecializationKind PrevTSK,
7870 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007871 bool &HasNoEffect) {
7872 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007873
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007874 switch (NewTSK) {
7875 case TSK_Undeclared:
7876 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007877 assert(
7878 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7879 "previous declaration must be implicit!");
7880 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007881
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007882 case TSK_ExplicitSpecialization:
7883 switch (PrevTSK) {
7884 case TSK_Undeclared:
7885 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007886 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007887 // explicitly specialized or has merely been mentioned without any
7888 // instantiation.
7889 return false;
7890
7891 case TSK_ImplicitInstantiation:
7892 if (PrevPointOfInstantiation.isInvalid()) {
7893 // The declaration itself has not actually been instantiated, so it is
7894 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007895 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007896 return false;
7897 }
7898 // Fall through
Galina Kistanova3779cb32017-06-07 06:25:05 +00007899 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007900
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007901 case TSK_ExplicitInstantiationDeclaration:
7902 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007903 assert((PrevTSK == TSK_ImplicitInstantiation ||
7904 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007905 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007906
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007907 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007908 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007909 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007910 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007911 // implicit instantiation to take place, in every translation unit in
7912 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007913 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007914 // Is there any previous explicit specialization declaration?
7915 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7916 return false;
7917 }
7918
Douglas Gregor1d957a32009-10-27 18:42:08 +00007919 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007920 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007921 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007922 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007923
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007924 return true;
7925 }
Galina Kistanova1d36e832017-06-08 18:20:32 +00007926 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007927
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007928 case TSK_ExplicitInstantiationDeclaration:
7929 switch (PrevTSK) {
7930 case TSK_ExplicitInstantiationDeclaration:
7931 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007932 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007933 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007934
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007935 case TSK_Undeclared:
7936 case TSK_ImplicitInstantiation:
7937 // We're explicitly instantiating something that may have already been
7938 // implicitly instantiated; that's fine.
7939 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007940
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007941 case TSK_ExplicitSpecialization:
7942 // C++0x [temp.explicit]p4:
7943 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007944 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007945 // specialization for that template, the explicit instantiation has no
7946 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007947 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007948 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007949
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007950 case TSK_ExplicitInstantiationDefinition:
7951 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007952 // If an entity is the subject of both an explicit instantiation
7953 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007954 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007955 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007956 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007957
7958 // Explicit instantiations following a specialization have no effect and
7959 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7960 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007961 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7962 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007963 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007964 return false;
7965 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007966
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007967 case TSK_ExplicitInstantiationDefinition:
7968 switch (PrevTSK) {
7969 case TSK_Undeclared:
7970 case TSK_ImplicitInstantiation:
7971 // We're explicitly instantiating something that may have already been
7972 // implicitly instantiated; that's fine.
7973 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007974
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007975 case TSK_ExplicitSpecialization:
7976 // C++ DR 259, C++0x [temp.explicit]p4:
7977 // For a given set of template parameters, if an explicit
7978 // instantiation of a template appears after a declaration of
7979 // an explicit specialization for that template, the explicit
7980 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00007981 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007982 << PrevDecl;
7983 Diag(PrevDecl->getLocation(),
7984 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007985 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007986 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007987
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007988 case TSK_ExplicitInstantiationDeclaration:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007989 // We're explicitly instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007990 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00007991
7992 // C++0x [temp.explicit]p4:
7993 // For a given set of template parameters, if an explicit instantiation
7994 // of a template appears after a declaration of an explicit
7995 // specialization for that template, the explicit instantiation has no
7996 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007997 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00007998 // Is there any previous explicit specialization declaration?
7999 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8000 HasNoEffect = true;
8001 break;
8002 }
8003 }
8004
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008005 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008006
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008007 case TSK_ExplicitInstantiationDefinition:
8008 // C++0x [temp.spec]p5:
8009 // For a given template and a given set of template-arguments,
8010 // - an explicit instantiation definition shall appear at most once
8011 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008012
8013 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8014 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00008015 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008016 : diag::err_explicit_instantiation_duplicate)
8017 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00008018 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00008019 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008020 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008021 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008022 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008024
David Blaikie83d382b2011-09-23 05:06:16 +00008025 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008026}
8027
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008028/// Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00008029/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00008030///
James Dennettf14a6e52012-06-15 22:23:43 +00008031/// The only possible way to get a dependent function template specialization
8032/// is with a friend declaration, like so:
8033///
8034/// \code
8035/// template \<class T> void foo(T);
8036/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00008037/// friend void foo<>(T);
8038/// };
James Dennettf14a6e52012-06-15 22:23:43 +00008039/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00008040///
8041/// There really isn't any useful analysis we can do here, so we
8042/// just store the information.
8043bool
8044Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8045 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8046 LookupResult &Previous) {
8047 // Remove anything from Previous that isn't a function template in
8048 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00008049 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00008050 LookupResult::Filter F = Previous.makeFilter();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008051 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8052 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
John McCallb9c78482010-04-08 09:05:18 +00008053 while (F.hasNext()) {
8054 NamedDecl *D = F.next()->getUnderlyingDecl();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008055 if (!isa<FunctionTemplateDecl>(D)) {
John McCallb9c78482010-04-08 09:05:18 +00008056 F.erase();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008057 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8058 continue;
8059 }
8060
8061 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8062 D->getDeclContext()->getRedeclContext())) {
8063 F.erase();
8064 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8065 continue;
8066 }
John McCallb9c78482010-04-08 09:05:18 +00008067 }
8068 F.done();
8069
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008070 if (Previous.empty()) {
8071 Diag(FD->getLocation(),
8072 diag::err_dependent_function_template_spec_no_match);
8073 for (auto &P : DiscardedCandidates)
8074 Diag(P.second->getLocation(),
8075 diag::note_dependent_function_template_spec_discard_reason)
8076 << P.first;
8077 return true;
8078 }
John McCallb9c78482010-04-08 09:05:18 +00008079
8080 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8081 ExplicitTemplateArgs);
8082 return false;
8083}
8084
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008085/// Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008086/// specialization.
8087///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008088/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008089/// explicit function template specialization. On successful completion,
8090/// the function declaration \p FD will become a function template
8091/// specialization.
8092///
8093/// \param FD the function declaration, which will be updated to become a
8094/// function template specialization.
8095///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008096/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8097/// if any. Note that this may be valid info even when 0 arguments are
8098/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8099/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008100///
Francois Pichet3a44e432011-07-08 06:21:47 +00008101/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008102/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008103bool Sema::CheckFunctionTemplateSpecialization(
8104 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8105 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008106 // The set of function template specializations that could match this
8107 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00008108 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008109 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8110 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008111
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008112 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8113 ConvertedTemplateArgs;
8114
Sebastian Redl50c68252010-08-31 00:36:30 +00008115 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00008116 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8117 I != E; ++I) {
8118 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8119 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008120 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008121 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00008122 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8123 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008124 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008125
Richard Smith574f4f62013-01-14 05:37:29 +00008126 // When matching a constexpr member function template specialization
8127 // against the primary template, we don't yet know whether the
8128 // specialization has an implicit 'const' (because we don't know whether
8129 // it will be a static member function until we know which template it
8130 // specializes), so adjust it now assuming it specializes this template.
8131 QualType FT = FD->getType();
8132 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008133 CXXMethodDecl *OldMD =
8134 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00008135 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008136 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00008137 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8138 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00008139 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008140 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00008141 }
8142 }
8143
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008144 TemplateArgumentListInfo Args;
8145 if (ExplicitTemplateArgs)
8146 Args = *ExplicitTemplateArgs;
8147
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008148 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008149 // A trailing template-argument can be left unspecified in the
8150 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008151 // provided it can be deduced from the function argument type.
8152 // Perform template argument deduction to determine whether we may be
8153 // specializing this template.
8154 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00008155 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008156 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00008157 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8158 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00008159 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8160 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008161 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008162 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00008163 FailedCandidates.addCandidate().set(
8164 I.getPair(), FunTmpl->getTemplatedDecl(),
8165 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008166 (void)TDK;
8167 continue;
8168 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008169
Artem Belevich64135c32016-12-08 19:38:13 +00008170 // Target attributes are part of the cuda function signature, so
8171 // the deduced template's cuda target must match that of the
8172 // specialization. Given that C++ template deduction does not
8173 // take target attributes into account, we reject candidates
8174 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008175 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00008176 IdentifyCUDATarget(Specialization,
8177 /* IgnoreImplicitHDAttributes = */ true) !=
8178 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008179 FailedCandidates.addCandidate().set(
8180 I.getPair(), FunTmpl->getTemplatedDecl(),
8181 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8182 continue;
8183 }
8184
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008185 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008186 if (ExplicitTemplateArgs)
8187 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00008188 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008189 }
8190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008191
Douglas Gregor5de279c2009-09-26 03:41:46 +00008192 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008193 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008194 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008195 FD->getLocation(),
8196 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8197 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00008198 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008199 PDiag(diag::note_function_template_spec_matched));
8200
John McCall58cc69d2010-01-27 01:50:18 +00008201 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008202 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008203
8204 // Ignore access information; it doesn't figure into redeclaration checking.
8205 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00008206
8207 FunctionTemplateSpecializationInfo *SpecInfo
8208 = Specialization->getTemplateSpecializationInfo();
8209 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00008210
8211 // Note: do not overwrite location info if previous template
8212 // specialization kind was explicit.
8213 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00008214 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00008215 Specialization->setLocation(FD->getLocation());
Richard Smith54f04402017-05-18 02:29:20 +00008216 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
Richard Smith5b8b3db2012-02-20 23:28:05 +00008217 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8218 // function can differ from the template declaration with respect to
8219 // the constexpr specifier.
Richard Smith77e9e842017-05-09 23:02:10 +00008220 // FIXME: We need an update record for this AST mutation.
8221 // FIXME: What if there are multiple such prior declarations (for instance,
8222 // from different modules)?
Richard Smith5b8b3db2012-02-20 23:28:05 +00008223 Specialization->setConstexpr(FD->isConstexpr());
8224 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008225
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008226 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00008227 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00008228
8229 // If this is a friend declaration, then we're not really declaring
8230 // an explicit specialization.
8231 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008232
Douglas Gregor54888652009-10-07 00:13:32 +00008233 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00008234 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008235 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00008236 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008237 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008238 false))
Douglas Gregor54888652009-10-07 00:13:32 +00008239 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008240
8241 // C++ [temp.expl.spec]p6:
8242 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008243 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008244 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008245 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008246 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008247 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00008248 if (!isFriend &&
8249 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00008250 TSK_ExplicitSpecialization,
8251 Specialization,
8252 SpecInfo->getTemplateSpecializationKind(),
8253 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008254 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008255 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008256
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008257 // Mark the prior declaration as an explicit specialization, so that later
8258 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008259 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00008260 // Since explicit specializations do not inherit '=delete' from their
8261 // primary function template - check if the 'specialization' that was
8262 // implicitly generated (during template argument deduction for partial
8263 // ordering) from the most specialized of all the function templates that
8264 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8265 // first check that it was implicitly generated during template argument
8266 // deduction by making sure it wasn't referenced, and then reset the deleted
8267 // flag to not-deleted, so that we can inherit that information from 'FD'.
8268 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8269 !Specialization->getCanonicalDecl()->isReferenced()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008270 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali81a88be2016-06-14 03:23:15 +00008271 assert(
8272 Specialization->getCanonicalDecl() == Specialization &&
8273 "This must be the only existing declaration of this specialization");
Richard Smith77e9e842017-05-09 23:02:10 +00008274 // FIXME: We need an update record for this AST mutation.
Faisal Vali81a88be2016-06-14 03:23:15 +00008275 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008276 }
Richard Smith54f04402017-05-18 02:29:20 +00008277 // FIXME: We need an update record for this AST mutation.
John McCall816d75b2010-03-24 07:46:06 +00008278 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008279 MarkUnusedFileScopedDecl(Specialization);
8280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008281
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008282 // Turn the given function declaration into a function template
8283 // specialization, with the template arguments from the previous
8284 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008285 // Take copies of (semantic and syntactic) template argument lists.
8286 const TemplateArgumentList* TemplArgs = new (Context)
8287 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008288 FD->setFunctionTemplateSpecialization(
8289 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8290 SpecInfo->getTemplateSpecializationKind(),
8291 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008292
Artem Belevich64135c32016-12-08 19:38:13 +00008293 // A function template specialization inherits the target attributes
8294 // of its template. (We require the attributes explicitly in the
8295 // code to match, but a template may have implicit attributes by
8296 // virtue e.g. of being constexpr, and it passes these implicit
8297 // attributes on to its specializations.)
8298 if (LangOpts.CUDA)
8299 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8300
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008301 // The "previous declaration" for this function template specialization is
8302 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00008303 Previous.clear();
8304 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008305 return false;
8306}
8307
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008308/// Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008309/// specialization.
8310///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008311/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008312/// explicit member function specialization. On successful completion,
8313/// the function declaration \p FD will become a member function
8314/// specialization.
8315///
Douglas Gregor86d142a2009-10-08 07:24:58 +00008316/// \param Member the member declaration, which will be updated to become a
8317/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008318///
John McCall1f82f242009-11-18 22:49:29 +00008319/// \param Previous the set of declarations, one of which may be specialized
8320/// by this function specialization; the set will be modified to contain the
8321/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008322bool
John McCall1f82f242009-11-18 22:49:29 +00008323Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008324 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00008325
Douglas Gregor86d142a2009-10-08 07:24:58 +00008326 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00008327 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00008328 NamedDecl *Instantiation = nullptr;
8329 NamedDecl *InstantiatedFrom = nullptr;
8330 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008331
John McCall1f82f242009-11-18 22:49:29 +00008332 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008333 // Nowhere to look anyway.
8334 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008335 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8336 I != E; ++I) {
8337 NamedDecl *D = (*I)->getUnderlyingDecl();
8338 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00008339 QualType Adjusted = Function->getType();
8340 if (!hasExplicitCallingConv(Adjusted))
8341 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
Richard Smith4576a772018-09-10 06:35:32 +00008342 // This doesn't handle deduced return types, but both function
8343 // declarations should be undeduced at this point.
Rafael Espindola66747222013-12-10 00:59:31 +00008344 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008345 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008346 Instantiation = Method;
8347 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008348 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008349 break;
8350 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008351 }
8352 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00008353 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008354 VarDecl *PrevVar;
8355 if (Previous.isSingleResult() &&
8356 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00008357 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008358 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008359 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008360 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008361 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008362 }
8363 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008364 CXXRecordDecl *PrevRecord;
8365 if (Previous.isSingleResult() &&
8366 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008367 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008368 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008369 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008370 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008371 }
Richard Smith7d137e32012-03-23 03:33:32 +00008372 } else if (isa<EnumDecl>(Member)) {
8373 EnumDecl *PrevEnum;
8374 if (Previous.isSingleResult() &&
8375 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008376 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00008377 Instantiation = PrevEnum;
8378 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8379 MSInfo = PrevEnum->getMemberSpecializationInfo();
8380 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008381 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008382
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008383 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008384 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008385 // specializations are always out-of-line, the caller will complain about
8386 // this mismatch later.
8387 return false;
8388 }
John McCalle820e5e2010-04-13 20:37:33 +00008389
Richard Smith77e9e842017-05-09 23:02:10 +00008390 // A member specialization in a friend declaration isn't really declaring
8391 // an explicit specialization, just identifying a specific (possibly implicit)
8392 // specialization. Don't change the template specialization kind.
8393 //
8394 // FIXME: Is this really valid? Other compilers reject.
John McCalle820e5e2010-04-13 20:37:33 +00008395 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8396 // Preserve instantiation information.
8397 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8398 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8399 cast<CXXMethodDecl>(InstantiatedFrom),
8400 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8401 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8402 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8403 cast<CXXRecordDecl>(InstantiatedFrom),
8404 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8405 }
8406
8407 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008408 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00008409 return false;
8410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008411
Douglas Gregor86d142a2009-10-08 07:24:58 +00008412 // Make sure that this is a specialization of a member.
8413 if (!InstantiatedFrom) {
8414 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8415 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008416 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8417 return true;
8418 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008419
Douglas Gregor06db9f52009-10-12 20:18:28 +00008420 // C++ [temp.expl.spec]p6:
8421 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00008422 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008423 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008424 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008425 // use occurs; no diagnostic is required.
8426 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00008427
Abramo Bagnara8075c852010-06-12 07:44:57 +00008428 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00008429 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8430 TSK_ExplicitSpecialization,
8431 Instantiation,
8432 MSInfo->getTemplateSpecializationKind(),
8433 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008434 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008435 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008436
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008437 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008438 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008439 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008440 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008441 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008442 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008443
Richard Smith77e9e842017-05-09 23:02:10 +00008444 // Note that this member specialization is an "instantiation of" the
8445 // corresponding member of the original template.
8446 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008447 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8448 if (InstantiationFunction->getTemplateSpecializationKind() ==
8449 TSK_ImplicitInstantiation) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008450 // Explicit specializations of member functions of class templates do not
8451 // inherit '=delete' from the member function they are specializing.
8452 if (InstantiationFunction->isDeleted()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008453 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008454 assert(InstantiationFunction->getCanonicalDecl() ==
8455 InstantiationFunction);
Richard Smith77e9e842017-05-09 23:02:10 +00008456 // FIXME: We need an update record for this AST mutation.
Richard Smith5f274382016-09-28 23:55:27 +00008457 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008458 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008460
Richard Smith77e9e842017-05-09 23:02:10 +00008461 MemberFunction->setInstantiationOfMemberFunction(
8462 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8463 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8464 MemberVar->setInstantiationOfStaticDataMember(
Larisse Voufo39a1e502013-08-06 01:03:05 +00008465 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008466 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8467 MemberClass->setInstantiationOfMemberClass(
8468 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8469 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8470 MemberEnum->setInstantiationOfMemberEnum(
Richard Smith7d137e32012-03-23 03:33:32 +00008471 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008472 } else {
8473 llvm_unreachable("unknown member specialization kind");
Douglas Gregor86d142a2009-10-08 07:24:58 +00008474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008475
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008476 // Save the caller the trouble of having to figure out which declaration
8477 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008478 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008479 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008480 return false;
8481}
8482
Richard Smith77e9e842017-05-09 23:02:10 +00008483/// Complete the explicit specialization of a member of a class template by
8484/// updating the instantiated member to be marked as an explicit specialization.
8485///
8486/// \param OrigD The member declaration instantiated from the template.
8487/// \param Loc The location of the explicit specialization of the member.
8488template<typename DeclT>
8489static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8490 SourceLocation Loc) {
8491 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8492 return;
8493
8494 // FIXME: Inform AST mutation listeners of this AST mutation.
8495 // FIXME: If there are multiple in-class declarations of the member (from
8496 // multiple modules, or a declaration and later definition of a member type),
8497 // should we update all of them?
8498 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8499 OrigD->setLocation(Loc);
8500}
8501
8502void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8503 LookupResult &Previous) {
8504 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8505 if (Instantiation == Member)
8506 return;
8507
8508 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8509 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8510 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8511 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8512 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8513 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8514 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8515 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8516 else
8517 llvm_unreachable("unknown member specialization kind");
8518}
8519
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008520/// Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008521///
8522/// \returns true if a serious error occurs, false otherwise.
8523static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008524 SourceLocation InstLoc,
8525 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008526 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8527 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008528
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008529 if (CurContext->isRecord()) {
8530 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8531 << D;
8532 return true;
8533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008534
Richard Smith050d2612011-10-18 02:28:33 +00008535 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008536 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008537 // template. If the name declared in the explicit instantiation is an
8538 // unqualified name, the explicit instantiation shall appear in the
8539 // namespace where its template is declared or, if that namespace is inline
8540 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008541 //
8542 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008543 if (WasQualifiedName) {
8544 if (CurContext->Encloses(OrigContext))
8545 return false;
8546 } else {
8547 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8548 return false;
8549 }
8550
8551 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8552 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008553 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008554 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008555 diag::err_explicit_instantiation_out_of_scope :
8556 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008557 << D << NS;
8558 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008559 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008560 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008561 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8562 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8563 << D << NS;
8564 } else
8565 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008566 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008567 diag::err_explicit_instantiation_must_be_global :
8568 diag::warn_explicit_instantiation_must_be_global_0x)
8569 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008570 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008571 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008572}
8573
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008574/// Determine whether the given scope specifier has a template-id in it.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008575static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8576 if (!SS.isSet())
8577 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008578
Richard Smith050d2612011-10-18 02:28:33 +00008579 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008580 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008581 // or a static data member of a class template specialization, the name of
8582 // the class template specialization in the qualified-id for the member
8583 // name shall be a simple-template-id.
8584 //
8585 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008586 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8587 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008588 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008589 if (isa<TemplateSpecializationType>(T))
8590 return true;
8591
8592 return false;
8593}
8594
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008595/// Make a dllexport or dllimport attr on a class template specialization take
8596/// effect.
8597static void dllExportImportClassTemplateSpecialization(
8598 Sema &S, ClassTemplateSpecializationDecl *Def) {
8599 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8600 assert(A && "dllExportImportClassTemplateSpecialization called "
8601 "on Def without dllexport or dllimport");
8602
8603 // We reject explicit instantiations in class scope, so there should
8604 // never be any delayed exported classes to worry about.
8605 assert(S.DelayedDllExportClasses.empty() &&
8606 "delayed exports present at explicit instantiation");
8607 S.checkClassLevelDLLAttribute(Def);
8608
8609 // Propagate attribute to base class templates.
8610 for (auto &B : Def->bases()) {
8611 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8612 B.getType()->getAsCXXRecordDecl()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008613 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008614 }
8615
8616 S.referenceDLLExportedClassMethods();
8617}
8618
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008619// Explicit instantiation of a class template specialization
Erich Keanec480f302018-07-12 21:09:05 +00008620DeclResult Sema::ActOnExplicitInstantiation(
8621 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8622 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8623 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
8624 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
8625 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008626 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008627 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008628 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008629 // Check that the specialization uses the same tag kind as the
8630 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008631 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8632 assert(Kind != TTK_Enum &&
8633 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008634
Richard Trieu265c3442016-04-05 21:13:54 +00008635 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8636
8637 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008638 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8639 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008640 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008641 return true;
8642 }
8643
Douglas Gregord9034f02009-05-14 16:41:31 +00008644 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008645 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008646 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008647 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008648 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008649 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008650 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008651 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008652 diag::note_previous_use);
8653 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8654 }
8655
Douglas Gregore47f5a72009-10-14 23:41:34 +00008656 // C++0x [temp.explicit]p2:
8657 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008658 // definition and an explicit instantiation declaration. An explicit
8659 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008660 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8661 ? TSK_ExplicitInstantiationDefinition
8662 : TSK_ExplicitInstantiationDeclaration;
8663
8664 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8665 // Check for dllexport class template instantiation declarations.
Erich Keanee891aa92018-07-13 15:07:47 +00008666 for (const ParsedAttr &AL : Attr) {
8667 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00008668 Diag(ExternLoc,
8669 diag::warn_attribute_dllexport_explicit_instantiation_decl);
Erich Keanec480f302018-07-12 21:09:05 +00008670 Diag(AL.getLoc(), diag::note_attribute);
Hans Wennborgfd76d912015-01-15 21:18:30 +00008671 break;
8672 }
8673 }
8674
8675 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8676 Diag(ExternLoc,
8677 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8678 Diag(A->getLocation(), diag::note_attribute);
8679 }
8680 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008681
Hans Wennborga86a83b2016-05-26 19:42:56 +00008682 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8683 // instantiation declarations for most purposes.
8684 bool DLLImportExplicitInstantiationDef = false;
8685 if (TSK == TSK_ExplicitInstantiationDefinition &&
8686 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8687 // Check for dllimport class template instantiation definitions.
8688 bool DLLImport =
8689 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
Erich Keanee891aa92018-07-13 15:07:47 +00008690 for (const ParsedAttr &AL : Attr) {
8691 if (AL.getKind() == ParsedAttr::AT_DLLImport)
Hans Wennborga86a83b2016-05-26 19:42:56 +00008692 DLLImport = true;
Erich Keanee891aa92018-07-13 15:07:47 +00008693 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborga86a83b2016-05-26 19:42:56 +00008694 // dllexport trumps dllimport here.
8695 DLLImport = false;
8696 break;
8697 }
8698 }
8699 if (DLLImport) {
8700 TSK = TSK_ExplicitInstantiationDeclaration;
8701 DLLImportExplicitInstantiationDef = true;
8702 }
8703 }
8704
Douglas Gregora1f49972009-05-13 00:25:59 +00008705 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008706 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008707 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008708
8709 // Check that the template argument list is well-formed for this
8710 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008711 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008712 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8713 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008714 return true;
8715
Douglas Gregora1f49972009-05-13 00:25:59 +00008716 // Find the class template specialization declaration that
8717 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008718 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008719 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008720 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008721
Abramo Bagnara8075c852010-06-12 07:44:57 +00008722 TemplateSpecializationKind PrevDecl_TSK
8723 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8724
Douglas Gregor54888652009-10-07 00:13:32 +00008725 // C++0x [temp.explicit]p2:
8726 // [...] An explicit instantiation shall appear in an enclosing
8727 // namespace of its template. [...]
8728 //
8729 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008730 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8731 SS.isSet()))
8732 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008733
Craig Topperc3ec1492014-05-26 06:22:03 +00008734 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008735
Abramo Bagnara8075c852010-06-12 07:44:57 +00008736 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008737 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008738 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008739 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008740 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008741 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008742 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008743
Abramo Bagnara8075c852010-06-12 07:44:57 +00008744 // Even though HasNoEffect == true means that this explicit instantiation
8745 // has no effect on semantics, we go on to put its syntax in the AST.
8746
8747 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8748 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008749 // Since the only prior class template specialization with these
8750 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008751 // declaration node as our own, updating the source location
8752 // for the template name to reflect our new declaration.
8753 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008754 Specialization = PrevDecl;
8755 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008756 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008757 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008758
8759 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8760 DLLImportExplicitInstantiationDef) {
8761 // The new specialization might add a dllimport attribute.
8762 HasNoEffect = false;
8763 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008764 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008765
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008766 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008767 // Create a new class template specialization declaration node for
8768 // this explicit specialization.
8769 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008770 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008771 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008772 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008773 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008774 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008775 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00008776 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008777
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008778 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008779 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008780 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008781 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008782 }
8783
8784 // Build the fully-sugared type for this explicit instantiation as
8785 // the user wrote in the explicit instantiation itself. This means
8786 // that we'll pretty-print the type retrieved from the
8787 // specialization's declaration the way that the user actually wrote
8788 // the explicit instantiation, rather than formatting the name based
8789 // on the "canonical" representation used to store the template
8790 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008791 TypeSourceInfo *WrittenTy
8792 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8793 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008794 Context.getTypeDeclType(Specialization));
8795 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008796
Abramo Bagnara8075c852010-06-12 07:44:57 +00008797 // Set source locations for keywords.
8798 Specialization->setExternLoc(ExternLoc);
8799 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008800 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008801
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008802 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Erich Keanec480f302018-07-12 21:09:05 +00008803 ProcessDeclAttributeList(S, Specialization, Attr);
Rafael Espindola0b062072012-01-03 06:04:21 +00008804
Abramo Bagnara8075c852010-06-12 07:44:57 +00008805 // Add the explicit instantiation into its lexical context. However,
8806 // since explicit instantiations are never found by name lookup, we
8807 // just put it into the declaration context directly.
8808 Specialization->setLexicalDeclContext(CurContext);
8809 CurContext->addDecl(Specialization);
8810
8811 // Syntax is now OK, so return if it has no other effect on semantics.
8812 if (HasNoEffect) {
8813 // Set the template specialization kind.
8814 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008815 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008816 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008817
8818 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008819 // A definition of a class template or class member template
8820 // shall be in scope at the point of the explicit instantiation of
8821 // the class template or class member template.
8822 //
8823 // This check comes when we actually try to perform the
8824 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008825 ClassTemplateSpecializationDecl *Def
8826 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008827 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008828 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00008829 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008830 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008831 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008832 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8833 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008834
Douglas Gregor1d957a32009-10-27 18:42:08 +00008835 // Instantiate the members of this class template specialization.
8836 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008837 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00008838 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008839 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008840 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8841 // TSK_ExplicitInstantiationDefinition
8842 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00008843 (TSK == TSK_ExplicitInstantiationDefinition ||
8844 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00008845 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008846 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008847
Hans Wennborgc0875502015-06-09 00:39:05 +00008848 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00008849 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8850 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00008851 // In the MS ABI, an explicit instantiation definition can add a dll
8852 // attribute to a template with a previous instantiation declaration.
8853 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008854 auto *A = cast<InheritableAttr>(
8855 getDLLAttr(Specialization)->clone(getASTContext()));
8856 A->setInherited(true);
8857 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008858 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008859 }
8860 }
8861
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008862 // Fix a TSK_ImplicitInstantiation followed by a
8863 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008864 bool NewlyDLLExported =
8865 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8866 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008867 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8868 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8869 // In the MS ABI, an explicit instantiation definition can add a dll
8870 // attribute to a template with a previous implicit instantiation.
8871 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8872 // avoid potentially strange codegen behavior. For example, if we extend
8873 // this conditional to dllimport, and we have a source file calling a
8874 // method on an implicitly instantiated template class instance and then
8875 // declaring a dllimport explicit instantiation definition for the same
8876 // template class, the codegen for the method call will not respect the
8877 // dllimport, while it will with cl. The Def will already have the DLL
8878 // attribute, since the Def and Specialization will be the same in the
8879 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8880 // attribute to the Specialization; we just need to make it take effect.
8881 assert(Def == Specialization &&
8882 "Def and Specialization should match for implicit instantiation");
8883 dllExportImportClassTemplateSpecialization(*this, Def);
8884 }
8885
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008886 // Set the template specialization kind. Make sure it is set before
8887 // instantiating the members which will trigger ASTConsumer callbacks.
8888 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008889 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008890 } else {
8891
8892 // Set the template specialization kind.
8893 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008894 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008895
John McCall48871652010-08-21 09:40:31 +00008896 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008897}
8898
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008899// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008900DeclResult
Erich Keanec480f302018-07-12 21:09:05 +00008901Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
8902 SourceLocation TemplateLoc, unsigned TagSpec,
8903 SourceLocation KWLoc, CXXScopeSpec &SS,
8904 IdentifierInfo *Name, SourceLocation NameLoc,
8905 const ParsedAttributesView &Attr) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008906
Douglas Gregord6ab8742009-05-28 23:31:59 +00008907 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008908 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008909 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008910 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008911 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008912 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008913 SourceLocation(), false, TypeResult(),
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00008914 /*IsTypeSpecifier*/false,
8915 /*IsTemplateParamOrArg*/false);
John McCall7f41d982009-09-11 04:59:25 +00008916 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8917
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008918 if (!TagD)
8919 return true;
8920
John McCall48871652010-08-21 09:40:31 +00008921 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00008922 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008923
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008924 if (Tag->isInvalidDecl())
8925 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008926
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008927 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8928 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8929 if (!Pattern) {
8930 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8931 << Context.getTypeDeclType(Record);
8932 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8933 return true;
8934 }
8935
Douglas Gregore47f5a72009-10-14 23:41:34 +00008936 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008937 // If the explicit instantiation is for a class or member class, the
8938 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00008939 // simple-template-id.
8940 //
8941 // C++98 has the same restriction, just worded differently.
8942 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00008943 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008944 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008945
Douglas Gregore47f5a72009-10-14 23:41:34 +00008946 // C++0x [temp.explicit]p2:
8947 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008948 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00008949 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00008950 TemplateSpecializationKind TSK
8951 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8952 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008953
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008954 // C++0x [temp.explicit]p2:
8955 // [...] An explicit instantiation shall appear in an enclosing
8956 // namespace of its template. [...]
8957 //
8958 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008959 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008960
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008961 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008962 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00008963 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008964 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00008965 PrevDecl = Record;
8966 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008967 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008968 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008969 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008970 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008971 PrevDecl,
8972 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008973 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008974 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008975 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00008976 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008977 return TagD;
8978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008979
Douglas Gregor12e49d32009-10-15 22:53:21 +00008980 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008981 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008982 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00008983 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008984 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00008985 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008986 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008987 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00008988 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00008989 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8990 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00008991 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8992 << Pattern;
8993 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008994 } else {
8995 if (InstantiateClass(NameLoc, Record, Def,
8996 getTemplateInstantiationArgs(Record),
8997 TSK))
8998 return true;
8999
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009000 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00009001 if (!RecordDef)
9002 return true;
9003 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009004 }
9005
Douglas Gregor1d957a32009-10-27 18:42:08 +00009006 // Instantiate all of the members of the class.
9007 InstantiateClassMembers(NameLoc, RecordDef,
9008 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009009
Douglas Gregor88d292c2010-05-13 16:44:06 +00009010 if (TSK == TSK_ExplicitInstantiationDefinition)
9011 MarkVTableUsed(NameLoc, RecordDef, true);
9012
Mike Stump87c57ac2009-05-16 07:39:55 +00009013 // FIXME: We don't have any representation for explicit instantiations of
9014 // member classes. Such a representation is not needed for compilation, but it
9015 // should be available for clients that want to see all of the declarations in
9016 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009017 return TagD;
9018}
9019
John McCallfaf5fb42010-08-26 23:41:50 +00009020DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9021 SourceLocation ExternLoc,
9022 SourceLocation TemplateLoc,
9023 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009024 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009025 // TODO: check if/when DNInfo should replace Name.
9026 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9027 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00009028 if (!Name) {
9029 if (!D.isInvalidType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009030 Diag(D.getDeclSpec().getBeginLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009031 diag::err_explicit_instantiation_requires_name)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009032 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009033
Douglas Gregor450f00842009-09-25 18:43:00 +00009034 return true;
9035 }
9036
9037 // The scope passed in may not be a decl scope. Zip up the scope tree until
9038 // we find one that is.
9039 while ((S->getFlags() & Scope::DeclScope) == 0 ||
9040 (S->getFlags() & Scope::TemplateParamScope) != 0)
9041 S = S->getParent();
9042
9043 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00009044 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9045 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00009046 if (R.isNull())
9047 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009048
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009049 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00009050 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009051 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00009052 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009053 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9054 << Name;
9055 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009056 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009057 != DeclSpec::SCS_unspecified) {
9058 // Complain about then remove the storage class specifier.
9059 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9060 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009061
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009062 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00009063 }
9064
Douglas Gregor3c74d412009-10-14 20:14:33 +00009065 // C++0x [temp.explicit]p1:
9066 // [...] An explicit instantiation of a function template shall not use the
9067 // inline or constexpr specifiers.
9068 // Presumably, this also applies to member functions of class templates as
9069 // well.
Richard Smith83c19292011-10-18 03:44:03 +00009070 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009071 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009072 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00009073 diag::err_explicit_instantiation_inline :
9074 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00009075 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009076 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00009077 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9078 // not already specified.
9079 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9080 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009081
Richard Smith19a311a2017-02-09 22:47:51 +00009082 // A deduction guide is not on the list of entities that can be explicitly
9083 // instantiated.
9084 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009085 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9086 << /*explicit instantiation*/ 0;
Richard Smith19a311a2017-02-09 22:47:51 +00009087 return true;
9088 }
9089
Douglas Gregore47f5a72009-10-14 23:41:34 +00009090 // C++0x [temp.explicit]p2:
9091 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009092 // definition and an explicit instantiation declaration. An explicit
9093 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00009094 TemplateSpecializationKind TSK
9095 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9096 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009097
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009098 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00009099 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00009100
9101 if (!R->isFunctionType()) {
9102 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009103 // A [...] static data member of a class template can be explicitly
9104 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009105 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009106 // C++1y [temp.explicit]p1:
9107 // A [...] variable [...] template specialization can be explicitly
9108 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00009109 if (Previous.isAmbiguous())
9110 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009111
John McCall67c00872009-12-02 08:25:40 +00009112 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00009113 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009114
Larisse Voufo39a1e502013-08-06 01:03:05 +00009115 if (!PrevTemplate) {
9116 if (!Prev || !Prev->isStaticDataMember()) {
9117 // We expect to see a data data member here.
9118 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9119 << Name;
9120 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9121 P != PEnd; ++P)
9122 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9123 return true;
9124 }
9125
9126 if (!Prev->getInstantiatedFromStaticDataMember()) {
9127 // FIXME: Check for explicit specialization?
9128 Diag(D.getIdentifierLoc(),
9129 diag::err_explicit_instantiation_data_member_not_instantiated)
9130 << Prev;
9131 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9132 // FIXME: Can we provide a note showing where this was declared?
9133 return true;
9134 }
9135 } else {
9136 // Explicitly instantiate a variable template.
9137
9138 // C++1y [dcl.spec.auto]p6:
9139 // ... A program that uses auto or decltype(auto) in a context not
9140 // explicitly allowed in this section is ill-formed.
9141 //
9142 // This includes auto-typed variable template instantiations.
9143 if (R->isUndeducedType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009144 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009145 diag::err_auto_not_allowed_var_inst);
9146 return true;
9147 }
9148
Faisal Vali2ab8c152017-12-30 04:15:27 +00009149 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Richard Smithef985ac2013-09-18 02:10:12 +00009150 // C++1y [temp.explicit]p3:
9151 // If the explicit instantiation is for a variable, the unqualified-id
9152 // in the declaration shall be a template-id.
9153 Diag(D.getIdentifierLoc(),
9154 diag::err_explicit_instantiation_without_template_id)
9155 << PrevTemplate;
9156 Diag(PrevTemplate->getLocation(),
9157 diag::note_explicit_instantiation_here);
9158 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00009159 }
9160
Richard Smithef985ac2013-09-18 02:10:12 +00009161 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00009162 TemplateArgumentListInfo TemplateArgs =
9163 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00009164
Larisse Voufo39a1e502013-08-06 01:03:05 +00009165 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9166 D.getIdentifierLoc(), TemplateArgs);
9167 if (Res.isInvalid())
9168 return true;
9169
9170 // Ignore access control bits, we don't need them for redeclaration
9171 // checking.
9172 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00009173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009174
Douglas Gregore47f5a72009-10-14 23:41:34 +00009175 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009176 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009177 // or a static data member of a class template specialization, the name of
9178 // the class template specialization in the qualified-id for the member
9179 // name shall be a simple-template-id.
9180 //
9181 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009182 //
Richard Smith5977d872013-09-18 21:55:14 +00009183 // This does not apply to variable template specializations, where the
9184 // template-id is in the unqualified-id instead.
9185 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009186 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009187 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009188 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009189
Douglas Gregore47f5a72009-10-14 23:41:34 +00009190 // Check the scope of this explicit instantiation.
9191 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009192
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009193 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00009194 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9195 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009196 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009197 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00009198 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009199 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009200
Larisse Voufo39a1e502013-08-06 01:03:05 +00009201 if (!HasNoEffect) {
9202 // Instantiate static data member or variable template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009203 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Louis Dionnee6e81752018-10-10 15:32:29 +00009204 // Merge attributes.
9205 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009206 if (TSK == TSK_ExplicitInstantiationDefinition)
9207 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9208 }
9209
9210 // Check the new variable specialization against the parsed input.
9211 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009212 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009213 diag::err_invalid_var_template_spec_type)
9214 << 0 << PrevTemplate << R << Prev->getType();
9215 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9216 << 2 << PrevTemplate->getDeclName();
9217 return true;
9218 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009219
Douglas Gregor450f00842009-09-25 18:43:00 +00009220 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00009221 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009222 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009223
9224 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00009225 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00009226 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00009227 TemplateArgumentListInfo TemplateArgs;
Faisal Vali2ab8c152017-12-30 04:15:27 +00009228 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00009229 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00009230 HasExplicitTemplateArgs = true;
9231 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009232
Douglas Gregor450f00842009-09-25 18:43:00 +00009233 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009234 // A [...] function [...] can be explicitly instantiated from its template.
9235 // A member function [...] of a class template can be explicitly
9236 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009237 // template.
John McCall27c11dd2017-06-07 23:00:05 +00009238 UnresolvedSet<8> TemplateMatches;
9239 FunctionDecl *NonTemplateMatch = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009240 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00009241 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9242 P != PEnd; ++P) {
9243 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00009244 if (!HasExplicitTemplateArgs) {
9245 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00009246 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9247 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00009248 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
John McCall27c11dd2017-06-07 23:00:05 +00009249 if (Method->getPrimaryTemplate()) {
9250 TemplateMatches.addDecl(Method, P.getAccess());
9251 } else {
9252 // FIXME: Can this assert ever happen? Needs a test.
9253 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9254 NonTemplateMatch = Method;
9255 }
Douglas Gregord90fd522009-09-25 21:45:23 +00009256 }
Douglas Gregor450f00842009-09-25 18:43:00 +00009257 }
9258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009259
Douglas Gregor450f00842009-09-25 18:43:00 +00009260 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9261 if (!FunTmpl)
9262 continue;
9263
Larisse Voufo98b20f12013-07-19 23:00:19 +00009264 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00009265 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009266 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009267 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00009268 (HasExplicitTemplateArgs ? &TemplateArgs
9269 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00009270 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009271 // Keep track of almost-matches.
9272 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00009273 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009274 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00009275 (void)TDK;
9276 continue;
9277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009278
Artem Belevich64135c32016-12-08 19:38:13 +00009279 // Target attributes are part of the cuda function signature, so
9280 // the cuda target of the instantiated function must match that of its
9281 // template. Given that C++ template deduction does not take
9282 // target attributes into account, we reject candidates here that
9283 // have a different target.
9284 if (LangOpts.CUDA &&
9285 IdentifyCUDATarget(Specialization,
9286 /* IgnoreImplicitHDAttributes = */ true) !=
Erich Keanec480f302018-07-12 21:09:05 +00009287 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
Artem Belevich64135c32016-12-08 19:38:13 +00009288 FailedCandidates.addCandidate().set(
9289 P.getPair(), FunTmpl->getTemplatedDecl(),
9290 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9291 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009292 }
9293
John McCall27c11dd2017-06-07 23:00:05 +00009294 TemplateMatches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00009295 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009296
John McCall27c11dd2017-06-07 23:00:05 +00009297 FunctionDecl *Specialization = NonTemplateMatch;
9298 if (!Specialization) {
9299 // Find the most specialized function template specialization.
9300 UnresolvedSetIterator Result = getMostSpecialized(
9301 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9302 D.getIdentifierLoc(),
9303 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9304 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9305 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00009306
John McCall27c11dd2017-06-07 23:00:05 +00009307 if (Result == TemplateMatches.end())
9308 return true;
John McCall58cc69d2010-01-27 01:50:18 +00009309
John McCall27c11dd2017-06-07 23:00:05 +00009310 // Ignore access control bits, we don't need them for redeclaration checking.
9311 Specialization = cast<FunctionDecl>(*Result);
9312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009313
Alexey Bataev73983912014-11-06 10:10:50 +00009314 // C++11 [except.spec]p4
9315 // In an explicit instantiation an exception-specification may be specified,
9316 // but is not required.
9317 // If an exception-specification is specified in an explicit instantiation
9318 // directive, it shall be compatible with the exception-specifications of
9319 // other declarations of that function.
9320 if (auto *FPT = R->getAs<FunctionProtoType>())
9321 if (FPT->hasExceptionSpec()) {
9322 unsigned DiagID =
9323 diag::err_mismatched_exception_spec_explicit_instantiation;
9324 if (getLangOpts().MicrosoftExt)
9325 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9326 bool Result = CheckEquivalentExceptionSpec(
9327 PDiag(DiagID) << Specialization->getType(),
9328 PDiag(diag::note_explicit_instantiation_here),
9329 Specialization->getType()->getAs<FunctionProtoType>(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009330 Specialization->getLocation(), FPT, D.getBeginLoc());
Alexey Bataev73983912014-11-06 10:10:50 +00009331 // In Microsoft mode, mismatching exception specifications just cause a
9332 // warning.
9333 if (!getLangOpts().MicrosoftExt && Result)
9334 return true;
9335 }
9336
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009337 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009338 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009339 diag::err_explicit_instantiation_member_function_not_instantiated)
9340 << Specialization
9341 << (Specialization->getTemplateSpecializationKind() ==
9342 TSK_ExplicitSpecialization);
9343 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9344 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009345 }
9346
Douglas Gregorec9fd132012-01-14 16:38:05 +00009347 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00009348 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9349 PrevDecl = Specialization;
9350
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009351 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00009352 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009353 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009354 PrevDecl,
9355 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009356 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009357 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009358 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009359
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009360 // FIXME: We may still want to build some representation of this
9361 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00009362 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00009363 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009364 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00009365
Erich Keanec480f302018-07-12 21:09:05 +00009366 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009367
Hans Wennborgb8304a62017-11-29 23:44:11 +00009368 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9369 // instantiation declarations.
9370 if (TSK == TSK_ExplicitInstantiationDefinition &&
9371 Specialization->hasAttr<DLLImportAttr>() &&
9372 Context.getTargetInfo().getCXXABI().isMicrosoft())
9373 TSK = TSK_ExplicitInstantiationDeclaration;
9374
9375 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9376
Richard Smitheb36ddf2014-04-24 22:45:46 +00009377 if (Specialization->isDefined()) {
9378 // Let the ASTConsumer know that this function has been explicitly
9379 // instantiated now, and its linkage might have changed.
9380 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9381 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00009382 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009383
Douglas Gregore47f5a72009-10-14 23:41:34 +00009384 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009385 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009386 // or a static data member of a class template specialization, the name of
9387 // the class template specialization in the qualified-id for the member
9388 // name shall be a simple-template-id.
9389 //
9390 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009391 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Faisal Vali2ab8c152017-12-30 04:15:27 +00009392 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009393 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00009394 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009395 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009396 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009397 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009398
Douglas Gregore47f5a72009-10-14 23:41:34 +00009399 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009400 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00009401 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009402 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00009403 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009404
Douglas Gregor450f00842009-09-25 18:43:00 +00009405 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00009406 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009407}
9408
John McCallfaf5fb42010-08-26 23:41:50 +00009409TypeResult
Faisal Vali090da2d2018-01-01 18:23:28 +00009410Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
John McCall7f41d982009-09-11 04:59:25 +00009411 const CXXScopeSpec &SS, IdentifierInfo *Name,
9412 SourceLocation TagLoc, SourceLocation NameLoc) {
9413 // This has to hold, because SS is expected to be defined.
9414 assert(Name && "Expected a name in a dependent tag");
9415
Aaron Ballman4a979672014-01-03 13:56:08 +00009416 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009417 if (!NNS)
9418 return true;
9419
Abramo Bagnara6150c882010-05-11 21:36:43 +00009420 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009421
Douglas Gregorba41d012010-04-24 16:38:41 +00009422 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9423 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009424 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009425 return true;
9426 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009427
Douglas Gregore7c20652011-03-02 00:47:37 +00009428 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009429 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009430 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009431
Douglas Gregore7c20652011-03-02 00:47:37 +00009432 // Create type-source location information for this type.
9433 TypeLocBuilder TLB;
9434 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009435 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009436 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9437 TL.setNameLoc(NameLoc);
9438 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009439}
9440
John McCallfaf5fb42010-08-26 23:41:50 +00009441TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009442Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9443 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009444 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009445 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009446 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009447
Richard Smith0bf8a4922011-10-18 20:49:44 +00009448 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9449 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009450 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009451 diag::warn_cxx98_compat_typename_outside_of_template :
9452 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009453 << FixItHint::CreateRemoval(TypenameLoc);
9454
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009455 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009456 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9457 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009458 if (T.isNull())
9459 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009460
9461 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9462 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009463 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009464 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009465 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009466 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009467 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009468 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009469 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009470 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009471 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009472 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009473
John McCallba7bf592010-08-24 05:47:05 +00009474 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009475}
9476
John McCallfaf5fb42010-08-26 23:41:50 +00009477TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009478Sema::ActOnTypenameType(Scope *S,
9479 SourceLocation TypenameLoc,
9480 const CXXScopeSpec &SS,
9481 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009482 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009483 IdentifierInfo *TemplateII,
9484 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009485 SourceLocation LAngleLoc,
9486 ASTTemplateArgsPtr TemplateArgsIn,
9487 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009488 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9489 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009490 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009491 diag::warn_cxx98_compat_typename_outside_of_template :
9492 diag::ext_typename_outside_of_template)
9493 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009494
Richard Smith74f02342017-01-19 21:00:13 +00009495 // Strangely, non-type results are not ignored by this lookup, so the
9496 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009497 if (TypenameLoc.isValid()) {
9498 auto *LookupRD =
9499 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9500 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9501 Diag(TemplateIILoc,
9502 diag::ext_out_of_line_qualified_id_type_names_constructor)
9503 << TemplateII << 0 /*injected-class-name used as template name*/
9504 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9505 }
Richard Smith74f02342017-01-19 21:00:13 +00009506 }
9507
Douglas Gregorb09518c2011-02-27 22:46:49 +00009508 // Translate the parser's template argument list in our AST format.
9509 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9510 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009511
Douglas Gregorb09518c2011-02-27 22:46:49 +00009512 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009513 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9514 // Construct a dependent template specialization type.
9515 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009516 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009517 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9518 DTN->getQualifier(),
9519 DTN->getIdentifier(),
9520 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009521
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009522 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009523 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009524 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009525 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009526 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9527 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009528 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009529 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009530 SpecTL.setLAngleLoc(LAngleLoc);
9531 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009532 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9533 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009534 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009535 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009536
Richard Smith74f02342017-01-19 21:00:13 +00009537 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009538 if (T.isNull())
9539 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009540
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009541 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009542 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009543 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009544 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009545 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009546 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009547 SpecTL.setLAngleLoc(LAngleLoc);
9548 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009549 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9550 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009551
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009552 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9553 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009554 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009555 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009556
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009557 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9558 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009559}
9560
Douglas Gregorb09518c2011-02-27 22:46:49 +00009561
Richard Smith6f8d2c62012-05-09 05:17:00 +00009562/// Determine whether this failed name lookup should be treated as being
9563/// disabled by a usage of std::enable_if.
9564static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009565 SourceRange &CondRange, Expr *&Cond) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009566 // We must be looking for a ::type...
9567 if (!II.isStr("type"))
9568 return false;
9569
9570 // ... within an explicitly-written template specialization...
9571 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9572 return false;
9573 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009574 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9575 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9576 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009577 return false;
George Burgess IV00f70bd2018-03-01 05:43:23 +00009578 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009579
9580 // ... which names a complete class template declaration...
9581 const TemplateDecl *EnableIfDecl =
9582 EnableIfTST->getTemplateName().getAsTemplateDecl();
9583 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9584 return false;
9585
9586 // ... called "enable_if".
9587 const IdentifierInfo *EnableIfII =
9588 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9589 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9590 return false;
9591
9592 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009593 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009594
9595 // Dig out the condition.
9596 Cond = nullptr;
9597 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9598 != TemplateArgument::Expression)
9599 return true;
9600
9601 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9602
9603 // Ignore Boolean literals; they add no value.
9604 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9605 Cond = nullptr;
9606
Richard Smith6f8d2c62012-05-09 05:17:00 +00009607 return true;
9608}
9609
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009610/// Build the type that describes a C++ typename specifier,
Douglas Gregor333489b2009-03-27 23:10:48 +00009611/// e.g., "typename T::type".
9612QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009613Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009614 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009615 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009616 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009617 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009618 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009619 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009620
John McCall0b66eb32010-05-01 00:40:08 +00009621 DeclContext *Ctx = computeDeclContext(SS);
9622 if (!Ctx) {
9623 // If the nested-name-specifier is dependent and couldn't be
9624 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009625 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009626 return Context.getDependentNameType(Keyword,
9627 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009628 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009629 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009630
John McCall0b66eb32010-05-01 00:40:08 +00009631 // If the nested-name-specifier refers to the current instantiation,
9632 // the "typename" keyword itself is superfluous. In C++03, the
9633 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9634 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009635 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009636
John McCall0b66eb32010-05-01 00:40:08 +00009637 if (RequireCompleteDeclContext(SS, Ctx))
9638 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009639
9640 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009641 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009642 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009643 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009644 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009645 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009646 case LookupResult::NotFound: {
9647 // If we're looking up 'type' within a template named 'enable_if', produce
9648 // a more specific diagnostic.
9649 SourceRange CondRange;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009650 Expr *Cond = nullptr;
9651 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9652 // If we have a condition, narrow it down to the specific failed
9653 // condition.
9654 if (Cond) {
9655 Expr *FailedCond;
9656 std::string FailedDescription;
9657 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00009658 findFailedBooleanCondition(Cond);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009659
9660 Diag(FailedCond->getExprLoc(),
9661 diag::err_typename_nested_not_found_requirement)
9662 << FailedDescription
9663 << FailedCond->getSourceRange();
9664 return QualType();
9665 }
9666
Richard Smith6f8d2c62012-05-09 05:17:00 +00009667 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009668 << Ctx << CondRange;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009669 return QualType();
9670 }
9671
Douglas Gregore40876a2009-10-13 21:16:44 +00009672 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009673 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009674 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009675
9676 case LookupResult::FoundUnresolvedValue: {
9677 // We found a using declaration that is a value. Most likely, the using
9678 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009679 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009680 IILoc);
9681 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9682 << Name << Ctx << FullRange;
9683 if (UnresolvedUsingValueDecl *Using
9684 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009685 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009686 Diag(Loc, diag::note_using_value_decl_missing_typename)
9687 << FixItHint::CreateInsertion(Loc, "typename ");
9688 }
9689 }
9690 // Fall through to create a dependent typename type, from which we can recover
9691 // better.
Galina Kistanova3779cb32017-06-07 06:25:05 +00009692 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009693
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009694 case LookupResult::NotFoundInCurrentInstantiation:
9695 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009696 return Context.getDependentNameType(Keyword,
9697 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009698 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009699
9700 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009701 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009702 // C++ [class.qual]p2:
9703 // In a lookup in which function names are not ignored and the
9704 // nested-name-specifier nominates a class C, if the name specified
9705 // after the nested-name-specifier, when looked up in C, is the
9706 // injected-class-name of C [...] then the name is instead considered
9707 // to name the constructor of class C.
9708 //
9709 // Unlike in an elaborated-type-specifier, function names are not ignored
9710 // in typename-specifier lookup. However, they are ignored in all the
9711 // contexts where we form a typename type with no keyword (that is, in
9712 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9713 //
9714 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9715 // ignore functions, but that appears to be an oversight.
9716 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9717 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9718 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9719 FoundRD->isInjectedClassName() &&
9720 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9721 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9722 << &II << 1 << 0 /*'typename' keyword used*/;
9723
Abramo Bagnara6150c882010-05-11 21:36:43 +00009724 // We found a type. Build an ElaboratedType, since the
9725 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009726 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009727 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009728 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009729 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009730 }
9731
Richard Smithee579842017-01-30 20:39:26 +00009732 // C++ [dcl.type.simple]p2:
9733 // A type-specifier of the form
9734 // typename[opt] nested-name-specifier[opt] template-name
9735 // is a placeholder for a deduced class type [...].
Aaron Ballmanc351fba2017-12-04 20:27:34 +00009736 if (getLangOpts().CPlusPlus17) {
Richard Smithee579842017-01-30 20:39:26 +00009737 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9738 return Context.getElaboratedType(
9739 Keyword, QualifierLoc.getNestedNameSpecifier(),
9740 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9741 QualType(), false));
9742 }
9743 }
Richard Smith600b5262017-01-26 20:40:47 +00009744
Douglas Gregor333489b2009-03-27 23:10:48 +00009745 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009746 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009747 break;
9748
9749 case LookupResult::FoundOverloaded:
9750 DiagID = diag::err_typename_nested_not_type;
9751 Referenced = *Result.begin();
9752 break;
9753
John McCall6538c932009-10-10 05:48:19 +00009754 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009755 return QualType();
9756 }
9757
9758 // If we get here, it's because name lookup did not find a
9759 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009760 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009761 IILoc);
9762 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009763 if (Referenced)
9764 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9765 << Name;
9766 return QualType();
9767}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009768
9769namespace {
9770 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009771 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009772 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009773 SourceLocation Loc;
9774 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009775
Douglas Gregor15acfb92009-08-06 16:20:37 +00009776 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009777 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009778
Mike Stump11289f42009-09-09 15:08:12 +00009779 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009780 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009781 DeclarationName Entity)
9782 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009783 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009784
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009785 /// Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009786 /// transformed.
9787 ///
9788 /// For the purposes of type reconstruction, a type has already been
9789 /// transformed if it is NULL or if it is not dependent.
9790 bool AlreadyTransformed(QualType T) {
9791 return T.isNull() || !T->isDependentType();
9792 }
Mike Stump11289f42009-09-09 15:08:12 +00009793
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009794 /// Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009795 /// rebuilt.
9796 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009797
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009798 /// Returns the name of the entity whose type is being rebuilt.
Douglas Gregor15acfb92009-08-06 16:20:37 +00009799 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009800
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009801 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +00009802 /// information is known based on another transformation.
9803 void setBase(SourceLocation Loc, DeclarationName Entity) {
9804 this->Loc = Loc;
9805 this->Entity = Entity;
9806 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009807
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00009808 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9809 // Lambdas never need to be transformed.
9810 return E;
9811 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00009812 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009813} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00009814
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009815/// Rebuilds a type within the context of the current instantiation.
Douglas Gregor15acfb92009-08-06 16:20:37 +00009816///
Mike Stump11289f42009-09-09 15:08:12 +00009817/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00009818/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00009819/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00009820/// partial specialization thereof). This routine will rebuild that type now
9821/// that we have entered the declarator's scope, which may produce different
9822/// canonical types, e.g.,
9823///
9824/// \code
9825/// template<typename T>
9826/// struct X {
9827/// typedef T* pointer;
9828/// pointer data();
9829/// };
9830///
9831/// template<typename T>
9832/// typename X<T>::pointer X<T>::data() { ... }
9833/// \endcode
9834///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00009835/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009836/// since we do not know that we can look into X<T> when we parsed the type.
9837/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00009838/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00009839/// as the canonical type of T*, allowing the return types of the out-of-line
9840/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00009841TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9842 SourceLocation Loc,
9843 DeclarationName Name) {
9844 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00009845 return T;
Mike Stump11289f42009-09-09 15:08:12 +00009846
Douglas Gregor15acfb92009-08-06 16:20:37 +00009847 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9848 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00009849}
Douglas Gregorbe999392009-09-15 16:23:51 +00009850
John McCalldadc5752010-08-24 06:29:42 +00009851ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00009852 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9853 DeclarationName());
9854 return Rebuilder.TransformExpr(E);
9855}
9856
John McCall99b2fe52010-04-29 23:50:39 +00009857bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00009858 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009859 return true;
John McCall2408e322010-04-27 00:57:59 +00009860
Douglas Gregor10176412011-02-25 16:07:42 +00009861 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009862 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9863 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009864 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009865 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009866 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009867 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009868
Douglas Gregor10176412011-02-25 16:07:42 +00009869 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009870 return false;
John McCall2408e322010-04-27 00:57:59 +00009871}
9872
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009873/// Rebuild the template parameters now that we know we're in a current
Douglas Gregor041b0842011-10-14 15:31:12 +00009874/// instantiation.
9875bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9876 TemplateParameterList *Params) {
9877 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9878 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009879
Douglas Gregor041b0842011-10-14 15:31:12 +00009880 // There is nothing to rebuild in a type parameter.
9881 if (isa<TemplateTypeParmDecl>(Param))
9882 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009883
Douglas Gregor041b0842011-10-14 15:31:12 +00009884 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009885 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009886 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9887 if (RebuildTemplateParamsInCurrentInstantiation(
9888 TTP->getTemplateParameters()))
9889 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009890
Douglas Gregor041b0842011-10-14 15:31:12 +00009891 continue;
9892 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009893
Douglas Gregor041b0842011-10-14 15:31:12 +00009894 // Rebuild the type of a non-type template parameter.
9895 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009896 TypeSourceInfo *NewTSI
9897 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9898 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009899 NTTP->getDeclName());
9900 if (!NewTSI)
9901 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009902
Erik Pilkington9f9462a2018-08-07 22:59:02 +00009903 if (NewTSI->getType()->isUndeducedType()) {
9904 // C++17 [temp.dep.expr]p3:
9905 // An id-expression is type-dependent if it contains
9906 // - an identifier associated by name lookup with a non-type
9907 // template-parameter declared with a type that contains a
9908 // placeholder type (7.1.7.4),
9909 NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
9910 }
9911
Douglas Gregor041b0842011-10-14 15:31:12 +00009912 if (NewTSI != NTTP->getTypeSourceInfo()) {
9913 NTTP->setTypeSourceInfo(NewTSI);
9914 NTTP->setType(NewTSI->getType());
9915 }
9916 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009917
Douglas Gregor041b0842011-10-14 15:31:12 +00009918 return false;
9919}
9920
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009921/// Produces a formatted string that describes the binding of
Douglas Gregorbe999392009-09-15 16:23:51 +00009922/// template parameters to template arguments.
9923std::string
9924Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9925 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009926 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00009927}
9928
9929std::string
9930Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9931 const TemplateArgument *Args,
9932 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009933 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00009934 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00009935
Douglas Gregore62e6a02009-11-11 19:13:48 +00009936 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009937 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009938
Douglas Gregorbe999392009-09-15 16:23:51 +00009939 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00009940 if (I >= NumArgs)
9941 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009942
Douglas Gregorbe999392009-09-15 16:23:51 +00009943 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009944 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00009945 else
Douglas Gregor0192c232010-12-20 16:52:59 +00009946 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009947
Douglas Gregorbe999392009-09-15 16:23:51 +00009948 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00009949 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00009950 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00009951 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00009952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009953
Douglas Gregor0192c232010-12-20 16:52:59 +00009954 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00009955 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00009956 }
Douglas Gregor0192c232010-12-20 16:52:59 +00009957
9958 Out << ']';
9959 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00009960}
Francois Pichet1c229c02011-04-22 22:18:13 +00009961
Richard Smithe40f2ba2013-08-07 21:41:30 +00009962void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9963 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00009964 if (!FD)
9965 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00009966
Justin Lebar28f09c52016-10-10 16:26:08 +00009967 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00009968
9969 // Take tokens to avoid allocations
9970 LPT->Toks.swap(Toks);
9971 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00009972 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00009973
9974 FD->setLateTemplateParsed(true);
9975}
9976
9977void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9978 if (!FD)
9979 return;
9980 FD->setLateTemplateParsed(false);
9981}
Francois Pichet1c229c02011-04-22 22:18:13 +00009982
9983bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9984 DeclContext *DC = CurContext;
9985
9986 while (DC) {
9987 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9988 const FunctionDecl *FD = RD->isLocalClass();
9989 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9990 } else if (DC->isTranslationUnit() || DC->isNamespace())
9991 return false;
9992
9993 DC = DC->getParent();
9994 }
9995 return false;
9996}
Richard Smith6739a102016-05-05 00:56:12 +00009997
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009998namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009999/// Walk the path from which a declaration was instantiated, and check
Richard Smith6739a102016-05-05 00:56:12 +000010000/// that every explicit specialization along that path is visible. This enforces
10001/// C++ [temp.expl.spec]/6:
10002///
10003/// If a template, a member template or a member of a class template is
10004/// explicitly specialized then that specialization shall be declared before
10005/// the first use of that specialization that would cause an implicit
10006/// instantiation to take place, in every translation unit in which such a
10007/// use occurs; no diagnostic is required.
10008///
10009/// and also C++ [temp.class.spec]/1:
10010///
10011/// A partial specialization shall be declared before the first use of a
10012/// class template specialization that would make use of the partial
10013/// specialization as the result of an implicit or explicit instantiation
10014/// in every translation unit in which such a use occurs; no diagnostic is
10015/// required.
10016class ExplicitSpecializationVisibilityChecker {
10017 Sema &S;
10018 SourceLocation Loc;
10019 llvm::SmallVector<Module *, 8> Modules;
10020
10021public:
10022 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10023 : S(S), Loc(Loc) {}
10024
10025 void check(NamedDecl *ND) {
10026 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10027 return checkImpl(FD);
10028 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10029 return checkImpl(RD);
10030 if (auto *VD = dyn_cast<VarDecl>(ND))
10031 return checkImpl(VD);
10032 if (auto *ED = dyn_cast<EnumDecl>(ND))
10033 return checkImpl(ED);
10034 }
10035
10036private:
10037 void diagnose(NamedDecl *D, bool IsPartialSpec) {
10038 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10039 : Sema::MissingImportKind::ExplicitSpecialization;
10040 const bool Recover = true;
10041
10042 // If we got a custom set of modules (because only a subset of the
10043 // declarations are interesting), use them, otherwise let
10044 // diagnoseMissingImport intelligently pick some.
10045 if (Modules.empty())
10046 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10047 else
10048 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10049 }
10050
10051 // Check a specific declaration. There are three problematic cases:
10052 //
10053 // 1) The declaration is an explicit specialization of a template
10054 // specialization.
10055 // 2) The declaration is an explicit specialization of a member of an
10056 // templated class.
10057 // 3) The declaration is an instantiation of a template, and that template
10058 // is an explicit specialization of a member of a templated class.
10059 //
10060 // We don't need to go any deeper than that, as the instantiation of the
10061 // surrounding class / etc is not triggered by whatever triggered this
10062 // instantiation, and thus should be checked elsewhere.
10063 template<typename SpecDecl>
10064 void checkImpl(SpecDecl *Spec) {
10065 bool IsHiddenExplicitSpecialization = false;
10066 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10067 IsHiddenExplicitSpecialization =
10068 Spec->getMemberSpecializationInfo()
10069 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
Richard Smith54f04402017-05-18 02:29:20 +000010070 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
Richard Smith6739a102016-05-05 00:56:12 +000010071 } else {
10072 checkInstantiated(Spec);
10073 }
10074
10075 if (IsHiddenExplicitSpecialization)
10076 diagnose(Spec->getMostRecentDecl(), false);
10077 }
10078
10079 void checkInstantiated(FunctionDecl *FD) {
10080 if (auto *TD = FD->getPrimaryTemplate())
10081 checkTemplate(TD);
10082 }
10083
10084 void checkInstantiated(CXXRecordDecl *RD) {
10085 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10086 if (!SD)
10087 return;
10088
10089 auto From = SD->getSpecializedTemplateOrPartial();
10090 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10091 checkTemplate(TD);
10092 else if (auto *TD =
10093 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10094 if (!S.hasVisibleDeclaration(TD))
10095 diagnose(TD, true);
10096 checkTemplate(TD);
10097 }
10098 }
10099
10100 void checkInstantiated(VarDecl *RD) {
10101 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10102 if (!SD)
10103 return;
10104
10105 auto From = SD->getSpecializedTemplateOrPartial();
10106 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10107 checkTemplate(TD);
10108 else if (auto *TD =
10109 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10110 if (!S.hasVisibleDeclaration(TD))
10111 diagnose(TD, true);
10112 checkTemplate(TD);
10113 }
10114 }
10115
10116 void checkInstantiated(EnumDecl *FD) {}
10117
10118 template<typename TemplDecl>
10119 void checkTemplate(TemplDecl *TD) {
10120 if (TD->isMemberSpecialization()) {
10121 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10122 diagnose(TD->getMostRecentDecl(), false);
10123 }
10124 }
10125};
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010126} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +000010127
10128void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10129 if (!getLangOpts().Modules)
10130 return;
10131
10132 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10133}
10134
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010135/// Check whether a template partial specialization that we've discovered
Richard Smith6739a102016-05-05 00:56:12 +000010136/// is hidden, and produce suitable diagnostics if so.
10137void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10138 NamedDecl *Spec) {
10139 llvm::SmallVector<Module *, 8> Modules;
10140 if (!hasVisibleDeclaration(Spec, &Modules))
10141 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10142 MissingImportKind::PartialSpecialization,
10143 /*Recover*/true);
10144}