blob: 58ad439747e15d0edfe92a8eb326152ca1cb5a47 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00007//
8// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +000010
Douglas Gregor15acfb92009-08-06 16:20:37 +000011#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000012#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000013#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000014#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000015#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000018#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000019#include "clang/AST/TypeVisitor.h"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000020#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/DeclSpec.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/ParsedTemplate.h"
27#include "clang/Sema/Scope.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000031#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000032#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000033#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000034
Eric Fiselier6ad68552016-07-01 01:24:09 +000035#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000036using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000038
John McCall9b72f892010-11-10 02:40:36 +000039// Exported for use by Parser.
40SourceRange
41clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
42 unsigned N) {
43 if (!N) return SourceRange();
44 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
45}
46
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000047namespace clang {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000048/// [temp.constr.decl]p2: A template's associated constraints are
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000049/// defined as a single constraint-expression derived from the introduced
50/// constraint-expressions [ ... ].
51///
52/// \param Params The template parameter list and optional requires-clause.
53///
54/// \param FD The underlying templated function declaration for a function
55/// template.
56static Expr *formAssociatedConstraints(TemplateParameterList *Params,
57 FunctionDecl *FD);
58}
59
60static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
61 FunctionDecl *FD) {
62 // FIXME: Concepts: collect additional introduced constraint-expressions
63 assert(!FD && "Cannot collect constraints from function declaration yet.");
64 return Params->getRequiresClause();
65}
66
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000067/// Determine whether the declaration found is acceptable as the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +000068/// of a template and, if so, return that template declaration. Otherwise,
Richard Smithafcfb6b2019-02-15 21:53:07 +000069/// returns null.
70///
71/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
72/// is true. In all other cases it will return a TemplateDecl (or null).
73NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
74 bool AllowFunctionTemplates,
75 bool AllowDependent) {
76 D = D->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000077
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000078 if (isa<TemplateDecl>(D)) {
79 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000080 return nullptr;
81
Richard Smithafcfb6b2019-02-15 21:53:07 +000082 return D;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000083 }
Mike Stump11289f42009-09-09 15:08:12 +000084
Douglas Gregorb7bfe792009-09-02 22:59:36 +000085 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
86 // C++ [temp.local]p1:
87 // Like normal (non-template) classes, class templates have an
88 // injected-class-name (Clause 9). The injected-class-name
89 // can be used with or without a template-argument-list. When
90 // it is used without a template-argument-list, it is
91 // equivalent to the injected-class-name followed by the
92 // template-parameters of the class template enclosed in
93 // <>. When it is used with a template-argument-list, it
94 // refers to the specified class template specialization,
95 // which could be the current specialization or another
96 // specialization.
97 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000098 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000099 if (Record->getDescribedClassTemplate())
100 return Record->getDescribedClassTemplate();
101
102 if (ClassTemplateSpecializationDecl *Spec
103 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
104 return Spec->getSpecializedTemplate();
105 }
Mike Stump11289f42009-09-09 15:08:12 +0000106
Craig Topperc3ec1492014-05-26 06:22:03 +0000107 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000108 }
Mike Stump11289f42009-09-09 15:08:12 +0000109
Richard Smithcbebd622018-05-14 20:52:48 +0000110 // 'using Dependent::foo;' can resolve to a template name.
111 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
112 // injected-class-name).
Richard Smithafcfb6b2019-02-15 21:53:07 +0000113 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
Richard Smithcbebd622018-05-14 20:52:48 +0000114 return D;
115
Craig Topperc3ec1492014-05-26 06:22:03 +0000116 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000117}
118
Simon Pilgrim6905d222016-12-30 22:55:33 +0000119void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Richard Smithafcfb6b2019-02-15 21:53:07 +0000120 bool AllowFunctionTemplates,
121 bool AllowDependent) {
John McCalle66edc12009-11-24 19:00:30 +0000122 LookupResult::Filter filter = R.makeFilter();
123 while (filter.hasNext()) {
124 NamedDecl *Orig = filter.next();
Richard Smithafcfb6b2019-02-15 21:53:07 +0000125 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
John McCalle66edc12009-11-24 19:00:30 +0000126 filter.erase();
John McCalle66edc12009-11-24 19:00:30 +0000127 }
128 filter.done();
129}
130
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000131bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
Richard Smithafcfb6b2019-02-15 21:53:07 +0000132 bool AllowFunctionTemplates,
133 bool AllowDependent) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000134 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Richard Smithafcfb6b2019-02-15 21:53:07 +0000135 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000136 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +0000137
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000138 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000139}
140
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000141TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000142 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000143 bool hasTemplateKeyword,
Richard Smithc08b6932018-04-27 02:00:13 +0000144 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000145 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000146 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000147 TemplateTy &TemplateResult,
148 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000149 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000150
Douglas Gregor3cf81312009-11-03 23:16:33 +0000151 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000152 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000153
Douglas Gregor3cf81312009-11-03 23:16:33 +0000154 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000155 case UnqualifiedIdKind::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000156 TName = DeclarationName(Name.Identifier);
157 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000158
Faisal Vali2ab8c152017-12-30 04:15:27 +0000159 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000160 TName = Context.DeclarationNames.getCXXOperatorName(
161 Name.OperatorFunctionId.Operator);
162 break;
163
Faisal Vali2ab8c152017-12-30 04:15:27 +0000164 case UnqualifiedIdKind::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000165 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
166 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000167
Douglas Gregor3cf81312009-11-03 23:16:33 +0000168 default:
169 return TNK_Non_template;
170 }
Mike Stump11289f42009-09-09 15:08:12 +0000171
John McCallba7bf592010-08-24 05:47:05 +0000172 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000173
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000174 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000175 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
176 MemberOfUnknownSpecialization))
177 return TNK_Non_template;
John McCallfb3f9ba2010-08-28 20:17:00 +0000178 if (R.empty()) return TNK_Non_template;
Richard Smith40bd10b2019-02-15 00:29:04 +0000179
Richard Smithafcfb6b2019-02-15 21:53:07 +0000180 NamedDecl *D = nullptr;
181 if (R.isAmbiguous()) {
182 // If we got an ambiguity involving a non-function template, treat this
183 // as a template name, and pick an arbitrary template for error recovery.
184 bool AnyFunctionTemplates = false;
185 for (NamedDecl *FoundD : R) {
186 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
187 if (isa<FunctionTemplateDecl>(FoundTemplate))
188 AnyFunctionTemplates = true;
189 else {
190 D = FoundTemplate;
191 break;
192 }
193 }
194 }
195
196 // If we didn't find any templates at all, this isn't a template name.
197 // Leave the ambiguity for a later lookup to diagnose.
198 if (!D && !AnyFunctionTemplates) {
199 R.suppressDiagnostics();
200 return TNK_Non_template;
201 }
202
203 // If the only templates were function templates, filter out the rest.
204 // We'll diagnose the ambiguity later.
205 if (!D)
206 FilterAcceptableTemplateNames(R);
John McCalldcc71402010-08-13 02:23:42 +0000207 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000208
Richard Smithafcfb6b2019-02-15 21:53:07 +0000209 // At this point, we have either picked a single template name declaration D
210 // or we have a non-empty set of results R containing either one template name
211 // declaration or a set of function templates.
212
John McCalld28ae272009-12-02 08:04:21 +0000213 TemplateName Template;
214 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000215
John McCalld28ae272009-12-02 08:04:21 +0000216 unsigned ResultCount = R.end() - R.begin();
Richard Smithafcfb6b2019-02-15 21:53:07 +0000217 if (!D && ResultCount > 1) {
John McCalld28ae272009-12-02 08:04:21 +0000218 // We assume that we'll preserve the qualifier from a function
219 // template name in other ways.
220 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
221 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000222
223 // We'll do this lookup again later.
224 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000225 } else {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000226 if (!D) {
227 D = getAsTemplateNameDecl(*R.begin());
228 assert(D && "unambiguous result is not a template name");
229 }
230
231 if (isa<UnresolvedUsingValueDecl>(D)) {
232 // We don't yet know whether this is a template-name or not.
233 MemberOfUnknownSpecialization = true;
234 return TNK_Non_template;
235 }
236
237 TemplateDecl *TD = cast<TemplateDecl>(D);
John McCalld28ae272009-12-02 08:04:21 +0000238
239 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000240 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000241 Template = Context.getQualifiedTemplateName(Qualifier,
242 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000243 } else {
244 Template = TemplateName(TD);
245 }
246
John McCalldcc71402010-08-13 02:23:42 +0000247 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000248 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000249
250 // We'll do this lookup again later.
251 R.suppressDiagnostics();
252 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000253 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000254 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
Faisal Valia534f072018-04-26 00:42:40 +0000255 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000256 TemplateKind =
Faisal Valia534f072018-04-26 00:42:40 +0000257 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000258 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000259 }
Mike Stump11289f42009-09-09 15:08:12 +0000260
John McCalld28ae272009-12-02 08:04:21 +0000261 TemplateResult = TemplateTy::make(Template);
262 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000263}
264
Richard Smith278890f2017-02-10 20:39:58 +0000265bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
266 SourceLocation NameLoc,
267 ParsedTemplateTy *Template) {
268 CXXScopeSpec SS;
269 bool MemberOfUnknownSpecialization = false;
270
271 // We could use redeclaration lookup here, but we don't need to: the
272 // syntactic form of a deduction guide is enough to identify it even
273 // if we can't look up the template name at all.
274 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000275 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
276 /*EnteringContext*/ false,
277 MemberOfUnknownSpecialization))
278 return false;
Richard Smith278890f2017-02-10 20:39:58 +0000279
280 if (R.empty()) return false;
281 if (R.isAmbiguous()) {
282 // FIXME: Diagnose an ambiguity if we find at least one template.
283 R.suppressDiagnostics();
284 return false;
285 }
286
287 // We only treat template-names that name type templates as valid deduction
288 // guide names.
289 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
290 if (!TD || !getAsTypeTemplateDecl(TD))
291 return false;
292
293 if (Template)
294 *Template = TemplateTy::make(TemplateName(TD));
295 return true;
296}
297
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000298bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000299 SourceLocation IILoc,
300 Scope *S,
301 const CXXScopeSpec *SS,
302 TemplateTy &SuggestedTemplate,
303 TemplateNameKind &SuggestedKind) {
304 // We can't recover unless there's a dependent scope specifier preceding the
305 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000306 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000307 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
308 computeDeclContext(*SS))
309 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000310
Douglas Gregor18473f32010-01-12 21:28:44 +0000311 // The code is missing a 'template' keyword prior to the dependent template
312 // name.
313 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
314 Diag(IILoc, diag::err_template_kw_missing)
315 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000316 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000317 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000318 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
319 SuggestedKind = TNK_Dependent_template_name;
320 return true;
321}
322
Richard Smith79810042018-05-11 02:43:08 +0000323bool Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000324 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000325 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000326 bool EnteringContext,
Richard Smith79810042018-05-11 02:43:08 +0000327 bool &MemberOfUnknownSpecialization,
328 SourceLocation TemplateKWLoc) {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000329 Found.setTemplateNameLookup(true);
330
John McCalle66edc12009-11-24 19:00:30 +0000331 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000332 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000333 DeclContext *LookupCtx = nullptr;
Richard Smith79810042018-05-11 02:43:08 +0000334 bool IsDependent = false;
John McCalle66edc12009-11-24 19:00:30 +0000335 if (!ObjectType.isNull()) {
336 // This nested-name-specifier occurs in a member access expression, e.g.,
337 // x->B::f, and we are looking into the type of the object.
338 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
339 LookupCtx = computeDeclContext(ObjectType);
Richard Smith79810042018-05-11 02:43:08 +0000340 IsDependent = !LookupCtx;
341 assert((IsDependent || !ObjectType->isIncompleteType() ||
Richard Smith5ed79562013-06-07 20:03:01 +0000342 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000343 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000344
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000345 // Template names cannot appear inside an Objective-C class or object type.
346 if (ObjectType->isObjCObjectOrInterfaceType()) {
347 Found.clear();
Richard Smith79810042018-05-11 02:43:08 +0000348 return false;
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000349 }
John McCalle66edc12009-11-24 19:00:30 +0000350 } else if (SS.isSet()) {
351 // This nested-name-specifier occurs after another nested-name-specifier,
352 // so long into the context associated with the prior nested-name-specifier.
353 LookupCtx = computeDeclContext(SS, EnteringContext);
Richard Smith79810042018-05-11 02:43:08 +0000354 IsDependent = !LookupCtx;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000355
John McCalle66edc12009-11-24 19:00:30 +0000356 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000357 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
Richard Smith79810042018-05-11 02:43:08 +0000358 return true;
John McCalle66edc12009-11-24 19:00:30 +0000359 }
360
361 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000362 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000363 if (LookupCtx) {
364 // Perform "qualified" name lookup into the declaration context we
365 // computed, which is either the type of the base of a member access
366 // expression or the declaration context associated with a prior
367 // nested-name-specifier.
368 LookupQualifiedName(Found, LookupCtx);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000369
Richard Smith79810042018-05-11 02:43:08 +0000370 // FIXME: The C++ standard does not clearly specify what happens in the
371 // case where the object type is dependent, and implementations vary. In
372 // Clang, we treat a name after a . or -> as a template-name if lookup
373 // finds a non-dependent member or member of the current instantiation that
374 // is a type template, or finds no such members and lookup in the context
375 // of the postfix-expression finds a type template. In the latter case, the
376 // name is nonetheless dependent, and we may resolve it to a member of an
377 // unknown specialization when we come to instantiate the template.
378 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
John McCalle66edc12009-11-24 19:00:30 +0000379 }
380
Richard Smith79810042018-05-11 02:43:08 +0000381 if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
382 // C++ [basic.lookup.classref]p1:
383 // In a class member access expression (5.2.5), if the . or -> token is
384 // immediately followed by an identifier followed by a <, the
385 // identifier must be looked up to determine whether the < is the
386 // beginning of a template argument list (14.2) or a less-than operator.
387 // The identifier is first looked up in the class of the object
388 // expression. If the identifier is not found, it is then looked up in
389 // the context of the entire postfix-expression and shall name a class
390 // template.
391 if (S)
392 LookupName(Found, S);
393
394 if (!ObjectType.isNull()) {
395 // FIXME: We should filter out all non-type templates here, particularly
396 // variable templates and concepts. But the exclusion of alias templates
397 // and template template parameters is a wording defect.
398 AllowFunctionTemplatesInLookup = false;
399 ObjectTypeSearchedInScope = true;
400 }
401
402 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
403 }
404
Richard Smithafcfb6b2019-02-15 21:53:07 +0000405 if (Found.isAmbiguous())
406 return false;
407
Richard Smith79810042018-05-11 02:43:08 +0000408 if (Found.empty() && !IsDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000409 // If we did not find any names, attempt to correct any typos.
410 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000411 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000412 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Bruno Ricci70ad3962019-03-25 17:08:51 +0000413 DefaultFilterCCC FilterCCC{};
414 FilterCCC.WantTypeSpecifiers = false;
415 FilterCCC.WantExpressionKeywords = false;
416 FilterCCC.WantRemainingKeywords = false;
417 FilterCCC.WantCXXNamedCasts = true;
418 if (TypoCorrection Corrected =
419 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
420 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000421 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000422 if (auto *ND = Corrected.getFoundDecl())
423 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000424 FilterAcceptableTemplateNames(Found);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000425 if (Found.isAmbiguous()) {
426 Found.clear();
427 } else if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000428 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000429 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
430 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000431 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000432 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
433 << Name << LookupCtx << DroppedSpecifier
434 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000435 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000436 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000437 }
John McCalle9cccd82010-06-16 08:42:20 +0000438 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000439 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000440 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000441 }
442 }
443
Richard Smith79810042018-05-11 02:43:08 +0000444 NamedDecl *ExampleLookupResult =
445 Found.empty() ? nullptr : Found.getRepresentativeDecl();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000446 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000447 if (Found.empty()) {
Richard Smith79810042018-05-11 02:43:08 +0000448 if (IsDependent) {
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000449 MemberOfUnknownSpecialization = true;
Richard Smith79810042018-05-11 02:43:08 +0000450 return false;
451 }
452
453 // If a 'template' keyword was used, a lookup that finds only non-template
454 // names is an error.
455 if (ExampleLookupResult && TemplateKWLoc.isValid()) {
456 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
457 << Found.getLookupName() << SS.getRange();
Richard Smithcbebd622018-05-14 20:52:48 +0000458 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
Richard Smith79810042018-05-11 02:43:08 +0000459 diag::note_template_kw_refers_to_non_template)
460 << Found.getLookupName();
461 return true;
462 }
463
464 return false;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000465 }
John McCalle66edc12009-11-24 19:00:30 +0000466
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000467 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000468 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000469 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000470 // [...] If the lookup in the class of the object expression finds a
471 // template, the name is also looked up in the context of the entire
472 // postfix-expression and [...]
473 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000474 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000475 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
476 LookupOrdinaryName);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000477 FoundOuter.setTemplateNameLookup(true);
John McCalle66edc12009-11-24 19:00:30 +0000478 LookupName(FoundOuter, S);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000479 // FIXME: We silently accept an ambiguous lookup here, in violation of
480 // [basic.lookup]/1.
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000481 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000482
Richard Smithafcfb6b2019-02-15 21:53:07 +0000483 NamedDecl *OuterTemplate;
John McCalle66edc12009-11-24 19:00:30 +0000484 if (FoundOuter.empty()) {
485 // - if the name is not found, the name found in the class of the
486 // object expression is used, otherwise
Richard Smithafcfb6b2019-02-15 21:53:07 +0000487 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
488 !(OuterTemplate =
489 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
John McCalle66edc12009-11-24 19:00:30 +0000490 // - if the name is found in the context of the entire
491 // postfix-expression and does not name a class template, the name
492 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000493 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000494 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000495 // - if the name found is a class template, it must refer to the same
496 // entity as the one found in the class of the object expression,
497 // otherwise the program is ill-formed.
498 if (!Found.isSingleResult() ||
Richard Smithafcfb6b2019-02-15 21:53:07 +0000499 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
500 OuterTemplate->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000502 diag::ext_nested_name_member_ref_lookup_ambiguous)
503 << Found.getLookupName()
504 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000505 Diag(Found.getRepresentativeDecl()->getLocation(),
506 diag::note_ambig_member_ref_object_type)
507 << ObjectType;
508 Diag(FoundOuter.getFoundDecl()->getLocation(),
509 diag::note_ambig_member_ref_scope);
510
511 // Recover by taking the template that we found in the object
512 // expression's type.
513 }
514 }
515 }
Richard Smith79810042018-05-11 02:43:08 +0000516
517 return false;
John McCalle66edc12009-11-24 19:00:30 +0000518}
519
Richard Smith42bc73a2017-05-10 02:30:28 +0000520void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
521 SourceLocation Less,
522 SourceLocation Greater) {
523 if (TemplateName.isInvalid())
524 return;
525
526 DeclarationNameInfo NameInfo;
527 CXXScopeSpec SS;
528 LookupNameKind LookupKind;
529
530 DeclContext *LookupCtx = nullptr;
531 NamedDecl *Found = nullptr;
Richard Smithbf5bcf22018-06-26 23:20:26 +0000532 bool MissingTemplateKeyword = false;
Richard Smith42bc73a2017-05-10 02:30:28 +0000533
534 // Figure out what name we looked up.
Richard Smithbf5bcf22018-06-26 23:20:26 +0000535 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
536 NameInfo = DRE->getNameInfo();
537 SS.Adopt(DRE->getQualifierLoc());
538 LookupKind = LookupOrdinaryName;
539 Found = DRE->getFoundDecl();
540 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000541 NameInfo = ME->getMemberNameInfo();
542 SS.Adopt(ME->getQualifierLoc());
543 LookupKind = LookupMemberName;
544 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
545 Found = ME->getMemberDecl();
Richard Smithbf5bcf22018-06-26 23:20:26 +0000546 } else if (auto *DSDRE =
547 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
548 NameInfo = DSDRE->getNameInfo();
549 SS.Adopt(DSDRE->getQualifierLoc());
550 MissingTemplateKeyword = true;
551 } else if (auto *DSME =
552 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
553 NameInfo = DSME->getMemberNameInfo();
554 SS.Adopt(DSME->getQualifierLoc());
555 MissingTemplateKeyword = true;
Richard Smith42bc73a2017-05-10 02:30:28 +0000556 } else {
Richard Smithbf5bcf22018-06-26 23:20:26 +0000557 llvm_unreachable("unexpected kind of potential template name");
558 }
559
560 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
561 // was missing.
562 if (MissingTemplateKeyword) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000563 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
564 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
Richard Smithbf5bcf22018-06-26 23:20:26 +0000565 return;
Richard Smith42bc73a2017-05-10 02:30:28 +0000566 }
567
568 // Try to correct the name by looking for templates and C++ named casts.
569 struct TemplateCandidateFilter : CorrectionCandidateCallback {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000570 Sema &S;
571 TemplateCandidateFilter(Sema &S) : S(S) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000572 WantTypeSpecifiers = false;
573 WantExpressionKeywords = false;
574 WantRemainingKeywords = false;
575 WantCXXNamedCasts = true;
576 };
577 bool ValidateCandidate(const TypoCorrection &Candidate) override {
578 if (auto *ND = Candidate.getCorrectionDecl())
Richard Smithafcfb6b2019-02-15 21:53:07 +0000579 return S.getAsTemplateNameDecl(ND);
Richard Smith42bc73a2017-05-10 02:30:28 +0000580 return Candidate.isKeyword();
581 }
Bruno Ricci70ad3962019-03-25 17:08:51 +0000582
583 std::unique_ptr<CorrectionCandidateCallback> clone() override {
584 return llvm::make_unique<TemplateCandidateFilter>(*this);
585 }
Richard Smith42bc73a2017-05-10 02:30:28 +0000586 };
587
588 DeclarationName Name = NameInfo.getName();
Bruno Ricci70ad3962019-03-25 17:08:51 +0000589 TemplateCandidateFilter CCC(*this);
590 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
591 CTK_ErrorRecovery, LookupCtx)) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000592 auto *ND = Corrected.getFoundDecl();
593 if (ND)
Richard Smithafcfb6b2019-02-15 21:53:07 +0000594 ND = getAsTemplateNameDecl(ND);
Richard Smith42bc73a2017-05-10 02:30:28 +0000595 if (ND || Corrected.isKeyword()) {
596 if (LookupCtx) {
597 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
598 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
599 Name.getAsString() == CorrectedStr;
600 diagnoseTypo(Corrected,
601 PDiag(diag::err_non_template_in_member_template_id_suggest)
602 << Name << LookupCtx << DroppedSpecifier
Richard Smith52f8d192017-05-10 21:32:16 +0000603 << SS.getRange(), false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000604 } else {
605 diagnoseTypo(Corrected,
606 PDiag(diag::err_non_template_in_template_id_suggest)
Richard Smith52f8d192017-05-10 21:32:16 +0000607 << Name, false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000608 }
609 if (Found)
610 Diag(Found->getLocation(),
611 diag::note_non_template_in_template_id_found);
612 return;
613 }
614 }
615
616 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
617 << Name << SourceRange(Less, Greater);
618 if (Found)
619 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
620}
621
John McCallcd4b4772009-12-02 03:53:29 +0000622/// ActOnDependentIdExpression - Handle a dependent id-expression that
623/// was just parsed. This is only possible with an explicit scope
624/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000625ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000626Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000627 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000628 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000629 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000630 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000631 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632
Reid Kleckner1af391df2016-03-11 18:59:12 +0000633 // C++11 [expr.prim.general]p12:
634 // An id-expression that denotes a non-static data member or non-static
635 // member function of a class can only be used:
636 // (...)
637 // - if that id-expression denotes a non-static data member and it
638 // appears in an unevaluated operand.
639 //
640 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
641 // CXXDependentScopeMemberExpr. The former can instantiate to either
642 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
643 // always a MemberExpr.
644 bool MightBeCxx11UnevalField =
645 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
646
Akira Hatanakad644e022016-12-16 03:19:41 +0000647 // Check if the nested name specifier is an enum type.
648 bool IsEnum = false;
649 if (NestedNameSpecifier *NNS = SS.getScopeRep())
650 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
651
652 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000653 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
Brian Gesiak5488ab42019-01-11 01:54:53 +0000654 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000655
John McCalle66edc12009-11-24 19:00:30 +0000656 // Since the 'this' expression is synthesized, we don't need to
657 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000658 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000659
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000660 return CXXDependentScopeMemberExpr::Create(
661 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
662 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
663 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000664 }
665
Abramo Bagnara7945c982012-01-27 09:46:47 +0000666 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000667}
668
John McCalldadc5752010-08-24 06:29:42 +0000669ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000670Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000671 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000672 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000673 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000674 return DependentScopeDeclRefExpr::Create(
675 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
676 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000677}
678
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000679
680/// Determine whether we would be unable to instantiate this template (because
681/// it either has no definition, or is in the process of being instantiated).
682bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
683 NamedDecl *Instantiation,
684 bool InstantiatedFromMember,
685 const NamedDecl *Pattern,
686 const NamedDecl *PatternDef,
687 TemplateSpecializationKind TSK,
688 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000689 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
690 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000691
Richard Smithedbc6e92016-10-14 21:41:24 +0000692 bool IsEntityBeingDefined = false;
693 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
694 IsEntityBeingDefined = TD->isBeingDefined();
695
696 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000697 NamedDecl *SuggestedDef = nullptr;
698 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
699 /*OnlyNeedComplete*/false)) {
700 // If we're allowed to diagnose this and recover, do so.
701 bool Recover = Complain && !isSFINAEContext();
702 if (Complain)
703 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
704 Sema::MissingImportKind::Definition, Recover);
705 return !Recover;
706 }
707 return false;
708 }
709
Richard Smith6f4e2e02016-08-23 19:41:39 +0000710 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
711 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000712
Richard Smithedbc6e92016-10-14 21:41:24 +0000713 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000714 QualType InstantiationTy;
715 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
716 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000717 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000718 Diag(PointOfInstantiation,
719 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000720 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000721 << InstantiationTy;
722 // Not much point in noting the template declaration here, since
723 // we're lexically inside it.
724 Instantiation->setInvalidDecl();
725 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000726 if (isa<FunctionDecl>(Instantiation)) {
727 Diag(PointOfInstantiation,
728 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000729 << /*member function*/ 1 << Instantiation->getDeclName()
730 << Instantiation->getDeclContext();
731 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000732 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000733 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000734 Diag(PointOfInstantiation,
735 diag::err_implicit_instantiate_member_undefined)
736 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000737 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000738 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000739 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000740 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000741 Diag(PointOfInstantiation,
742 diag::err_explicit_instantiation_undefined_func_template)
743 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000744 Note = diag::note_explicit_instantiation_here;
745 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000746 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
747 << (TSK != TSK_ImplicitInstantiation)
748 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000749 Note = diag::note_template_decl_here;
750 } else {
751 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
752 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
753 Diag(PointOfInstantiation,
754 diag::err_explicit_instantiation_undefined_var_template)
755 << Instantiation;
756 Instantiation->setInvalidDecl();
757 } else
758 Diag(PointOfInstantiation,
759 diag::err_explicit_instantiation_undefined_member)
760 << /*static data member*/ 2 << Instantiation->getDeclName()
761 << Instantiation->getDeclContext();
762 Note = diag::note_explicit_instantiation_here;
763 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000764 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000765 if (Note) // Diagnostics were emitted.
766 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000767
768 // In general, Instantiation isn't marked invalid to get more than one
769 // error for multiple undefined instantiations. But the code that does
770 // explicit declaration -> explicit definition conversion can't handle
771 // invalid declarations, so mark as invalid in that case.
772 if (TSK == TSK_ExplicitInstantiationDeclaration)
773 Instantiation->setInvalidDecl();
774 return true;
775}
776
Douglas Gregor5101c242008-12-05 18:15:24 +0000777/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
778/// that the template parameter 'PrevDecl' is being shadowed by a new
779/// declaration at location Loc. Returns true to indicate that this is
780/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000781void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000782 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000783
784 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000785 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000786 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000787
788 // C++ [temp.local]p4:
789 // A template-parameter shall not be redeclared within its
790 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000791 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000792 << cast<NamedDecl>(PrevDecl)->getDeclName();
793 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000794}
795
Douglas Gregor463421d2009-03-03 04:44:36 +0000796/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000797/// the parameter D to reference the templated declaration and return a pointer
798/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000799TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
800 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
801 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000802 return Temp;
803 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000804 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000805}
806
Douglas Gregoreb29d182011-01-05 17:40:24 +0000807ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
808 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000809 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000810 "Only template template arguments can be pack expansions here");
811 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
812 "Template template argument pack expansion without packs");
813 ParsedTemplateArgument Result(*this);
814 Result.EllipsisLoc = EllipsisLoc;
815 return Result;
816}
817
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000818static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
819 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000821 switch (Arg.getKind()) {
822 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000823 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000824 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000825 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000826 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000827 return TemplateArgumentLoc(TemplateArgument(T), DI);
828 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000829
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000830 case ParsedTemplateArgument::NonType: {
831 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
832 return TemplateArgumentLoc(TemplateArgument(E), E);
833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000835 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000836 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000837 TemplateArgument TArg;
838 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000839 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000840 else
841 TArg = Template;
842 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000843 Arg.getScopeSpec().getWithLocInContext(
844 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000845 Arg.getLocation(),
846 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000847 }
848 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000850 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000851}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000852
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000853/// Translates template arguments as provided by the parser
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000854/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000855void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
856 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000857 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000858 TemplateArgs.addArgument(translateTemplateArgument(*this,
859 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000860}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000861
Richard Smithb80d5402013-06-25 22:21:36 +0000862static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
863 SourceLocation Loc,
864 IdentifierInfo *Name) {
865 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
Richard Smithbecb92d2017-10-10 22:33:17 +0000866 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
Richard Smithb80d5402013-06-25 22:21:36 +0000867 if (PrevDecl && PrevDecl->isTemplateParameter())
868 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
869}
870
Richard Smith77a9c602018-02-28 03:02:23 +0000871/// Convert a parsed type into a parsed template argument. This is mostly
872/// trivial, except that we may have parsed a C++17 deduced class template
873/// specialization type, in which case we should form a template template
874/// argument instead of a type template argument.
875ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
876 TypeSourceInfo *TInfo;
877 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
878 if (T.isNull())
879 return ParsedTemplateArgument();
880 assert(TInfo && "template argument with no location");
881
882 // If we might have formed a deduced template specialization type, convert
883 // it to a template template argument.
884 if (getLangOpts().CPlusPlus17) {
885 TypeLoc TL = TInfo->getTypeLoc();
886 SourceLocation EllipsisLoc;
887 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
888 EllipsisLoc = PET.getEllipsisLoc();
889 TL = PET.getPatternLoc();
890 }
891
892 CXXScopeSpec SS;
893 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
894 SS.Adopt(ET.getQualifierLoc());
895 TL = ET.getNamedTypeLoc();
896 }
897
898 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
899 TemplateName Name = DTST.getTypePtr()->getTemplateName();
900 if (SS.isSet())
901 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
902 /*HasTemplateKeyword*/ false,
903 Name.getAsTemplateDecl());
904 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
905 DTST.getTemplateNameLoc());
906 if (EllipsisLoc.isValid())
907 Result = Result.getTemplatePackExpansion(EllipsisLoc);
908 return Result;
909 }
910 }
911
912 // This is a normal type template argument. Note, if the type template
913 // argument is an injected-class-name for a template, it has a dual nature
Fangrui Song6907ce22018-07-30 19:24:48 +0000914 // and can be used as either a type or a template. We handle that in
Richard Smith77a9c602018-02-28 03:02:23 +0000915 // convertTypeTemplateArgumentToTemplate.
916 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
917 ParsedType.get().getAsOpaquePtr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000918 TInfo->getTypeLoc().getBeginLoc());
Richard Smith77a9c602018-02-28 03:02:23 +0000919}
920
Douglas Gregor5101c242008-12-05 18:15:24 +0000921/// ActOnTypeParameter - Called when a C++ template type parameter
922/// (e.g., "typename T") has been parsed. Typename specifies whether
923/// the keyword "typename" was used to declare the type parameter
924/// (otherwise, "class" was used), and KeyLoc is the location of the
925/// "class" or "typename" keyword. ParamName is the name of the
926/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000927/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000928/// If the type parameter has a default argument, it will be added
929/// later via ActOnTypeParameterDefault.
Faisal Valibe294032017-12-23 18:56:34 +0000930NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000931 SourceLocation EllipsisLoc,
932 SourceLocation KeyLoc,
933 IdentifierInfo *ParamName,
934 SourceLocation ParamNameLoc,
935 unsigned Depth, unsigned Position,
936 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000937 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000938 assert(S->isTemplateParamScope() &&
939 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000940
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000941 SourceLocation Loc = ParamNameLoc;
942 if (!ParamName)
943 Loc = KeyLoc;
944
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000945 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000946 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000947 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000948 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000949 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000950 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000951
952 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000953 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
954
Douglas Gregor5101c242008-12-05 18:15:24 +0000955 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000956 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000957 IdResolver.AddDecl(Param);
958 }
959
Douglas Gregorf5500772011-01-05 15:48:55 +0000960 // C++0x [temp.param]p9:
961 // A default template-argument may be specified for any kind of
962 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000963 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000964 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000965 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000966 }
967
Douglas Gregordc13ded2010-07-01 00:00:45 +0000968 // Handle the default argument, if provided.
969 if (DefaultArg) {
970 TypeSourceInfo *DefaultTInfo;
971 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000972
Douglas Gregordc13ded2010-07-01 00:00:45 +0000973 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000974
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000975 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000976 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000977 UPPC_DefaultArgument))
978 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000979
Douglas Gregordc13ded2010-07-01 00:00:45 +0000980 // Check the template argument itself.
981 if (CheckTemplateArgument(Param, DefaultTInfo)) {
982 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000983 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000984 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985
Richard Smith1469b912015-06-10 00:29:03 +0000986 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000988
John McCall48871652010-08-21 09:40:31 +0000989 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000990}
991
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000992/// Check that the type of a non-type template parameter is
Douglas Gregor463421d2009-03-03 04:44:36 +0000993/// well-formed.
994///
995/// \returns the (possibly-promoted) parameter type if valid;
996/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000997QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
998 SourceLocation Loc) {
999 if (TSI->getType()->isUndeducedType()) {
Erik Pilkington9f9462a2018-08-07 22:59:02 +00001000 // C++17 [temp.dep.expr]p3:
Richard Smith15361a22016-12-28 06:27:18 +00001001 // An id-expression is type-dependent if it contains
1002 // - an identifier associated by name lookup with a non-type
1003 // template-parameter declared with a type that contains a
1004 // placeholder type (7.1.7.4),
1005 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
1006 }
1007
1008 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1009}
1010
1011QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1012 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +00001013 // We don't allow variably-modified types as the type of non-type template
1014 // parameters.
1015 if (T->isVariablyModifiedType()) {
1016 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1017 << T;
1018 return QualType();
1019 }
1020
Douglas Gregor463421d2009-03-03 04:44:36 +00001021 // C++ [temp.param]p4:
1022 //
1023 // A non-type template-parameter shall have one of the following
1024 // (optionally cv-qualified) types:
1025 //
1026 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +00001027 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001028 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +00001029 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001030 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +00001031 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001032 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +00001033 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001034 // -- std::nullptr_t.
1035 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +00001036 // If T is a dependent type, we can't do the check now, so we
1037 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +00001038 T->isDependentType() ||
1039 // Allow use of auto in template parameter declarations.
1040 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +00001041 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1042 // are ignored when determining its type.
1043 return T.getUnqualifiedType();
1044 }
1045
Douglas Gregor463421d2009-03-03 04:44:36 +00001046 // C++ [temp.param]p8:
1047 //
1048 // A non-type template-parameter of type "array of T" or
1049 // "function returning T" is adjusted to be of type "pointer to
1050 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +00001051 else if (T->isArrayType() || T->isFunctionType())
1052 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001053
Douglas Gregor463421d2009-03-03 04:44:36 +00001054 Diag(Loc, diag::err_template_nontype_parm_bad_type)
1055 << T;
1056
1057 return QualType();
1058}
1059
Faisal Valibe294032017-12-23 18:56:34 +00001060NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
John McCall48871652010-08-21 09:40:31 +00001061 unsigned Depth,
1062 unsigned Position,
1063 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +00001064 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +00001065 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +00001066
Faisal Valia223d1c2017-12-22 03:50:55 +00001067 // Check that we have valid decl-specifiers specified.
1068 auto CheckValidDeclSpecifiers = [this, &D] {
1069 // C++ [temp.param]
Fangrui Song6907ce22018-07-30 19:24:48 +00001070 // p1
Malcolm Parsonsfab36802018-04-16 08:31:08 +00001071 // template-parameter:
1072 // ...
1073 // parameter-declaration
Fangrui Song6907ce22018-07-30 19:24:48 +00001074 // p2
Faisal Valia223d1c2017-12-22 03:50:55 +00001075 // ... A storage class shall not be specified in a template-parameter
1076 // declaration.
Fangrui Song6907ce22018-07-30 19:24:48 +00001077 // [dcl.typedef]p1:
Faisal Valia223d1c2017-12-22 03:50:55 +00001078 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1079 // of a parameter-declaration
1080 const DeclSpec &DS = D.getDeclSpec();
1081 auto EmitDiag = [this](SourceLocation Loc) {
1082 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1083 << FixItHint::CreateRemoval(Loc);
1084 };
1085 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1086 EmitDiag(DS.getStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001087
Sam McCall1371cba2017-12-22 07:09:51 +00001088 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
Faisal Valia223d1c2017-12-22 03:50:55 +00001089 EmitDiag(DS.getThreadStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001090
1091 // [dcl.inline]p1:
1092 // The inline specifier can be applied only to the declaration or
Faisal Valia223d1c2017-12-22 03:50:55 +00001093 // definition of a variable or function.
Fangrui Song6907ce22018-07-30 19:24:48 +00001094
Faisal Valia223d1c2017-12-22 03:50:55 +00001095 if (DS.isInlineSpecified())
1096 EmitDiag(DS.getInlineSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001097
Faisal Valia223d1c2017-12-22 03:50:55 +00001098 // [dcl.constexpr]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00001099 // The constexpr specifier shall be applied only to the definition of a
1100 // variable or variable template or the declaration of a function or
Faisal Valia223d1c2017-12-22 03:50:55 +00001101 // function template.
Fangrui Song6907ce22018-07-30 19:24:48 +00001102
Faisal Valia223d1c2017-12-22 03:50:55 +00001103 if (DS.isConstexprSpecified())
1104 EmitDiag(DS.getConstexprSpecLoc());
1105
1106 // [dcl.fct.spec]p1:
1107 // Function-specifiers can be used only in function declarations.
1108
1109 if (DS.isVirtualSpecified())
1110 EmitDiag(DS.getVirtualSpecLoc());
1111
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00001112 if (DS.isExplicitSpecified())
Faisal Valia223d1c2017-12-22 03:50:55 +00001113 EmitDiag(DS.getExplicitSpecLoc());
1114
1115 if (DS.isNoreturnSpecified())
1116 EmitDiag(DS.getNoreturnSpecLoc());
1117 };
1118
1119 CheckValidDeclSpecifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00001120
Richard Smith15361a22016-12-28 06:27:18 +00001121 if (TInfo->getType()->isUndeducedType()) {
1122 Diag(D.getIdentifierLoc(),
1123 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1124 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1125 }
Douglas Gregor5101c242008-12-05 18:15:24 +00001126
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001127 assert(S->isTemplateParamScope() &&
1128 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +00001129 bool Invalid = false;
1130
Richard Smith15361a22016-12-28 06:27:18 +00001131 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001132 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001133 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +00001134 Invalid = true;
1135 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136
Richard Smithb80d5402013-06-25 22:21:36 +00001137 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001138 bool IsParameterPack = D.hasEllipsis();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001139 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1140 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1141 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1142 TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001143 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +00001144
Douglas Gregor5101c242008-12-05 18:15:24 +00001145 if (Invalid)
1146 Param->setInvalidDecl();
1147
Richard Smithb80d5402013-06-25 22:21:36 +00001148 if (ParamName) {
1149 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1150 ParamName);
1151
Douglas Gregor5101c242008-12-05 18:15:24 +00001152 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +00001153 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +00001154 IdResolver.AddDecl(Param);
1155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001156
Douglas Gregorf5500772011-01-05 15:48:55 +00001157 // C++0x [temp.param]p9:
1158 // A default template-argument may be specified for any kind of
1159 // template-parameter that is not a template parameter pack.
1160 if (Default && IsParameterPack) {
1161 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +00001162 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +00001163 }
1164
Douglas Gregordc13ded2010-07-01 00:00:45 +00001165 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001166 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001167 // Check for unexpanded parameter packs.
1168 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1169 return Param;
1170
Douglas Gregordc13ded2010-07-01 00:00:45 +00001171 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +00001172 ExprResult DefaultRes =
1173 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +00001174 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +00001175 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00001176 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001177 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001178 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179
Richard Smith1469b912015-06-10 00:29:03 +00001180 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +00001181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001182
John McCall48871652010-08-21 09:40:31 +00001183 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +00001184}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001185
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001186/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +00001187/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001188/// has been parsed. S is the current scope.
Faisal Valibe294032017-12-23 18:56:34 +00001189NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
John McCall48871652010-08-21 09:40:31 +00001190 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00001191 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +00001192 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +00001193 IdentifierInfo *Name,
1194 SourceLocation NameLoc,
1195 unsigned Depth,
1196 unsigned Position,
1197 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +00001198 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001199 assert(S->isTemplateParamScope() &&
1200 "Template template parameter not in template parameter scope!");
1201
1202 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +00001203 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001204 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +00001205 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001206 NameLoc.isInvalid()? TmpLoc : NameLoc,
1207 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +00001208 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001209 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001210
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001211 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +00001212 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001213 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +00001214 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1215
John McCall48871652010-08-21 09:40:31 +00001216 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001217 IdResolver.AddDecl(Param);
1218 }
1219
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001220 if (Params->size() == 0) {
1221 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1222 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1223 Param->setInvalidDecl();
1224 }
1225
Douglas Gregorf5500772011-01-05 15:48:55 +00001226 // C++0x [temp.param]p9:
1227 // A default template-argument may be specified for any kind of
1228 // template-parameter that is not a template parameter pack.
1229 if (IsParameterPack && !Default.isInvalid()) {
1230 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1231 Default = ParsedTemplateArgument();
1232 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001233
Douglas Gregordc13ded2010-07-01 00:00:45 +00001234 if (!Default.isInvalid()) {
1235 // Check only that we have a template template argument. We don't want to
1236 // try to check well-formedness now, because our template template parameter
1237 // might have dependent types in its template parameters, which we wouldn't
1238 // be able to match now.
1239 //
1240 // If none of the template template parameter's template arguments mention
1241 // other template parameters, we could actually perform more checking here.
1242 // However, it isn't worth doing.
1243 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1244 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +00001245 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +00001246 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00001247 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001248 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001249
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001250 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001251 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001252 DefaultArg.getArgument().getAsTemplate(),
1253 UPPC_DefaultArgument))
1254 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001255
Richard Smith1469b912015-06-10 00:29:03 +00001256 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +00001257 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001258
John McCall48871652010-08-21 09:40:31 +00001259 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +00001260}
1261
Hubert Tongf608c052016-04-29 18:05:37 +00001262/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1263/// constrained by RequiresClause, that contains the template parameters in
1264/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +00001265TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001266Sema::ActOnTemplateParameterList(unsigned Depth,
1267 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001268 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001269 SourceLocation LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001270 ArrayRef<NamedDecl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001271 SourceLocation RAngleLoc,
1272 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001273 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001274 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001275
David Majnemer902f8c62015-12-27 07:16:27 +00001276 return TemplateParameterList::Create(
1277 Context, TemplateLoc, LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001278 llvm::makeArrayRef(Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001279 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001280}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001281
Bruno Ricci4224c872018-12-21 14:35:24 +00001282static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1283 const CXXScopeSpec &SS) {
John McCall3e11ebe2010-03-15 10:12:16 +00001284 if (SS.isSet())
Bruno Ricci4224c872018-12-21 14:35:24 +00001285 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
John McCall3e11ebe2010-03-15 10:12:16 +00001286}
1287
Erich Keanec480f302018-07-12 21:09:05 +00001288DeclResult Sema::CheckClassTemplate(
1289 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1290 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1291 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1292 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1293 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1294 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001295 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001296 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001297 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001298 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001299
1300 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001301 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001302 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001303
Abramo Bagnara6150c882010-05-11 21:36:43 +00001304 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1305 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001306
1307 // There is no such thing as an unnamed class template.
1308 if (!Name) {
1309 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001310 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001311 }
1312
Richard Smith6483d222012-04-21 01:27:54 +00001313 // Find any previous declaration with this name. For a friend with no
1314 // scope explicitly specified, we only look for tag declarations (per
1315 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001316 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001317 LookupResult Previous(*this, Name, NameLoc,
1318 (SS.isEmpty() && TUK == TUK_Friend)
1319 ? LookupTagName : LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001320 forRedeclarationInCurContext());
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001321 if (SS.isNotEmpty() && !SS.isInvalid()) {
1322 SemanticContext = computeDeclContext(SS, true);
1323 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001324 // FIXME: Horrible, horrible hack! We can't currently represent this
1325 // in the AST, and historically we have just ignored such friend
1326 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001327 Diag(NameLoc, TUK == TUK_Friend
1328 ? diag::warn_template_qualified_friend_ignored
1329 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001330 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001331 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001332 }
Mike Stump11289f42009-09-09 15:08:12 +00001333
John McCall0b66eb32010-05-01 00:40:08 +00001334 if (RequireCompleteDeclContext(SS, SemanticContext))
1335 return true;
1336
Simon Pilgrim6905d222016-12-30 22:55:33 +00001337 // If we're adding a template to a dependent context, we may need to
1338 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001339 // now that we know what the current instantiation is.
1340 if (SemanticContext->isDependentContext()) {
1341 ContextRAII SavedContext(*this, SemanticContext);
1342 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1343 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001344 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
Richard Smithc660c8f2018-03-16 13:36:56 +00001345 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
Richard Smith6483d222012-04-21 01:27:54 +00001346
John McCall27b18f82009-11-17 02:14:36 +00001347 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001348 } else {
1349 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001350
1351 // C++14 [class.mem]p14:
1352 // If T is the name of a class, then each of the following shall have a
1353 // name different from T:
1354 // -- every member template of class T
1355 if (TUK != TUK_Friend &&
1356 DiagnoseClassNameShadow(SemanticContext,
1357 DeclarationNameInfo(Name, NameLoc)))
1358 return true;
1359
John McCall27b18f82009-11-17 02:14:36 +00001360 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001361 }
Mike Stump11289f42009-09-09 15:08:12 +00001362
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001363 if (Previous.isAmbiguous())
1364 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001365
Craig Topperc3ec1492014-05-26 06:22:03 +00001366 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001367 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001368 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001369
Serge Pavlove50bf752016-06-10 04:39:07 +00001370 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1371 // Maybe we will complain about the shadowed template parameter.
1372 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1373 // Just pretend that we didn't see the previous declaration.
1374 PrevDecl = nullptr;
1375 }
1376
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001377 // If there is a previous declaration with the same name, check
1378 // whether this is a valid redeclaration.
Richard Smithbecb92d2017-10-10 22:33:17 +00001379 ClassTemplateDecl *PrevClassTemplate =
1380 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001381
1382 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001383 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001384 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001385 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001386 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1387 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001388 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001389 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1390 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1391 PrevClassTemplate
1392 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1393 ->getSpecializedTemplate();
1394 }
1395 }
1396
John McCalld43784f2009-12-18 11:25:59 +00001397 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001398 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399 // [...] When looking for a prior declaration of a class or a function
1400 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001401 // function is neither a qualified name nor a template-id, scopes outside
1402 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001403 if (!SS.isSet()) {
1404 DeclContext *OutermostContext = CurContext;
1405 while (!OutermostContext->isFileContext())
1406 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001407
Richard Smith61e582f2012-04-20 07:12:26 +00001408 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001409 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1410 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1411 SemanticContext = PrevDecl->getDeclContext();
1412 } else {
1413 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001414 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001415 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001416 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001417 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001418
1419 // Check that the chosen semantic context doesn't already contain a
1420 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001421 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001422 DeclContext *LookupContext = SemanticContext;
1423 while (LookupContext->isTransparentContext())
1424 LookupContext = LookupContext->getLookupParent();
1425 LookupQualifiedName(Previous, LookupContext);
1426
1427 if (Previous.isAmbiguous())
1428 return true;
1429
1430 if (Previous.begin() != Previous.end())
1431 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001432 }
John McCall90d3bb92009-12-17 23:21:11 +00001433 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001434 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001435 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1436 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001437 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001438
Richard Smithfc805ca2015-07-06 04:43:58 +00001439 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1440 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1441 if (SS.isEmpty() &&
1442 !(PrevClassTemplate &&
1443 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1444 SemanticContext->getRedeclContext()))) {
1445 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1446 Diag(Shadow->getTargetDecl()->getLocation(),
1447 diag::note_using_decl_target);
1448 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1449 // Recover by ignoring the old declaration.
1450 PrevDecl = PrevClassTemplate = nullptr;
1451 }
1452 }
1453
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001454 // TODO Memory management; associated constraints are not always stored.
1455 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1456
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001457 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001458 // Ensure that the template parameter lists are compatible. Skip this check
1459 // for a friend in a dependent context: the template parameter list itself
1460 // could be dependent.
1461 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1462 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001463 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001464 /*Complain=*/true,
1465 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001466 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001467
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001468 // Check for matching associated constraints on redeclarations.
1469 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1470 const bool RedeclACMismatch = [&] {
1471 if (!(CurAC || PrevAC))
1472 return false; // Nothing to check; no mismatch.
1473 if (CurAC && PrevAC) {
1474 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1475 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1476 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1477 if (CurACInfo == PrevACInfo)
1478 return false; // All good; no mismatch.
1479 }
1480 return true;
1481 }();
1482
1483 if (RedeclACMismatch) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001484 Diag(CurAC ? CurAC->getBeginLoc() : NameLoc,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001485 diag::err_template_different_associated_constraints);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001486 Diag(PrevAC ? PrevAC->getBeginLoc() : PrevClassTemplate->getLocation(),
1487 diag::note_template_prev_declaration)
1488 << /*declaration*/ 0;
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001489 return true;
1490 }
1491
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001492 // C++ [temp.class]p4:
1493 // In a redeclaration, partial specialization, explicit
1494 // specialization or explicit instantiation of a class template,
1495 // the class-key shall agree in kind with the original class
1496 // template declaration (7.1.5.3).
1497 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001498 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001499 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001500 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001501 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001502 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001503 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001504 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001505 }
1506
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001507 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001508 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001509 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001510 // If we have a prior definition that is not visible, treat this as
1511 // simply making that previous definition visible.
1512 NamedDecl *Hidden = nullptr;
1513 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001514 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00001515 SkipBody->Previous = Def;
Richard Smithbe3980b2015-03-27 00:41:57 +00001516 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1517 assert(Tmpl && "original definition of a class template is not a "
1518 "class template?");
Richard Smith858e0e02017-05-11 23:11:16 +00001519 makeMergedDefinitionVisible(Hidden);
1520 makeMergedDefinitionVisible(Tmpl);
Richard Smithc4577662018-09-12 02:13:47 +00001521 } else {
1522 Diag(NameLoc, diag::err_redefinition) << Name;
1523 Diag(Def->getLocation(), diag::note_previous_definition);
1524 // FIXME: Would it make sense to try to "forget" the previous
1525 // definition, as part of error recovery?
1526 return true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001527 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001528 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001529 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001530 } else if (PrevDecl) {
1531 // C++ [temp]p5:
1532 // A class template shall not have the same name as any other
1533 // template, class, function, object, enumeration, enumerator,
1534 // namespace, or type in the same scope (3.3), except as specified
1535 // in (14.5.4).
1536 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1537 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001538 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001539 }
1540
Douglas Gregordba32632009-02-10 19:49:53 +00001541 // Check the template parameter list of this declaration, possibly
1542 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001543 // template declaration. Skip this check for a friend in a dependent
1544 // context, because the template parameter list might be dependent.
1545 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001546 CheckTemplateParameterList(
1547 TemplateParams,
Richard Smithc4577662018-09-12 02:13:47 +00001548 PrevClassTemplate
1549 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1550 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001551 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1552 SemanticContext->isDependentContext())
1553 ? TPC_ClassTemplateMember
Richard Smithc4577662018-09-12 02:13:47 +00001554 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1555 SkipBody))
Douglas Gregordba32632009-02-10 19:49:53 +00001556 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001557
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001558 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001559 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001560 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001561 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1562 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001563 : diag::err_member_decl_does_not_match)
1564 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001565 Invalid = true;
1566 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001567 }
1568
Vassil Vassilev352e4412017-01-12 09:16:26 +00001569 // If this is a templated friend in a dependent context we should not put it
1570 // on the redecl chain. In some cases, the templated friend can be the most
1571 // recent declaration tricking the template instantiator to make substitutions
1572 // there.
1573 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1574 bool ShouldAddRedecl
1575 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1576
Mike Stump11289f42009-09-09 15:08:12 +00001577 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001578 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001579 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001580 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001581 /*DelayTypeCreation=*/true);
Bruno Ricci4224c872018-12-21 14:35:24 +00001582 SetNestedNameSpecifier(*this, NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001583 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001584 NewClass->setTemplateParameterListsInfo(
1585 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1586 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001587
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001588 // Add alignment attributes if necessary; these attributes are checked when
1589 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00001590 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Eli Friedman0415f3e12012-08-08 21:08:34 +00001591 AddAlignmentAttributesForRecord(NewClass);
1592 AddMsStructLayoutForRecord(NewClass);
1593 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001594
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001595 // Attach the associated constraints when the declaration will not be part of
1596 // a decl chain.
1597 Expr *const ACtoAttach =
1598 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1599
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001600 ClassTemplateDecl *NewTemplate
1601 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1602 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001603 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001604
1605 if (ShouldAddRedecl)
1606 NewTemplate->setPreviousDecl(PrevClassTemplate);
1607
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001608 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001609
Douglas Gregor21823bf2011-12-20 18:11:52 +00001610 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001611 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001612
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001613 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001614 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001615 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001616 assert(T->isDependentType() && "Class template type is not dependent?");
1617 (void)T;
1618
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001619 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001620 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001621 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001622 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1623 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001624
Anders Carlsson137108d2009-03-26 01:24:28 +00001625 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001626 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001627 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001628
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001629 // Set the lexical context of these templates
1630 NewClass->setLexicalDeclContext(CurContext);
1631 NewTemplate->setLexicalDeclContext(CurContext);
1632
Richard Smithc4577662018-09-12 02:13:47 +00001633 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001634 NewClass->startDefinition();
1635
Erich Keanec480f302018-07-12 21:09:05 +00001636 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001637
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001638 if (PrevClassTemplate)
1639 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1640
Rafael Espindola385c0422012-07-13 18:04:45 +00001641 AddPushedVisibilityAttribute(NewClass);
1642
Richard Smith234ff472014-08-23 00:49:01 +00001643 if (TUK != TUK_Friend) {
1644 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1645 Scope *Outer = S;
1646 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1647 Outer = Outer->getParent();
1648 PushOnScopeChains(NewTemplate, Outer);
1649 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001650 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001651 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001652 NewClass->setAccess(PrevClassTemplate->getAccess());
1653 }
John McCall27b5c252009-09-14 21:59:20 +00001654
Richard Smith64017682013-07-17 23:53:16 +00001655 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001656
John McCall27b5c252009-09-14 21:59:20 +00001657 // Friend templates are visible in fairly strange ways.
1658 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001659 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001660 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001661 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1662 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001663 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001665
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001666 FriendDecl *Friend = FriendDecl::Create(
1667 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001668 Friend->setAccess(AS_public);
1669 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001670 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001671
Richard Smithbecb92d2017-10-10 22:33:17 +00001672 if (PrevClassTemplate)
1673 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1674
Douglas Gregordba32632009-02-10 19:49:53 +00001675 if (Invalid) {
1676 NewTemplate->setInvalidDecl();
1677 NewClass->setInvalidDecl();
1678 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001679
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001680 ActOnDocumentableDecl(NewTemplate);
1681
Richard Smithc4577662018-09-12 02:13:47 +00001682 if (SkipBody && SkipBody->ShouldSkip)
1683 return SkipBody->Previous;
1684
John McCall48871652010-08-21 09:40:31 +00001685 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001686}
1687
Richard Smith32918772017-02-14 00:25:28 +00001688namespace {
Erik Pilkington69770d32018-07-27 21:23:48 +00001689/// Tree transform to "extract" a transformed type from a class template's
1690/// constructor to a deduction guide.
1691class ExtractTypeForDeductionGuide
1692 : public TreeTransform<ExtractTypeForDeductionGuide> {
1693public:
1694 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
1695 ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1696
1697 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1698
1699 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1700 return TransformType(
1701 TLB,
1702 TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1703 }
1704};
1705
Richard Smith32918772017-02-14 00:25:28 +00001706/// Transform to convert portions of a constructor declaration into the
1707/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1708struct ConvertConstructorToDeductionGuideTransform {
1709 ConvertConstructorToDeductionGuideTransform(Sema &S,
1710 ClassTemplateDecl *Template)
1711 : SemaRef(S), Template(Template) {}
1712
1713 Sema &SemaRef;
1714 ClassTemplateDecl *Template;
1715
1716 DeclContext *DC = Template->getDeclContext();
1717 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1718 DeclarationName DeductionGuideName =
1719 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1720
1721 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1722
1723 // Index adjustment to apply to convert depth-1 template parameters into
1724 // depth-0 template parameters.
1725 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1726
1727 /// Transform a constructor declaration into a deduction guide.
Richard Smithbc491202017-02-17 20:05:37 +00001728 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1729 CXXConstructorDecl *CD) {
Richard Smith32918772017-02-14 00:25:28 +00001730 SmallVector<TemplateArgument, 16> SubstArgs;
1731
Richard Smithb4f96252017-02-21 06:30:38 +00001732 LocalInstantiationScope Scope(SemaRef);
1733
Richard Smith32918772017-02-14 00:25:28 +00001734 // C++ [over.match.class.deduct]p1:
1735 // -- For each constructor of the class template designated by the
1736 // template-name, a function template with the following properties:
1737
1738 // -- The template parameters are the template parameters of the class
1739 // template followed by the template parameters (including default
1740 // template arguments) of the constructor, if any.
1741 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1742 if (FTD) {
1743 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1744 SmallVector<NamedDecl *, 16> AllParams;
1745 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1746 AllParams.insert(AllParams.begin(),
1747 TemplateParams->begin(), TemplateParams->end());
1748 SubstArgs.reserve(InnerParams->size());
1749
1750 // Later template parameters could refer to earlier ones, so build up
1751 // a list of substituted template arguments as we go.
1752 for (NamedDecl *Param : *InnerParams) {
1753 MultiLevelTemplateArgumentList Args;
1754 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001755 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001756 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1757 if (!NewParam)
1758 return nullptr;
1759 AllParams.push_back(NewParam);
1760 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1761 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1762 }
1763 TemplateParams = TemplateParameterList::Create(
1764 SemaRef.Context, InnerParams->getTemplateLoc(),
1765 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1766 /*FIXME: RequiresClause*/ nullptr);
1767 }
1768
1769 // If we built a new template-parameter-list, track that we need to
1770 // substitute references to the old parameters into references to the
1771 // new ones.
1772 MultiLevelTemplateArgumentList Args;
1773 if (FTD) {
1774 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001775 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001776 }
1777
Richard Smithbc491202017-02-17 20:05:37 +00001778 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
Richard Smith32918772017-02-14 00:25:28 +00001779 .getAsAdjusted<FunctionProtoTypeLoc>();
1780 assert(FPTL && "no prototype for constructor declaration");
1781
1782 // Transform the type of the function, adjusting the return type and
1783 // replacing references to the old parameters with references to the
1784 // new ones.
1785 TypeLocBuilder TLB;
1786 SmallVector<ParmVarDecl*, 8> Params;
1787 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1788 if (NewType.isNull())
1789 return nullptr;
1790 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1791
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00001792 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1793 CD->getBeginLoc(), CD->getLocation(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001794 CD->getEndLoc());
Richard Smith32918772017-02-14 00:25:28 +00001795 }
1796
1797 /// Build a deduction guide with the specified parameter types.
1798 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1799 SourceLocation Loc = Template->getLocation();
1800
1801 // Build the requested type.
1802 FunctionProtoType::ExtProtoInfo EPI;
1803 EPI.HasTrailingReturn = true;
1804 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1805 DeductionGuideName, EPI);
1806 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1807
1808 FunctionProtoTypeLoc FPTL =
1809 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1810
1811 // Build the parameters, needed during deduction / substitution.
1812 SmallVector<ParmVarDecl*, 4> Params;
1813 for (auto T : ParamTypes) {
1814 ParmVarDecl *NewParam = ParmVarDecl::Create(
1815 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1816 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1817 NewParam->setScopeInfo(0, Params.size());
1818 FPTL.setParam(Params.size(), NewParam);
1819 Params.push_back(NewParam);
1820 }
1821
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00001822 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1823 Loc, Loc, Loc);
Richard Smith32918772017-02-14 00:25:28 +00001824 }
1825
1826private:
1827 /// Transform a constructor template parameter into a deduction guide template
1828 /// parameter, rebuilding any internal references to earlier parameters and
1829 /// renumbering as we go.
1830 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1831 MultiLevelTemplateArgumentList &Args) {
1832 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1833 // TemplateTypeParmDecl's index cannot be changed after creation, so
1834 // substitute it directly.
1835 auto *NewTTP = TemplateTypeParmDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001836 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
1837 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
Richard Smith32918772017-02-14 00:25:28 +00001838 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1839 TTP->isParameterPack());
1840 if (TTP->hasDefaultArgument()) {
1841 TypeSourceInfo *InstantiatedDefaultArg =
1842 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1843 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1844 if (InstantiatedDefaultArg)
1845 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1846 }
Richard Smithb4f96252017-02-21 06:30:38 +00001847 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1848 NewTTP);
Richard Smith32918772017-02-14 00:25:28 +00001849 return NewTTP;
1850 }
1851
1852 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1853 return transformTemplateParameterImpl(TTP, Args);
1854
1855 return transformTemplateParameterImpl(
1856 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1857 }
1858 template<typename TemplateParmDecl>
1859 TemplateParmDecl *
1860 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1861 MultiLevelTemplateArgumentList &Args) {
1862 // Ask the template instantiator to do the heavy lifting for us, then adjust
1863 // the index of the parameter once it's done.
1864 auto *NewParam =
1865 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1866 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1867 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1868 return NewParam;
1869 }
1870
1871 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1872 FunctionProtoTypeLoc TL,
1873 SmallVectorImpl<ParmVarDecl*> &Params,
1874 MultiLevelTemplateArgumentList &Args) {
1875 SmallVector<QualType, 4> ParamTypes;
1876 const FunctionProtoType *T = TL.getTypePtr();
1877
1878 // -- The types of the function parameters are those of the constructor.
1879 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001880 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001881 if (!NewParam)
1882 return QualType();
1883 ParamTypes.push_back(NewParam->getType());
1884 Params.push_back(NewParam);
1885 }
1886
1887 // -- The return type is the class template specialization designated by
1888 // the template-name and template arguments corresponding to the
1889 // template parameters obtained from the class template.
1890 //
1891 // We use the injected-class-name type of the primary template instead.
1892 // This has the convenient property that it is different from any type that
1893 // the user can write in a deduction-guide (because they cannot enter the
1894 // context of the template), so implicit deduction guides can never collide
1895 // with explicit ones.
1896 QualType ReturnType = DeducedType;
1897 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1898
1899 // Resolving a wording defect, we also inherit the variadicness of the
1900 // constructor.
1901 FunctionProtoType::ExtProtoInfo EPI;
1902 EPI.Variadic = T->isVariadic();
1903 EPI.HasTrailingReturn = true;
1904
1905 QualType Result = SemaRef.BuildFunctionType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001906 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
Richard Smith32918772017-02-14 00:25:28 +00001907 if (Result.isNull())
1908 return QualType();
1909
1910 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1911 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1912 NewTL.setLParenLoc(TL.getLParenLoc());
1913 NewTL.setRParenLoc(TL.getRParenLoc());
1914 NewTL.setExceptionSpecRange(SourceRange());
1915 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1916 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1917 NewTL.setParam(I, Params[I]);
1918
1919 return Result;
1920 }
1921
1922 ParmVarDecl *
1923 transformFunctionTypeParam(ParmVarDecl *OldParam,
1924 MultiLevelTemplateArgumentList &Args) {
1925 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smith479ba8e2017-04-20 01:15:31 +00001926 TypeSourceInfo *NewDI;
Erik Pilkington69770d32018-07-27 21:23:48 +00001927 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
Richard Smith479ba8e2017-04-20 01:15:31 +00001928 // Expand out the one and only element in each inner pack.
1929 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1930 NewDI =
1931 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1932 OldParam->getLocation(), OldParam->getDeclName());
1933 if (!NewDI) return nullptr;
1934 NewDI =
1935 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1936 PackTL.getTypePtr()->getNumExpansions());
1937 } else
1938 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1939 OldParam->getDeclName());
Richard Smith32918772017-02-14 00:25:28 +00001940 if (!NewDI)
1941 return nullptr;
1942
Erik Pilkington69770d32018-07-27 21:23:48 +00001943 // Extract the type. This (for instance) replaces references to typedef
1944 // members of the current instantiations with the definitions of those
1945 // typedefs, avoiding triggering instantiation of the deduced type during
1946 // deduction.
1947 NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
Richard Smithc27b3d72017-02-14 01:49:59 +00001948
Richard Smith32918772017-02-14 00:25:28 +00001949 // Resolving a wording defect, we also inherit default arguments from the
1950 // constructor.
1951 ExprResult NewDefArg;
1952 if (OldParam->hasDefaultArg()) {
Erik Pilkington69770d32018-07-27 21:23:48 +00001953 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
Richard Smith32918772017-02-14 00:25:28 +00001954 if (NewDefArg.isInvalid())
1955 return nullptr;
1956 }
1957
1958 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1959 OldParam->getInnerLocStart(),
1960 OldParam->getLocation(),
1961 OldParam->getIdentifier(),
1962 NewDI->getType(),
1963 NewDI,
1964 OldParam->getStorageClass(),
1965 NewDefArg.get());
1966 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1967 OldParam->getFunctionScopeIndex());
Erik Pilkington69770d32018-07-27 21:23:48 +00001968 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
Richard Smith32918772017-02-14 00:25:28 +00001969 return NewParam;
1970 }
1971
1972 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00001973 bool Explicit, TypeSourceInfo *TInfo,
Richard Smith32918772017-02-14 00:25:28 +00001974 SourceLocation LocStart, SourceLocation Loc,
1975 SourceLocation LocEnd) {
Richard Smithbc491202017-02-17 20:05:37 +00001976 DeclarationNameInfo Name(DeductionGuideName, Loc);
Richard Smithefa919a2017-02-16 21:29:21 +00001977 ArrayRef<ParmVarDecl *> Params =
1978 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1979
Richard Smith32918772017-02-14 00:25:28 +00001980 // Build the implicit deduction guide template.
Richard Smithbc491202017-02-17 20:05:37 +00001981 auto *Guide =
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00001982 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1983 Name, TInfo->getType(), TInfo, LocEnd);
Richard Smith32918772017-02-14 00:25:28 +00001984 Guide->setImplicit();
Richard Smithefa919a2017-02-16 21:29:21 +00001985 Guide->setParams(Params);
1986
1987 for (auto *Param : Params)
1988 Param->setDeclContext(Guide);
Richard Smith32918772017-02-14 00:25:28 +00001989
1990 auto *GuideTemplate = FunctionTemplateDecl::Create(
1991 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1992 GuideTemplate->setImplicit();
1993 Guide->setDescribedFunctionTemplate(GuideTemplate);
1994
1995 if (isa<CXXRecordDecl>(DC)) {
1996 Guide->setAccess(AS_public);
1997 GuideTemplate->setAccess(AS_public);
1998 }
1999
2000 DC->addDecl(GuideTemplate);
2001 return GuideTemplate;
2002 }
2003};
2004}
2005
2006void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2007 SourceLocation Loc) {
2008 DeclContext *DC = Template->getDeclContext();
2009 if (DC->isDependentContext())
2010 return;
2011
2012 ConvertConstructorToDeductionGuideTransform Transform(
2013 *this, cast<ClassTemplateDecl>(Template));
2014 if (!isCompleteType(Loc, Transform.DeducedType))
2015 return;
2016
2017 // Check whether we've already declared deduction guides for this template.
2018 // FIXME: Consider storing a flag on the template to indicate this.
2019 auto Existing = DC->lookup(Transform.DeductionGuideName);
2020 for (auto *D : Existing)
2021 if (D->isImplicit())
2022 return;
2023
2024 // In case we were expanding a pack when we attempted to declare deduction
2025 // guides, turn off pack expansion for everything we're about to do.
2026 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2027 // Create a template instantiation record to track the "instantiation" of
2028 // constructors into deduction guides.
2029 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2030 // this substitution process actually fail?
2031 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
Volodymyr Sapsai2f649f32018-05-14 22:49:44 +00002032 if (BuildingDeductionGuides.isInvalid())
2033 return;
Richard Smith32918772017-02-14 00:25:28 +00002034
2035 // Convert declared constructors into deduction guide templates.
2036 // FIXME: Skip constructors for which deduction must necessarily fail (those
2037 // for which some class template parameter without a default argument never
2038 // appears in a deduced context).
2039 bool AddedAny = false;
Richard Smith32918772017-02-14 00:25:28 +00002040 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2041 D = D->getUnderlyingDecl();
2042 if (D->isInvalidDecl() || D->isImplicit())
2043 continue;
2044 D = cast<NamedDecl>(D->getCanonicalDecl());
2045
2046 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00002047 auto *CD =
2048 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00002049 // Class-scope explicit specializations (MS extension) do not result in
2050 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00002051 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00002052 continue;
2053
Richard Smithbc491202017-02-17 20:05:37 +00002054 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00002055 AddedAny = true;
Richard Smith32918772017-02-14 00:25:28 +00002056 }
2057
Faisal Vali81b756e2017-10-22 14:45:08 +00002058 // C++17 [over.match.class.deduct]
2059 // -- If C is not defined or does not declare any constructors, an
2060 // additional function template derived as above from a hypothetical
2061 // constructor C().
Richard Smith32918772017-02-14 00:25:28 +00002062 if (!AddedAny)
2063 Transform.buildSimpleDeductionGuide(None);
2064
Faisal Vali81b756e2017-10-22 14:45:08 +00002065 // -- An additional function template derived as above from a hypothetical
2066 // constructor C(C), called the copy deduction candidate.
2067 cast<CXXDeductionGuideDecl>(
2068 cast<FunctionTemplateDecl>(
2069 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2070 ->getTemplatedDecl())
2071 ->setIsCopyDeductionCandidate();
Richard Smith32918772017-02-14 00:25:28 +00002072}
2073
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002074/// Diagnose the presence of a default template argument on a
Douglas Gregored5731f2009-11-25 17:50:39 +00002075/// template parameter, which is ill-formed in certain contexts.
2076///
2077/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002078static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00002079 Sema::TemplateParamListContext TPC,
2080 SourceLocation ParamLoc,
2081 SourceRange DefArgRange) {
2082 switch (TPC) {
2083 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002084 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00002085 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002086 return false;
2087
2088 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002089 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002090 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00002091 // A default template-argument shall not be specified in a
2092 // function template declaration or a function template
2093 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00002094 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002095 // template-argument, that declaration shall be a definition and shall be
2096 // the only declaration of the function template in the translation unit.
2097 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002098 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002099 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2100 : diag::ext_template_parameter_default_in_function_template)
2101 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00002102 return false;
2103
2104 case Sema::TPC_ClassTemplateMember:
2105 // C++0x [temp.param]p9:
2106 // A default template-argument shall not be specified in the
2107 // template-parameter-lists of the definition of a member of a
2108 // class template that appears outside of the member's class.
2109 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2110 << DefArgRange;
2111 return true;
2112
David Majnemerba8f17a2013-06-25 22:08:55 +00002113 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002114 case Sema::TPC_FriendFunctionTemplate:
2115 // C++ [temp.param]p9:
2116 // A default template-argument shall not be specified in a
2117 // friend template declaration.
2118 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2119 << DefArgRange;
2120 return true;
2121
2122 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2123 // for friend function templates if there is only a single
2124 // declaration (and it is a definition). Strange!
2125 }
2126
David Blaikie8a40f702012-01-17 06:56:22 +00002127 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00002128}
2129
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002130/// Check for unexpanded parameter packs within the template parameters
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002131/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00002132static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2133 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002134 // A template template parameter which is a parameter pack is also a pack
2135 // expansion.
2136 if (TTP->isParameterPack())
2137 return false;
2138
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002139 TemplateParameterList *Params = TTP->getTemplateParameters();
2140 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2141 NamedDecl *P = Params->getParam(I);
2142 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002143 if (!NTTP->isParameterPack() &&
2144 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002145 NTTP->getTypeSourceInfo(),
2146 Sema::UPPC_NonTypeTemplateParameterType))
2147 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002148
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002149 continue;
2150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151
2152 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002153 = dyn_cast<TemplateTemplateParmDecl>(P))
2154 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2155 return true;
2156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002157
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002158 return false;
2159}
2160
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002161/// Checks the validity of a template parameter list, possibly
Douglas Gregordba32632009-02-10 19:49:53 +00002162/// considering the template parameter list from a previous
2163/// declaration.
2164///
2165/// If an "old" template parameter list is provided, it must be
2166/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2167/// template parameter list.
2168///
2169/// \param NewParams Template parameter list for a new template
2170/// declaration. This template parameter list will be updated with any
2171/// default arguments that are carried through from the previous
2172/// template parameter list.
2173///
2174/// \param OldParams If provided, template parameter list from a
2175/// previous declaration of the same template. Default template
2176/// arguments will be merged from the old template parameter list to
2177/// the new template parameter list.
2178///
Douglas Gregored5731f2009-11-25 17:50:39 +00002179/// \param TPC Describes the context in which we are checking the given
2180/// template parameter list.
2181///
Richard Smithc4577662018-09-12 02:13:47 +00002182/// \param SkipBody If we might have already made a prior merged definition
2183/// of this template visible, the corresponding body-skipping information.
2184/// Default argument redefinition is not an error when skipping such a body,
2185/// because (under the ODR) we can assume the default arguments are the same
2186/// as the prior merged definition.
2187///
Douglas Gregordba32632009-02-10 19:49:53 +00002188/// \returns true if an error occurred, false otherwise.
2189bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00002190 TemplateParameterList *OldParams,
Richard Smithc4577662018-09-12 02:13:47 +00002191 TemplateParamListContext TPC,
2192 SkipBodyInfo *SkipBody) {
Douglas Gregordba32632009-02-10 19:49:53 +00002193 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00002194
Douglas Gregordba32632009-02-10 19:49:53 +00002195 // C++ [temp.param]p10:
2196 // The set of default template-arguments available for use with a
2197 // template declaration or definition is obtained by merging the
2198 // default arguments from the definition (if in scope) and all
2199 // declarations in scope in the same way default function
2200 // arguments are (8.3.6).
2201 bool SawDefaultArgument = false;
2202 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00002203
Mike Stumpc89c8e32009-02-11 23:03:27 +00002204 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00002205 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00002206 if (OldParams)
2207 OldParam = OldParams->begin();
2208
Douglas Gregor0693def2011-01-27 01:40:17 +00002209 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00002210 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2211 NewParamEnd = NewParams->end();
2212 NewParam != NewParamEnd; ++NewParam) {
2213 // Variables used to diagnose redundant default arguments
2214 bool RedundantDefaultArg = false;
2215 SourceLocation OldDefaultLoc;
2216 SourceLocation NewDefaultLoc;
2217
David Blaikie651c73c2011-10-19 05:19:50 +00002218 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00002219 bool MissingDefaultArg = false;
2220
David Blaikie651c73c2011-10-19 05:19:50 +00002221 // Variable used to diagnose non-final parameter packs
2222 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00002223
Douglas Gregordba32632009-02-10 19:49:53 +00002224 if (TemplateTypeParmDecl *NewTypeParm
2225 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00002226 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002227 if (NewTypeParm->hasDefaultArgument() &&
2228 DiagnoseDefaultTemplateArgument(*this, TPC,
2229 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002230 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002231 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00002232 NewTypeParm->removeDefaultArgument();
2233
2234 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002235 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002236 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00002237 if (NewTypeParm->isParameterPack()) {
2238 assert(!NewTypeParm->hasDefaultArgument() &&
2239 "Parameter packs can't have a default argument!");
2240 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002241 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002242 NewTypeParm->hasDefaultArgument() &&
2243 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002244 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2245 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2246 SawDefaultArgument = true;
2247 RedundantDefaultArg = true;
2248 PreviousDefaultArgLoc = NewDefaultLoc;
2249 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2250 // Merge the default argument from the old declaration to the
2251 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002252 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002253 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2254 } else if (NewTypeParm->hasDefaultArgument()) {
2255 SawDefaultArgument = true;
2256 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2257 } else if (SawDefaultArgument)
2258 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002259 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00002260 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002261 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002262 if (!NewNonTypeParm->isParameterPack() &&
2263 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002264 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002265 UPPC_NonTypeTemplateParameterType)) {
2266 Invalid = true;
2267 continue;
2268 }
2269
Douglas Gregored5731f2009-11-25 17:50:39 +00002270 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002271 if (NewNonTypeParm->hasDefaultArgument() &&
2272 DiagnoseDefaultTemplateArgument(*this, TPC,
2273 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002274 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00002275 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002276 }
2277
Mike Stump12b8ce12009-08-04 21:02:39 +00002278 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002279 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002280 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002281 if (NewNonTypeParm->isParameterPack()) {
2282 assert(!NewNonTypeParm->hasDefaultArgument() &&
2283 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002284 if (!NewNonTypeParm->isPackExpansion())
2285 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002286 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002287 NewNonTypeParm->hasDefaultArgument() &&
2288 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002289 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2290 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2291 SawDefaultArgument = true;
2292 RedundantDefaultArg = true;
2293 PreviousDefaultArgLoc = NewDefaultLoc;
2294 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2295 // Merge the default argument from the old declaration to the
2296 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002297 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002298 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2299 } else if (NewNonTypeParm->hasDefaultArgument()) {
2300 SawDefaultArgument = true;
2301 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2302 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002303 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002304 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00002305 TemplateTemplateParmDecl *NewTemplateParm
2306 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002307
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002308 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002309 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002310 Invalid = true;
2311 continue;
2312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002313
David Blaikie651c73c2011-10-19 05:19:50 +00002314 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002315 if (NewTemplateParm->hasDefaultArgument() &&
2316 DiagnoseDefaultTemplateArgument(*this, TPC,
2317 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002318 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002319 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002320
2321 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002322 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002323 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002324 if (NewTemplateParm->isParameterPack()) {
2325 assert(!NewTemplateParm->hasDefaultArgument() &&
2326 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002327 if (!NewTemplateParm->isPackExpansion())
2328 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002329 } else if (OldTemplateParm &&
2330 hasVisibleDefaultArgument(OldTemplateParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002331 NewTemplateParm->hasDefaultArgument() &&
2332 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002333 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2334 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002335 SawDefaultArgument = true;
2336 RedundantDefaultArg = true;
2337 PreviousDefaultArgLoc = NewDefaultLoc;
2338 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2339 // Merge the default argument from the old declaration to the
2340 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002341 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002342 PreviousDefaultArgLoc
2343 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002344 } else if (NewTemplateParm->hasDefaultArgument()) {
2345 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002346 PreviousDefaultArgLoc
2347 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002348 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002349 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002350 }
2351
Richard Smith1fde8ec2012-09-07 02:06:42 +00002352 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002353 // If a template parameter of a primary class template or alias template
2354 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002355 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002356 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2357 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002358 Diag((*NewParam)->getLocation(),
2359 diag::err_template_param_pack_must_be_last_template_parameter);
2360 Invalid = true;
2361 }
2362
Douglas Gregordba32632009-02-10 19:49:53 +00002363 if (RedundantDefaultArg) {
2364 // C++ [temp.param]p12:
2365 // A template-parameter shall not be given default arguments
2366 // by two different declarations in the same scope.
2367 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2368 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2369 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002370 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002371 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002372 // If a template-parameter of a class template has a default
2373 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002374 // have a default template-argument supplied or be a template parameter
2375 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002376 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002377 diag::err_template_param_default_arg_missing);
2378 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2379 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002380 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002381 }
2382
2383 // If we have an old template parameter list that we're merging
2384 // in, move on to the next parameter.
2385 if (OldParams)
2386 ++OldParam;
2387 }
2388
Douglas Gregor0693def2011-01-27 01:40:17 +00002389 // We were missing some default arguments at the end of the list, so remove
2390 // all of the default arguments.
2391 if (RemoveDefaultArguments) {
2392 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2393 NewParamEnd = NewParams->end();
2394 NewParam != NewParamEnd; ++NewParam) {
2395 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2396 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002397 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002398 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2399 NTTP->removeDefaultArgument();
2400 else
2401 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2402 }
2403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002404
Douglas Gregordba32632009-02-10 19:49:53 +00002405 return Invalid;
2406}
Douglas Gregord32e0282009-02-09 23:23:08 +00002407
John McCalla020a012010-10-20 05:44:58 +00002408namespace {
2409
2410/// A class which looks for a use of a certain level of template
2411/// parameter.
2412struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2413 typedef RecursiveASTVisitor<DependencyChecker> super;
2414
2415 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00002416
2417 // Whether we're looking for a use of a template parameter that makes the
2418 // overall construct type-dependent / a dependent type. This is strictly
2419 // best-effort for now; we may fail to match at all for a dependent type
2420 // in some cases if this is set.
2421 bool IgnoreNonTypeDependent;
2422
John McCalla020a012010-10-20 05:44:58 +00002423 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002424 SourceLocation MatchLoc;
2425
Richard Smith13894182017-04-13 21:37:24 +00002426 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2427 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2428 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002429
Richard Smith57aae072016-12-28 02:37:25 +00002430 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith13894182017-04-13 21:37:24 +00002431 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2432 NamedDecl *ND = Params->getParam(0);
2433 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2434 Depth = PD->getDepth();
2435 } else if (NonTypeTemplateParmDecl *PD =
2436 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2437 Depth = PD->getDepth();
2438 } else {
2439 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2440 }
2441 }
John McCalla020a012010-10-20 05:44:58 +00002442
Richard Smith6056d5e2014-02-09 00:54:43 +00002443 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith13894182017-04-13 21:37:24 +00002444 if (ParmDepth >= Depth) {
John McCalla020a012010-10-20 05:44:58 +00002445 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002446 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002447 return true;
2448 }
2449 return false;
2450 }
2451
Richard Smith57aae072016-12-28 02:37:25 +00002452 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2453 // Prune out non-type-dependent expressions if requested. This can
2454 // sometimes result in us failing to find a template parameter reference
2455 // (if a value-dependent expression creates a dependent type), but this
2456 // mode is best-effort only.
2457 if (auto *E = dyn_cast_or_null<Expr>(S))
2458 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2459 return true;
2460 return super::TraverseStmt(S, Q);
2461 }
2462
2463 bool TraverseTypeLoc(TypeLoc TL) {
2464 if (IgnoreNonTypeDependent && !TL.isNull() &&
2465 !TL.getType()->isDependentType())
2466 return true;
2467 return super::TraverseTypeLoc(TL);
2468 }
2469
Richard Smith6056d5e2014-02-09 00:54:43 +00002470 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2471 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2472 }
2473
John McCalla020a012010-10-20 05:44:58 +00002474 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002475 // For a best-effort search, keep looking until we find a location.
2476 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002477 }
2478
2479 bool TraverseTemplateName(TemplateName N) {
2480 if (TemplateTemplateParmDecl *PD =
2481 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002482 if (Matches(PD->getDepth()))
2483 return false;
John McCalla020a012010-10-20 05:44:58 +00002484 return super::TraverseTemplateName(N);
2485 }
2486
2487 bool VisitDeclRefExpr(DeclRefExpr *E) {
2488 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002489 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2490 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002491 return false;
John McCalla020a012010-10-20 05:44:58 +00002492 return super::VisitDeclRefExpr(E);
2493 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002494
2495 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2496 return TraverseType(T->getReplacementType());
2497 }
2498
2499 bool
2500 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2501 return TraverseTemplateArgument(T->getArgumentPack());
2502 }
2503
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002504 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2505 return TraverseType(T->getInjectedSpecializationType());
2506 }
John McCalla020a012010-10-20 05:44:58 +00002507};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002508} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002509
Douglas Gregor972fe532011-05-10 18:27:06 +00002510/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002511/// list.
2512static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002513DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002514 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002515 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002516 return Checker.Match;
2517}
2518
Douglas Gregor972fe532011-05-10 18:27:06 +00002519// Find the source range corresponding to the named type in the given
2520// nested-name-specifier, if any.
2521static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2522 QualType T,
2523 const CXXScopeSpec &SS) {
2524 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2525 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2526 if (const Type *CurType = NNS->getAsType()) {
2527 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2528 return NNSLoc.getTypeLoc().getSourceRange();
2529 } else
2530 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002531
Douglas Gregor972fe532011-05-10 18:27:06 +00002532 NNSLoc = NNSLoc.getPrefix();
2533 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002534
Douglas Gregor972fe532011-05-10 18:27:06 +00002535 return SourceRange();
2536}
2537
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002538/// Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002539/// specifier, returning the template parameter list that applies to the
2540/// name.
2541///
2542/// \param DeclStartLoc the start of the declaration that has a scope
2543/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002544///
Douglas Gregor972fe532011-05-10 18:27:06 +00002545/// \param DeclLoc The location of the declaration itself.
2546///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002547/// \param SS the scope specifier that will be matched to the given template
2548/// parameter lists. This scope specifier precedes a qualified name that is
2549/// being declared.
2550///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002551/// \param TemplateId The template-id following the scope specifier, if there
2552/// is one. Used to check for a missing 'template<>'.
2553///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002554/// \param ParamLists the template parameter lists, from the outermost to the
2555/// innermost template parameter lists.
2556///
John McCalle820e5e2010-04-13 20:37:33 +00002557/// \param IsFriend Whether to apply the slightly different rules for
2558/// matching template parameters to scope specifiers in friend
2559/// declarations.
2560///
Richard Smithf445f192017-02-09 21:04:43 +00002561/// \param IsMemberSpecialization will be set true if the scope specifier
2562/// denotes a fully-specialized type, and therefore this is a declaration of
2563/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002564///
Mike Stump11289f42009-09-09 15:08:12 +00002565/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002566/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002567/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002568/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002569/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002570/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002571TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2572 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002573 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002574 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002575 bool &IsMemberSpecialization, bool &Invalid) {
2576 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002577 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002578
Douglas Gregor972fe532011-05-10 18:27:06 +00002579 // The sequence of nested types to which we will match up the template
2580 // parameter lists. We first build this list by starting with the type named
2581 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002582 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002583 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002584 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002585 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002586 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2587 T = Context.getTypeDeclType(Record);
2588 else
2589 T = QualType(SS.getScopeRep()->getAsType(), 0);
2590 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002591
Douglas Gregor972fe532011-05-10 18:27:06 +00002592 // If we found an explicit specialization that prevents us from needing
2593 // 'template<>' headers, this will be set to the location of that
2594 // explicit specialization.
2595 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002596
Douglas Gregor972fe532011-05-10 18:27:06 +00002597 while (!T.isNull()) {
2598 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002599
Douglas Gregor972fe532011-05-10 18:27:06 +00002600 // Retrieve the parent of a record type.
2601 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2602 // If this type is an explicit specialization, we're done.
2603 if (ClassTemplateSpecializationDecl *Spec
2604 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002605 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002606 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2607 ExplicitSpecLoc = Spec->getLocation();
2608 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002609 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002610 } else if (Record->getTemplateSpecializationKind()
2611 == TSK_ExplicitSpecialization) {
2612 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002613 break;
2614 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002615
Douglas Gregor972fe532011-05-10 18:27:06 +00002616 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2617 T = Context.getTypeDeclType(Parent);
2618 else
2619 T = QualType();
2620 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002621 }
2622
Douglas Gregor972fe532011-05-10 18:27:06 +00002623 if (const TemplateSpecializationType *TST
2624 = T->getAs<TemplateSpecializationType>()) {
2625 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2626 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2627 T = Context.getTypeDeclType(Parent);
2628 else
2629 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002630 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002631 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002632 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002633
Douglas Gregor972fe532011-05-10 18:27:06 +00002634 // Look one step prior in a dependent template specialization type.
2635 if (const DependentTemplateSpecializationType *DependentTST
2636 = T->getAs<DependentTemplateSpecializationType>()) {
2637 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2638 T = QualType(NNS->getAsType(), 0);
2639 else
2640 T = QualType();
2641 continue;
2642 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002643
Douglas Gregor972fe532011-05-10 18:27:06 +00002644 // Look one step prior in a dependent name type.
2645 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2646 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2647 T = QualType(NNS->getAsType(), 0);
2648 else
2649 T = QualType();
2650 continue;
2651 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002652
Douglas Gregor972fe532011-05-10 18:27:06 +00002653 // Retrieve the parent of an enumeration type.
2654 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2655 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2656 // check here.
2657 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002658
Douglas Gregor972fe532011-05-10 18:27:06 +00002659 // Get to the parent type.
2660 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2661 T = Context.getTypeDeclType(Parent);
2662 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002663 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002664 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002665 }
Mike Stump11289f42009-09-09 15:08:12 +00002666
Douglas Gregor972fe532011-05-10 18:27:06 +00002667 T = QualType();
2668 }
2669 // Reverse the nested types list, since we want to traverse from the outermost
2670 // to the innermost while checking template-parameter-lists.
2671 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002672
Douglas Gregor972fe532011-05-10 18:27:06 +00002673 // C++0x [temp.expl.spec]p17:
2674 // A member or a member template may be nested within many
2675 // enclosing class templates. In an explicit specialization for
2676 // such a member, the member declaration shall be preceded by a
2677 // template<> for each enclosing class template that is
2678 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002679 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002680
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002681 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002682 if (SawNonEmptyTemplateParameterList) {
2683 Diag(DeclLoc, diag::err_specialize_member_of_template)
2684 << !Recovery << Range;
2685 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002686 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002687 return true;
2688 }
2689
2690 return false;
2691 };
2692
2693 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2694 // Check that we can have an explicit specialization here.
2695 if (CheckExplicitSpecialization(Range, true))
2696 return true;
2697
2698 // We don't have a template header, but we should.
2699 SourceLocation ExpectedTemplateLoc;
2700 if (!ParamLists.empty())
2701 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2702 else
2703 ExpectedTemplateLoc = DeclStartLoc;
2704
2705 Diag(DeclLoc, diag::err_template_spec_needs_header)
2706 << Range
2707 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2708 return false;
2709 };
2710
Douglas Gregor972fe532011-05-10 18:27:06 +00002711 unsigned ParamIdx = 0;
2712 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2713 ++TypeIdx) {
2714 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002715
Douglas Gregor972fe532011-05-10 18:27:06 +00002716 // Whether we expect a 'template<>' header.
2717 bool NeedEmptyTemplateHeader = false;
2718
2719 // Whether we expect a template header with parameters.
2720 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002721
Douglas Gregor972fe532011-05-10 18:27:06 +00002722 // For a dependent type, the set of template parameters that we
2723 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002724 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002725
Douglas Gregor373af9b2011-05-11 23:26:17 +00002726 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002727 // A member or a member template may be nested within many enclosing
2728 // class templates. In an explicit specialization for such a member, the
2729 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002730 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002731 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2732 if (ClassTemplatePartialSpecializationDecl *Partial
2733 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2734 ExpectedTemplateParams = Partial->getTemplateParameters();
2735 NeedNonemptyTemplateHeader = true;
2736 } else if (Record->isDependentType()) {
2737 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002738 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002739 ->getTemplateParameters();
2740 NeedNonemptyTemplateHeader = true;
2741 }
2742 } else if (ClassTemplateSpecializationDecl *Spec
2743 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2744 // C++0x [temp.expl.spec]p4:
2745 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002746 // in the same manner as members of normal classes, and not using
2747 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002748 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2749 NeedEmptyTemplateHeader = true;
2750 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002751 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002752 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002753 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002754 != TSK_ExplicitSpecialization &&
2755 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002756 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002757
Douglas Gregor373af9b2011-05-11 23:26:17 +00002758 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002759 }
2760 } else if (const TemplateSpecializationType *TST
2761 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002762 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002763 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002764 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002765 }
2766 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2767 // FIXME: We actually could/should check the template arguments here
2768 // against the corresponding template parameter list.
2769 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002770 }
2771
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002772 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002773 // In an explicit specialization declaration for a member of a class
2774 // template or a member template that ap- pears in namespace scope, the
2775 // member template and some of its enclosing class templates may remain
2776 // unspecialized, except that the declaration shall not explicitly
2777 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002778 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002779 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002780 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002781 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2782 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002783 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002784 } else
2785 SawNonEmptyTemplateParameterList = true;
2786 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002787
Douglas Gregor972fe532011-05-10 18:27:06 +00002788 if (NeedEmptyTemplateHeader) {
2789 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002790 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002791 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002792 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002793
2794 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002795 if (ParamLists[ParamIdx]->size() > 0) {
2796 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002797 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002798 diag::err_template_param_list_matches_nontemplate)
2799 << T
2800 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2801 ParamLists[ParamIdx]->getRAngleLoc())
2802 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2803 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002804 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002805 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002806
Douglas Gregor972fe532011-05-10 18:27:06 +00002807 // Consume this template header.
2808 ++ParamIdx;
2809 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002810 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002811
2812 if (!IsFriend)
2813 if (DiagnoseMissingExplicitSpecialization(
2814 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002815 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002816
Douglas Gregor972fe532011-05-10 18:27:06 +00002817 continue;
2818 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002819
Douglas Gregor972fe532011-05-10 18:27:06 +00002820 if (NeedNonemptyTemplateHeader) {
2821 // In friend declarations we can have template-ids which don't
2822 // depend on the corresponding template parameter lists. But
2823 // assume that empty parameter lists are supposed to match this
2824 // template-id.
2825 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002826 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002827 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002828 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002829 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002830 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002831 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002832
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002833 if (ParamIdx < ParamLists.size()) {
2834 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002835 if (ExpectedTemplateParams &&
2836 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2837 ExpectedTemplateParams,
2838 true, TPL_TemplateMatch))
2839 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002840
Douglas Gregor972fe532011-05-10 18:27:06 +00002841 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002842 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002843 TPC_ClassTemplateMember))
2844 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002845
Douglas Gregor972fe532011-05-10 18:27:06 +00002846 ++ParamIdx;
2847 continue;
2848 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002849
Douglas Gregor972fe532011-05-10 18:27:06 +00002850 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2851 << T
2852 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2853 Invalid = true;
2854 continue;
2855 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002856 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002857
Douglas Gregord8d297c2009-07-21 23:53:31 +00002858 // If there were at least as many template-ids as there were template
2859 // parameter lists, then there are no template parameter lists remaining for
2860 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002861 if (ParamIdx >= ParamLists.size()) {
2862 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002863 // We don't have a template header for the declaration itself, but we
2864 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002865 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2866 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002867
2868 // Fabricate an empty template parameter list for the invented header.
2869 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002870 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002871 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002872 }
2873
Craig Topperc3ec1492014-05-26 06:22:03 +00002874 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002875 }
Mike Stump11289f42009-09-09 15:08:12 +00002876
Douglas Gregord8d297c2009-07-21 23:53:31 +00002877 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002878 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002879 bool HasAnyExplicitSpecHeader = false;
2880 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002881 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002882 if (ParamLists[I]->size() == 0)
2883 HasAnyExplicitSpecHeader = true;
2884 else
2885 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002886 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002887
Douglas Gregor972fe532011-05-10 18:27:06 +00002888 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002889 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2890 : diag::err_template_spec_extra_headers)
2891 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2892 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002893
2894 // If there was a specialization somewhere, such that 'template<>' is
2895 // not required, and there were any 'template<>' headers, note where the
2896 // specialization occurred.
2897 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002898 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002899 diag::note_explicit_template_spec_does_not_need_header)
2900 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002901
Douglas Gregor972fe532011-05-10 18:27:06 +00002902 // We have a template parameter list with no corresponding scope, which
2903 // means that the resulting template declaration can't be instantiated
2904 // properly (we'll end up with dependent nodes when we shouldn't).
2905 if (!AllExplicitSpecHeaders)
2906 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002907 }
Mike Stump11289f42009-09-09 15:08:12 +00002908
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002909 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002910 // In an explicit specialization declaration for a member of a class
2911 // template or a member template that ap- pears in namespace scope, the
2912 // member template and some of its enclosing class templates may remain
2913 // unspecialized, except that the declaration shall not explicitly
2914 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002915 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002916 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002917 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2918 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002919 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002920
Douglas Gregord8d297c2009-07-21 23:53:31 +00002921 // Return the last template parameter list, which corresponds to the
2922 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002923 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002924}
2925
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002926void Sema::NoteAllFoundTemplates(TemplateName Name) {
2927 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2928 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002929 << (isa<FunctionTemplateDecl>(Template)
2930 ? 0
2931 : isa<ClassTemplateDecl>(Template)
2932 ? 1
2933 : isa<VarTemplateDecl>(Template)
2934 ? 2
2935 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2936 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002937 return;
2938 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002939
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002940 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002941 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002942 IEnd = OST->end();
2943 I != IEnd; ++I)
2944 Diag((*I)->getLocation(), diag::note_template_declared_here)
2945 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002946
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002947 return;
2948 }
2949}
2950
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002951static QualType
2952checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2953 const SmallVectorImpl<TemplateArgument> &Converted,
2954 SourceLocation TemplateLoc,
2955 TemplateArgumentListInfo &TemplateArgs) {
2956 ASTContext &Context = SemaRef.getASTContext();
2957 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002958 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002959 // Specializations of __make_integer_seq<S, T, N> are treated like
2960 // S<T, 0, ..., N-1>.
2961
2962 // C++14 [inteseq.intseq]p1:
2963 // T shall be an integer type.
2964 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2965 SemaRef.Diag(TemplateArgs[1].getLocation(),
2966 diag::err_integer_sequence_integral_element_type);
2967 return QualType();
2968 }
2969
2970 // C++14 [inteseq.make]p1:
2971 // If N is negative the program is ill-formed.
2972 TemplateArgument NumArgsArg = Converted[2];
2973 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2974 if (NumArgs < 0) {
2975 SemaRef.Diag(TemplateArgs[2].getLocation(),
2976 diag::err_integer_sequence_negative_length);
2977 return QualType();
2978 }
2979
2980 QualType ArgTy = NumArgsArg.getIntegralType();
2981 TemplateArgumentListInfo SyntheticTemplateArgs;
2982 // The type argument gets reused as the first template argument in the
2983 // synthetic template argument list.
2984 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2985 // Expand N into 0 ... N-1.
2986 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2987 I < NumArgs; ++I) {
2988 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002989 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2990 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002991 }
2992 // The first template argument will be reused as the template decl that
2993 // our synthetic template arguments will be applied to.
2994 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2995 TemplateLoc, SyntheticTemplateArgs);
2996 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002997
2998 case BTK__type_pack_element:
2999 // Specializations of
3000 // __type_pack_element<Index, T_1, ..., T_N>
3001 // are treated like T_Index.
3002 assert(Converted.size() == 2 &&
3003 "__type_pack_element should be given an index and a parameter pack");
3004
3005 // If the Index is out of bounds, the program is ill-formed.
3006 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3007 llvm::APSInt Index = IndexArg.getAsIntegral();
3008 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3009 "type std::size_t, and hence be non-negative");
3010 if (Index >= Ts.pack_size()) {
3011 SemaRef.Diag(TemplateArgs[0].getLocation(),
3012 diag::err_type_pack_element_out_of_bounds);
3013 return QualType();
3014 }
3015
3016 // We simply return the type at index `Index`.
3017 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3018 return Nth->getAsType();
3019 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003020 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3021}
3022
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003023/// Determine whether this alias template is "enable_if_t".
3024static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3025 return AliasTemplate->getName().equals("enable_if_t");
3026}
3027
3028/// Collect all of the separable terms in the given condition, which
3029/// might be a conjunction.
3030///
3031/// FIXME: The right answer is to convert the logical expression into
3032/// disjunctive normal form, so we can find the first failed term
3033/// within each possible clause.
3034static void collectConjunctionTerms(Expr *Clause,
3035 SmallVectorImpl<Expr *> &Terms) {
3036 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3037 if (BinOp->getOpcode() == BO_LAnd) {
3038 collectConjunctionTerms(BinOp->getLHS(), Terms);
3039 collectConjunctionTerms(BinOp->getRHS(), Terms);
3040 }
3041
3042 return;
3043 }
3044
3045 Terms.push_back(Clause);
3046}
3047
Douglas Gregorbb33f572017-07-05 20:20:15 +00003048// The ranges-v3 library uses an odd pattern of a top-level "||" with
3049// a left-hand side that is value-dependent but never true. Identify
3050// the idiom and ignore that term.
3051static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3052 // Top-level '||'.
3053 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3054 if (!BinOp) return Cond;
3055
3056 if (BinOp->getOpcode() != BO_LOr) return Cond;
3057
3058 // With an inner '==' that has a literal on the right-hand side.
3059 Expr *LHS = BinOp->getLHS();
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003060 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
Douglas Gregorbb33f572017-07-05 20:20:15 +00003061 if (!InnerBinOp) return Cond;
3062
3063 if (InnerBinOp->getOpcode() != BO_EQ ||
3064 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3065 return Cond;
3066
3067 // If the inner binary operation came from a macro expansion named
3068 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3069 // of the '||', which is the real, user-provided condition.
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003070 SourceLocation Loc = InnerBinOp->getExprLoc();
Douglas Gregorbb33f572017-07-05 20:20:15 +00003071 if (!Loc.isMacroID()) return Cond;
3072
3073 StringRef MacroName = PP.getImmediateMacroName(Loc);
3074 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3075 return BinOp->getRHS();
3076
3077 return Cond;
3078}
3079
Clement Courbetf44c6f42018-12-11 08:39:11 +00003080namespace {
3081
3082// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3083// within failing boolean expression, such as substituting template parameters
3084// for actual types.
3085class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3086public:
3087 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3088 : Policy(P) {}
3089
3090 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3091 const auto *DR = dyn_cast<DeclRefExpr>(E);
3092 if (DR && DR->getQualifier()) {
3093 // If this is a qualified name, expand the template arguments in nested
3094 // qualifiers.
3095 DR->getQualifier()->print(OS, Policy, true);
3096 // Then print the decl itself.
3097 const ValueDecl *VD = DR->getDecl();
3098 OS << VD->getName();
3099 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3100 // This is a template variable, print the expanded template arguments.
3101 printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3102 }
3103 return true;
Clement Courbet9d432e02018-12-04 07:59:57 +00003104 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003105 return false;
Clement Courbet9d432e02018-12-04 07:59:57 +00003106 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003107
3108private:
3109 const PrintingPolicy Policy;
3110};
3111
3112} // end anonymous namespace
Clement Courbet9d432e02018-12-04 07:59:57 +00003113
Douglas Gregor672281a2017-09-14 23:38:42 +00003114std::pair<Expr *, std::string>
Clement Courbetf44c6f42018-12-11 08:39:11 +00003115Sema::findFailedBooleanCondition(Expr *Cond) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003116 Cond = lookThroughRangesV3Condition(PP, Cond);
Douglas Gregorbb33f572017-07-05 20:20:15 +00003117
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003118 // Separate out all of the terms in a conjunction.
3119 SmallVector<Expr *, 4> Terms;
3120 collectConjunctionTerms(Cond, Terms);
3121
3122 // Determine which term failed.
3123 Expr *FailedCond = nullptr;
3124 for (Expr *Term : Terms) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003125 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3126
Clement Courbetd8720412018-12-10 08:53:17 +00003127 // Literals are uninteresting.
3128 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3129 isa<IntegerLiteral>(TermAsWritten))
3130 continue;
3131
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003132 // The initialization of the parameter from the argument is
3133 // a constant-evaluated context.
3134 EnterExpressionEvaluationContext ConstantEvaluated(
Douglas Gregor672281a2017-09-14 23:38:42 +00003135 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003136
3137 bool Succeeded;
Douglas Gregor672281a2017-09-14 23:38:42 +00003138 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003139 !Succeeded) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003140 FailedCond = TermAsWritten;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003141 break;
3142 }
3143 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003144 if (!FailedCond)
Clement Courbetd8720412018-12-10 08:53:17 +00003145 FailedCond = Cond->IgnoreParenImpCasts();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003146
3147 std::string Description;
3148 {
3149 llvm::raw_string_ostream Out(Description);
Clement Courbetfb2c74d2018-12-20 09:05:15 +00003150 PrintingPolicy Policy = getPrintingPolicy();
3151 Policy.PrintCanonicalTypes = true;
3152 FailedBooleanConditionPrinterHelper Helper(Policy);
3153 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003154 }
3155 return { FailedCond, Description };
3156}
3157
Douglas Gregordc572a32009-03-30 22:58:21 +00003158QualType Sema::CheckTemplateIdType(TemplateName Name,
3159 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003160 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00003161 DependentTemplateName *DTN
3162 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00003163 if (DTN && DTN->isIdentifier())
3164 // When building a template-id where the template-name is dependent,
3165 // assume the template is a type template. Either our assumption is
3166 // correct, or the code is ill-formed and will be diagnosed when the
3167 // dependent name is substituted.
3168 return Context.getDependentTemplateSpecializationType(ETK_None,
3169 DTN->getQualifier(),
3170 DTN->getIdentifier(),
3171 TemplateArgs);
3172
Douglas Gregordc572a32009-03-30 22:58:21 +00003173 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00003174 if (!Template || isa<FunctionTemplateDecl>(Template) ||
Faisal Valia534f072018-04-26 00:42:40 +00003175 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003176 // We might have a substituted template template parameter pack. If so,
3177 // build a template specialization type for it.
3178 if (Name.getAsSubstTemplateTemplateParmPack())
3179 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003180
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003181 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3182 << Name;
3183 NoteAllFoundTemplates(Name);
3184 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00003185 }
Douglas Gregordc572a32009-03-30 22:58:21 +00003186
Douglas Gregorc40290e2009-03-09 23:48:35 +00003187 // Check that the template argument list is well-formed for this
3188 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003189 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00003190 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003191 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00003192 return QualType();
3193
Douglas Gregorc40290e2009-03-09 23:48:35 +00003194 QualType CanonType;
3195
Douglas Gregor678d76c2011-07-01 01:22:09 +00003196 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00003197 if (TypeAliasTemplateDecl *AliasTemplate =
3198 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00003199 // Find the canonical type for this type alias template specialization.
3200 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3201 if (Pattern->isInvalidDecl())
3202 return QualType();
3203
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003204 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3205 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003206
3207 // Only substitute for the innermost template argument list.
3208 MultiLevelTemplateArgumentList TemplateArgLists;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003209 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00003210 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3211 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00003212 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003213
Richard Smith802c4b72012-08-23 06:16:52 +00003214 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003215 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003216 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003217 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00003218
Richard Smith3f1b5d02011-05-05 21:57:07 +00003219 CanonType = SubstType(Pattern->getUnderlyingType(),
3220 TemplateArgLists, AliasTemplate->getLocation(),
3221 AliasTemplate->getDeclName());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003222 if (CanonType.isNull()) {
3223 // If this was enable_if and we failed to find the nested type
3224 // within enable_if in a SFINAE context, dig out the specific
3225 // enable_if condition that failed and present that instead.
3226 if (isEnableIfAliasTemplate(AliasTemplate)) {
3227 if (auto DeductionInfo = isSFINAEContext()) {
3228 if (*DeductionInfo &&
3229 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3230 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3231 diag::err_typename_nested_not_found_enable_if &&
3232 TemplateArgs[0].getArgument().getKind()
3233 == TemplateArgument::Expression) {
3234 Expr *FailedCond;
3235 std::string FailedDescription;
3236 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00003237 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003238
3239 // Remove the old SFINAE diagnostic.
3240 PartialDiagnosticAt OldDiag =
3241 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3242 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3243
3244 // Add a new SFINAE diagnostic specifying which condition
3245 // failed.
3246 (*DeductionInfo)->addSFINAEDiagnostic(
3247 OldDiag.first,
3248 PDiag(diag::err_typename_nested_not_found_requirement)
3249 << FailedDescription
3250 << FailedCond->getSourceRange());
3251 }
3252 }
3253 }
3254
Richard Smith3f1b5d02011-05-05 21:57:07 +00003255 return QualType();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003256 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003257 } else if (Name.isDependent() ||
3258 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00003259 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003260 // This class template specialization is a dependent
3261 // type. Therefore, its canonical type is another class template
3262 // specialization type that contains all of the converted
3263 // arguments in canonical form. This ensures that, e.g., A<T> and
3264 // A<T, T> have identical types when A is declared as:
3265 //
3266 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003267 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00003268
3269 // This might work out to be a current instantiation, in which
3270 // case the canonical type needs to be the InjectedClassNameType.
3271 //
3272 // TODO: in theory this could be a simple hashtable lookup; most
3273 // changes to CurContext don't change the set of current
3274 // instantiations.
3275 if (isa<ClassTemplateDecl>(Template)) {
3276 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3277 // If we get out to a namespace, we're done.
3278 if (Ctx->isFileContext()) break;
3279
3280 // If this isn't a record, keep looking.
3281 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3282 if (!Record) continue;
3283
3284 // Look for one of the two cases with InjectedClassNameTypes
3285 // and check whether it's the same template.
3286 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3287 !Record->getDescribedClassTemplate())
3288 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003289
John McCall2408e322010-04-27 00:57:59 +00003290 // Fetch the injected class name type and check whether its
3291 // injected type is equal to the type we just built.
3292 QualType ICNT = Context.getTypeDeclType(Record);
3293 QualType Injected = cast<InjectedClassNameType>(ICNT)
3294 ->getInjectedSpecializationType();
3295
3296 if (CanonType != Injected->getCanonicalTypeInternal())
3297 continue;
3298
3299 // If so, the canonical type of this TST is the injected
3300 // class name type of the record we just found.
3301 assert(ICNT.isCanonical());
3302 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00003303 break;
3304 }
3305 }
Mike Stump11289f42009-09-09 15:08:12 +00003306 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00003307 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003308 // Find the class template specialization declaration that
3309 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003310 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003311 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00003312 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003313 if (!Decl) {
3314 // This is the first time we have referenced this class template
3315 // specialization. Create the canonical declaration and add it to
3316 // the set of specializations.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003317 Decl = ClassTemplateSpecializationDecl::Create(
3318 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3319 ClassTemplate->getDeclContext(),
3320 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3321 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003322 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00003323 if (ClassTemplate->isOutOfLine())
3324 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00003325 }
3326
Erich Keanea32910d2017-03-23 18:51:54 +00003327 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3328 MultiLevelTemplateArgumentList TemplateArgLists;
3329 TemplateArgLists.addOuterTemplateArguments(Converted);
3330 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3331 Decl);
3332 }
3333
Chandler Carruth2acfb222013-09-27 22:14:40 +00003334 // Diagnose uses of this specialization.
3335 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3336
Douglas Gregorc40290e2009-03-09 23:48:35 +00003337 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00003338 assert(isa<RecordType>(CanonType) &&
3339 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003340 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3341 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3342 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003343 }
Mike Stump11289f42009-09-09 15:08:12 +00003344
Douglas Gregorc40290e2009-03-09 23:48:35 +00003345 // Build the fully-sugared type for this class template
3346 // specialization, which refers back to the class template
3347 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00003348 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003349}
3350
John McCallfaf5fb42010-08-26 23:41:50 +00003351TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003352Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00003353 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3354 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00003355 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00003356 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00003357 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00003358 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003359 if (SS.isInvalid())
3360 return true;
3361
Richard Smith62559bd2017-02-01 21:36:38 +00003362 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3363 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3364
3365 // C++ [temp.res]p3:
3366 // A qualified-id that refers to a type and in which the
3367 // nested-name-specifier depends on a template-parameter (14.6.2)
3368 // shall be prefixed by the keyword typename to indicate that the
3369 // qualified-id denotes a type, forming an
3370 // elaborated-type-specifier (7.1.5.3).
3371 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00003372 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00003373 << SS.getScopeRep() << TemplateII->getName();
3374 // Recover as if 'typename' were specified.
3375 // FIXME: This is not quite correct recovery as we don't transform SS
3376 // into the corresponding dependent form (and we don't diagnose missing
3377 // 'template' keywords within SS as a result).
3378 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3379 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3380 TemplateArgsIn, RAngleLoc);
3381 }
3382
3383 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3384 // it's not actually allowed to be used as a type in most cases. Because
3385 // we annotate it before we know whether it's valid, we have to check for
3386 // this case here.
3387 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00003388 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3389 Diag(TemplateIILoc,
3390 TemplateKWLoc.isInvalid()
3391 ? diag::err_out_of_line_qualified_id_type_names_constructor
3392 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3393 << TemplateII << 0 /*injected-class-name used as template name*/
3394 << 1 /*if any keyword was present, it was 'template'*/;
3395 }
3396 }
3397
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003398 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00003399
Douglas Gregorc40290e2009-03-09 23:48:35 +00003400 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003401 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003402 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00003403
Douglas Gregor5a064722011-02-28 17:23:35 +00003404 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00003405 QualType T
3406 = Context.getDependentTemplateSpecializationType(ETK_None,
3407 DTN->getQualifier(),
3408 DTN->getIdentifier(),
3409 TemplateArgs);
3410 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00003411 TypeLocBuilder TLB;
3412 DependentTemplateSpecializationTypeLoc SpecTL
3413 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003414 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3415 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003416 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003417 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003418 SpecTL.setLAngleLoc(LAngleLoc);
3419 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003420 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3421 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3422 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3423 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003424
Richard Smith74f02342017-01-19 21:00:13 +00003425 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003426 if (Result.isNull())
3427 return true;
3428
Douglas Gregore7c20652011-03-02 00:47:37 +00003429 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003430 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00003431 TemplateSpecializationTypeLoc SpecTL
3432 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003433 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003434 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003435 SpecTL.setLAngleLoc(LAngleLoc);
3436 SpecTL.setRAngleLoc(RAngleLoc);
3437 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3438 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00003439
Abramo Bagnara4244b432012-01-27 08:46:19 +00003440 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3441 // constructor or destructor name (in such a case, the scope specifier
3442 // will be attached to the enclosing Decl or Expr node).
3443 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003444 // Create an elaborated-type-specifier containing the nested-name-specifier.
3445 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3446 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003447 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00003448 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3449 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003450
Douglas Gregore7c20652011-03-02 00:47:37 +00003451 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00003452}
John McCall06f6fe8d2009-09-04 01:14:41 +00003453
Douglas Gregore7c20652011-03-02 00:47:37 +00003454TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00003455 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00003456 SourceLocation TagLoc,
3457 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003458 SourceLocation TemplateKWLoc,
3459 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00003460 SourceLocation TemplateLoc,
3461 SourceLocation LAngleLoc,
3462 ASTTemplateArgsPtr TemplateArgsIn,
3463 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003464 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003465
Douglas Gregore7c20652011-03-02 00:47:37 +00003466 // Translate the parser's template argument list in our AST format.
3467 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3468 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003469
Douglas Gregore7c20652011-03-02 00:47:37 +00003470 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00003471 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00003472 ElaboratedTypeKeyword Keyword
3473 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00003474
Douglas Gregore7c20652011-03-02 00:47:37 +00003475 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3476 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00003477 DTN->getQualifier(),
3478 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00003479 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003480
3481 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00003482 TypeLocBuilder TLB;
3483 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003484 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3485 SpecTL.setElaboratedKeywordLoc(TagLoc);
3486 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003487 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003488 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003489 SpecTL.setLAngleLoc(LAngleLoc);
3490 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003491 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3492 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3493 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3494 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003495
3496 if (TypeAliasTemplateDecl *TAT =
3497 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3498 // C++0x [dcl.type.elab]p2:
3499 // If the identifier resolves to a typedef-name or the simple-template-id
3500 // resolves to an alias template specialization, the
3501 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003502 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3503 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003504 Diag(TAT->getLocation(), diag::note_declared_at);
3505 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003506
Douglas Gregore7c20652011-03-02 00:47:37 +00003507 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3508 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003509 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003510
Douglas Gregore7c20652011-03-02 00:47:37 +00003511 // Check the tag kind
3512 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003513 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003514
John McCalld8fe9af2009-09-08 17:47:29 +00003515 IdentifierInfo *Id = D->getIdentifier();
3516 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003517
Richard Trieucaa33d32011-06-10 03:11:26 +00003518 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003519 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003520 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003521 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003522 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003523 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003524 }
3525 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003526
Douglas Gregore7c20652011-03-02 00:47:37 +00003527 // Provide source-location information for the template specialization.
3528 TypeLocBuilder TLB;
3529 TemplateSpecializationTypeLoc SpecTL
3530 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003531 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003532 SpecTL.setTemplateNameLoc(TemplateLoc);
3533 SpecTL.setLAngleLoc(LAngleLoc);
3534 SpecTL.setRAngleLoc(RAngleLoc);
3535 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3536 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003537
Douglas Gregore7c20652011-03-02 00:47:37 +00003538 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003539 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003540 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3541 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003542 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003543 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3544 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003545}
3546
Larisse Voufo39a1e502013-08-06 01:03:05 +00003547static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3548 NamedDecl *PrevDecl,
3549 SourceLocation Loc,
3550 bool IsPartialSpecialization);
3551
3552static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003553
Richard Smith300e0c32013-09-24 04:49:23 +00003554static bool isTemplateArgumentTemplateParameter(
3555 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3556 switch (Arg.getKind()) {
3557 case TemplateArgument::Null:
3558 case TemplateArgument::NullPtr:
3559 case TemplateArgument::Integral:
3560 case TemplateArgument::Declaration:
3561 case TemplateArgument::Pack:
3562 case TemplateArgument::TemplateExpansion:
3563 return false;
3564
3565 case TemplateArgument::Type: {
3566 QualType Type = Arg.getAsType();
3567 const TemplateTypeParmType *TPT =
3568 Arg.getAsType()->getAs<TemplateTypeParmType>();
3569 return TPT && !Type.hasQualifiers() &&
3570 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3571 }
3572
3573 case TemplateArgument::Expression: {
3574 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3575 if (!DRE || !DRE->getDecl())
3576 return false;
3577 const NonTypeTemplateParmDecl *NTTP =
3578 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3579 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3580 }
3581
3582 case TemplateArgument::Template:
3583 const TemplateTemplateParmDecl *TTP =
3584 dyn_cast_or_null<TemplateTemplateParmDecl>(
3585 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3586 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3587 }
3588 llvm_unreachable("unexpected kind of template argument");
3589}
3590
3591static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3592 ArrayRef<TemplateArgument> Args) {
3593 if (Params->size() != Args.size())
3594 return false;
3595
3596 unsigned Depth = Params->getDepth();
3597
3598 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3599 TemplateArgument Arg = Args[I];
3600
3601 // If the parameter is a pack expansion, the argument must be a pack
3602 // whose only element is a pack expansion.
3603 if (Params->getParam(I)->isParameterPack()) {
3604 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3605 !Arg.pack_begin()->isPackExpansion())
3606 return false;
3607 Arg = Arg.pack_begin()->getPackExpansionPattern();
3608 }
3609
3610 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3611 return false;
3612 }
3613
3614 return true;
3615}
3616
Richard Smith4b55a9c2014-04-17 03:29:33 +00003617/// Convert the parser's template argument list representation into our form.
3618static TemplateArgumentListInfo
3619makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3620 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3621 TemplateId.RAngleLoc);
3622 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3623 TemplateId.NumArgs);
3624 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3625 return TemplateArgs;
3626}
3627
Richard Smith0e617ec2016-12-27 07:56:27 +00003628template<typename PartialSpecDecl>
3629static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3630 if (Partial->getDeclContext()->isDependentContext())
3631 return;
3632
3633 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3634 // for non-substitution-failure issues?
3635 TemplateDeductionInfo Info(Partial->getLocation());
3636 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3637 return;
3638
3639 auto *Template = Partial->getSpecializedTemplate();
3640 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003641 diag::ext_partial_spec_not_more_specialized_than_primary)
3642 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003643
3644 if (Info.hasSFINAEDiagnostic()) {
3645 PartialDiagnosticAt Diag = {SourceLocation(),
3646 PartialDiagnostic::NullDiagnostic()};
3647 Info.takeSFINAEDiagnostic(Diag);
3648 SmallString<128> SFINAEArgString;
3649 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3650 S.Diag(Diag.first,
3651 diag::note_partial_spec_not_more_specialized_than_primary)
3652 << SFINAEArgString;
3653 }
3654
3655 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3656}
3657
Richard Smith4e05eaa2017-02-16 00:36:47 +00003658static void
3659noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3660 const llvm::SmallBitVector &DeducibleParams) {
3661 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3662 if (!DeducibleParams[I]) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00003663 NamedDecl *Param = TemplateParams->getParam(I);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003664 if (Param->getDeclName())
3665 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3666 << Param->getDeclName();
3667 else
3668 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3669 << "(anonymous)";
3670 }
3671 }
3672}
3673
3674
Richard Smith57aae072016-12-28 02:37:25 +00003675template<typename PartialSpecDecl>
3676static void checkTemplatePartialSpecialization(Sema &S,
3677 PartialSpecDecl *Partial) {
3678 // C++1z [temp.class.spec]p8: (DR1495)
3679 // - The specialization shall be more specialized than the primary
3680 // template (14.5.5.2).
3681 checkMoreSpecializedThanPrimary(S, Partial);
3682
3683 // C++ [temp.class.spec]p8: (DR1315)
3684 // - Each template-parameter shall appear at least once in the
3685 // template-id outside a non-deduced context.
3686 // C++1z [temp.class.spec.match]p3 (P0127R2)
3687 // If the template arguments of a partial specialization cannot be
3688 // deduced because of the structure of its template-parameter-list
3689 // and the template-id, the program is ill-formed.
3690 auto *TemplateParams = Partial->getTemplateParameters();
3691 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3692 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3693 TemplateParams->getDepth(), DeducibleParams);
3694
3695 if (!DeducibleParams.all()) {
3696 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3697 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3698 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3699 << (NumNonDeducible > 1)
3700 << SourceRange(Partial->getLocation(),
3701 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003702 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003703 }
3704}
3705
3706void Sema::CheckTemplatePartialSpecialization(
3707 ClassTemplatePartialSpecializationDecl *Partial) {
3708 checkTemplatePartialSpecialization(*this, Partial);
3709}
3710
3711void Sema::CheckTemplatePartialSpecialization(
3712 VarTemplatePartialSpecializationDecl *Partial) {
3713 checkTemplatePartialSpecialization(*this, Partial);
3714}
3715
Richard Smith4e05eaa2017-02-16 00:36:47 +00003716void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3717 // C++1z [temp.param]p11:
3718 // A template parameter of a deduction guide template that does not have a
3719 // default-argument shall be deducible from the parameter-type-list of the
3720 // deduction guide template.
3721 auto *TemplateParams = TD->getTemplateParameters();
3722 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3723 MarkDeducedTemplateParameters(TD, DeducibleParams);
3724 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3725 // A parameter pack is deducible (to an empty pack).
3726 auto *Param = TemplateParams->getParam(I);
3727 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3728 DeducibleParams[I] = true;
3729 }
3730
3731 if (!DeducibleParams.all()) {
3732 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3733 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3734 << (NumNonDeducible > 1);
3735 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3736 }
3737}
3738
Larisse Voufo39a1e502013-08-06 01:03:05 +00003739DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003740 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003741 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003742 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003743 // D must be variable template id.
Faisal Vali2ab8c152017-12-30 04:15:27 +00003744 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003745 "Variable template specialization is declared with a template it.");
3746
3747 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003748 TemplateArgumentListInfo TemplateArgs =
3749 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003750 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3751 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3752 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003753
Richard Smithbeef3452014-01-16 23:39:20 +00003754 TemplateName Name = TemplateId->Template.get();
3755
3756 // The template-id must name a variable template.
3757 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003758 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3759 if (!VarTemplate) {
3760 NamedDecl *FnTemplate;
3761 if (auto *OTS = Name.getAsOverloadedTemplate())
3762 FnTemplate = *OTS->begin();
3763 else
3764 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3765 if (FnTemplate)
3766 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3767 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003768 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3769 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003770 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003771
3772 // Check for unexpanded parameter packs in any of the template arguments.
3773 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3774 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3775 UPPC_PartialSpecialization))
3776 return true;
3777
3778 // Check that the template argument list is well-formed for this
3779 // template.
3780 SmallVector<TemplateArgument, 4> Converted;
3781 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3782 false, Converted))
3783 return true;
3784
Larisse Voufo39a1e502013-08-06 01:03:05 +00003785 // Find the variable template (partial) specialization declaration that
3786 // corresponds to these arguments.
3787 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003788 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3789 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003790 return true;
3791
Richard Smith57aae072016-12-28 02:37:25 +00003792 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3793 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003794 bool InstantiationDependent;
3795 if (!Name.isDependent() &&
3796 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003797 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003798 InstantiationDependent)) {
3799 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3800 << VarTemplate->getDeclName();
3801 IsPartialSpecialization = false;
3802 }
Richard Smith300e0c32013-09-24 04:49:23 +00003803
3804 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3805 Converted)) {
3806 // C++ [temp.class.spec]p9b3:
3807 //
3808 // -- The argument list of the specialization shall not be identical
3809 // to the implicit argument list of the primary template.
3810 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3811 << /*variable template*/ 1
3812 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3813 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3814 // FIXME: Recover from this by treating the declaration as a redeclaration
3815 // of the primary template.
3816 return true;
3817 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003818 }
3819
Craig Topperc3ec1492014-05-26 06:22:03 +00003820 void *InsertPos = nullptr;
3821 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003822
3823 if (IsPartialSpecialization)
3824 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003825 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003826 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003827 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003828
Craig Topperc3ec1492014-05-26 06:22:03 +00003829 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003830
3831 // Check whether we can declare a variable template specialization in
3832 // the current scope.
3833 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3834 TemplateNameLoc,
3835 IsPartialSpecialization))
3836 return true;
3837
3838 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3839 // Since the only prior variable template specialization with these
3840 // arguments was referenced but not declared, reuse that
3841 // declaration node as our own, updating its source location and
3842 // the list of outer template parameters to reflect our new declaration.
3843 Specialization = PrevDecl;
3844 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003845 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003846 } else if (IsPartialSpecialization) {
3847 // Create a new class template partial specialization declaration node.
3848 VarTemplatePartialSpecializationDecl *PrevPartial =
3849 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003850 VarTemplatePartialSpecializationDecl *Partial =
3851 VarTemplatePartialSpecializationDecl::Create(
3852 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3853 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003854 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003855
3856 if (!PrevPartial)
3857 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3858 Specialization = Partial;
3859
3860 // If we are providing an explicit specialization of a member variable
3861 // template specialization, make a note of that.
3862 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003863 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003864
Richard Smith57aae072016-12-28 02:37:25 +00003865 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003866 } else {
3867 // Create a new class template specialization declaration node for
3868 // this explicit specialization or friend declaration.
3869 Specialization = VarTemplateSpecializationDecl::Create(
3870 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003871 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003872 Specialization->setTemplateArgsInfo(TemplateArgs);
3873
3874 if (!PrevDecl)
3875 VarTemplate->AddSpecialization(Specialization, InsertPos);
3876 }
3877
3878 // C++ [temp.expl.spec]p6:
3879 // If a template, a member template or the member of a class template is
3880 // explicitly specialized then that specialization shall be declared
3881 // before the first use of that specialization that would cause an implicit
3882 // instantiation to take place, in every translation unit in which such a
3883 // use occurs; no diagnostic is required.
3884 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3885 bool Okay = false;
3886 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3887 // Is there any previous explicit specialization declaration?
3888 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3889 Okay = true;
3890 break;
3891 }
3892 }
3893
3894 if (!Okay) {
3895 SourceRange Range(TemplateNameLoc, RAngleLoc);
3896 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3897 << Name << Range;
3898
3899 Diag(PrevDecl->getPointOfInstantiation(),
3900 diag::note_instantiation_required_here)
3901 << (PrevDecl->getTemplateSpecializationKind() !=
3902 TSK_ImplicitInstantiation);
3903 return true;
3904 }
3905 }
3906
3907 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3908 Specialization->setLexicalDeclContext(CurContext);
3909
3910 // Add the specialization into its lexical context, so that it can
3911 // be seen when iterating through the list of declarations in that
3912 // context. However, specializations are not found by name lookup.
3913 CurContext->addDecl(Specialization);
3914
3915 // Note that this is an explicit specialization.
3916 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3917
3918 if (PrevDecl) {
3919 // Check that this isn't a redefinition of this specialization,
3920 // merging with previous declarations.
3921 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00003922 forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003923 PrevSpec.addDecl(PrevDecl);
3924 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003925 } else if (Specialization->isStaticDataMember() &&
3926 Specialization->isOutOfLine()) {
3927 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003928 }
3929
Larisse Voufo39a1e502013-08-06 01:03:05 +00003930 return Specialization;
3931}
3932
3933namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003934/// A partial specialization whose template arguments have matched
Larisse Voufo39a1e502013-08-06 01:03:05 +00003935/// a given template-id.
3936struct PartialSpecMatchResult {
3937 VarTemplatePartialSpecializationDecl *Partial;
3938 TemplateArgumentList *Args;
3939};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003940} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003941
3942DeclResult
3943Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3944 SourceLocation TemplateNameLoc,
3945 const TemplateArgumentListInfo &TemplateArgs) {
3946 assert(Template && "A variable template id without template?");
3947
3948 // Check that the template argument list is well-formed for this template.
3949 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003950 if (CheckTemplateArgumentList(
3951 Template, TemplateNameLoc,
3952 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003953 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003954 return true;
3955
3956 // Find the variable template specialization declaration that
3957 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003958 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003959 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003960 Converted, InsertPos)) {
3961 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003962 // If we already have a variable template specialization, return it.
3963 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003964 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003965
3966 // This is the first time we have referenced this variable template
3967 // specialization. Create the canonical declaration and add it to
3968 // the set of specializations, based on the closest partial specialization
3969 // that it represents. That is,
3970 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3971 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003972 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003973 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3974 bool AmbiguousPartialSpec = false;
3975 typedef PartialSpecMatchResult MatchResult;
3976 SmallVector<MatchResult, 4> Matched;
3977 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003978 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3979 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003980
3981 // 1. Attempt to find the closest partial specialization that this
3982 // specializes, if any.
3983 // If any of the template arguments is dependent, then this is probably
3984 // a placeholder for an incomplete declarative context; which must be
3985 // complete by instantiation time. Thus, do not search through the partial
3986 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003987 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3988 // Perhaps better after unification of DeduceTemplateArguments() and
3989 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003990 bool InstantiationDependent = false;
3991 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3992 TemplateArgs, InstantiationDependent)) {
3993
3994 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3995 Template->getPartialSpecializations(PartialSpecs);
3996
3997 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3998 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3999 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4000
4001 if (TemplateDeductionResult Result =
4002 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4003 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00004004 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00004005 FailedCandidates.addCandidate().set(
4006 DeclAccessPair::make(Template, AS_public), Partial,
4007 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00004008 (void)Result;
4009 } else {
4010 Matched.push_back(PartialSpecMatchResult());
4011 Matched.back().Partial = Partial;
4012 Matched.back().Args = Info.take();
4013 }
4014 }
4015
Larisse Voufo39a1e502013-08-06 01:03:05 +00004016 if (Matched.size() >= 1) {
4017 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4018 if (Matched.size() == 1) {
4019 // -- If exactly one matching specialization is found, the
4020 // instantiation is generated from that specialization.
4021 // We don't need to do anything for this.
4022 } else {
4023 // -- If more than one matching specialization is found, the
4024 // partial order rules (14.5.4.2) are used to determine
4025 // whether one of the specializations is more specialized
4026 // than the others. If none of the specializations is more
4027 // specialized than all of the other matching
4028 // specializations, then the use of the variable template is
4029 // ambiguous and the program is ill-formed.
4030 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4031 PEnd = Matched.end();
4032 P != PEnd; ++P) {
4033 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4034 PointOfInstantiation) ==
4035 P->Partial)
4036 Best = P;
4037 }
4038
4039 // Determine if the best partial specialization is more specialized than
4040 // the others.
4041 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4042 PEnd = Matched.end();
4043 P != PEnd; ++P) {
4044 if (P != Best && getMoreSpecializedPartialSpecialization(
4045 P->Partial, Best->Partial,
4046 PointOfInstantiation) != Best->Partial) {
4047 AmbiguousPartialSpec = true;
4048 break;
4049 }
4050 }
4051 }
4052
4053 // Instantiate using the best variable template partial specialization.
4054 InstantiationPattern = Best->Partial;
4055 InstantiationArgs = Best->Args;
4056 } else {
4057 // -- If no match is found, the instantiation is generated
4058 // from the primary template.
4059 // InstantiationPattern = Template->getTemplatedDecl();
4060 }
4061 }
4062
Larisse Voufo39a1e502013-08-06 01:03:05 +00004063 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00004064 // Note that we do not instantiate a definition until we see an odr-use
4065 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00004066 // FIXME: LateAttrs et al.?
4067 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4068 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4069 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4070 if (!Decl)
4071 return true;
4072
4073 if (AmbiguousPartialSpec) {
4074 // Partial ordering did not produce a clear winner. Complain.
4075 Decl->setInvalidDecl();
4076 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4077 << Decl;
4078
4079 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00004080 for (MatchResult P : Matched)
4081 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4082 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4083 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004084 return true;
4085 }
4086
4087 if (VarTemplatePartialSpecializationDecl *D =
4088 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4089 Decl->setInstantiationOf(D, InstantiationArgs);
4090
Richard Smith6739a102016-05-05 00:56:12 +00004091 checkSpecializationVisibility(TemplateNameLoc, Decl);
4092
Larisse Voufo39a1e502013-08-06 01:03:05 +00004093 assert(Decl && "No variable template specialization?");
4094 return Decl;
4095}
4096
4097ExprResult
4098Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4099 const DeclarationNameInfo &NameInfo,
4100 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4101 const TemplateArgumentListInfo *TemplateArgs) {
4102
4103 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4104 *TemplateArgs);
4105 if (Decl.isInvalid())
4106 return ExprError();
4107
4108 VarDecl *Var = cast<VarDecl>(Decl.get());
4109 if (!Var->getTemplateSpecializationKind())
4110 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4111 NameInfo.getLoc());
4112
4113 // Build an ordinary singleton decl ref.
4114 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00004115 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004116}
4117
Richard Smithecad88d2018-04-26 01:08:00 +00004118void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4119 SourceLocation Loc) {
4120 Diag(Loc, diag::err_template_missing_args)
4121 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4122 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4123 Diag(TD->getLocation(), diag::note_template_decl_here)
4124 << TD->getTemplateParameters()->getSourceRange();
4125 }
4126}
4127
John McCalldadc5752010-08-24 06:29:42 +00004128ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004129 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00004130 LookupResult &R,
4131 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004132 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00004133 // FIXME: Can we do any checking at this point? I guess we could check the
4134 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00004135 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00004136 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00004137 // foo<int> could identify a single function unambiguously
4138 // This approach does NOT work, since f<int>(1);
4139 // gets resolved prior to resorting to overload resolution
4140 // i.e., template<class T> void f(double);
4141 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00004142
4143 // These should be filtered out by our callers.
4144 assert(!R.empty() && "empty lookup results when building templateid");
4145 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4146
Richard Smith04100942018-04-26 02:10:22 +00004147 // Non-function templates require a template argument list.
4148 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4149 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4150 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4151 return ExprError();
4152 }
4153 }
4154
Richard Smith0bf96f92018-04-25 22:58:55 +00004155 auto AnyDependentArguments = [&]() -> bool {
4156 bool InstantiationDependent;
4157 return TemplateArgs &&
4158 TemplateSpecializationType::anyDependentTemplateArguments(
4159 *TemplateArgs, InstantiationDependent);
4160 };
4161
Larisse Voufo39a1e502013-08-06 01:03:05 +00004162 // In C++1y, check variable template ids.
Richard Smith0bf96f92018-04-25 22:58:55 +00004163 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
Richard Smithd7d11ef2014-02-03 20:09:56 +00004164 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4165 R.getAsSingle<VarTemplateDecl>(),
4166 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004167 }
4168
John McCall58cc69d2010-01-27 01:50:18 +00004169 // We don't want lookup warnings at this point.
4170 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004171
John McCalle66edc12009-11-24 19:00:30 +00004172 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00004173 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00004174 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004175 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004176 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004177 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00004178 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00004179
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004180 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00004181}
4182
John McCalle66edc12009-11-24 19:00:30 +00004183// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00004184ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004185Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004186 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004187 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004188 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004189
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004190 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00004191 DeclContext *DC;
4192 if (!(DC = computeDeclContext(SS, false)) ||
4193 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00004194 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00004195 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004196
Douglas Gregor786123d2010-05-21 23:18:07 +00004197 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004198 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +00004199 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4200 /*Entering*/false, MemberOfUnknownSpecialization,
4201 TemplateKWLoc))
4202 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004203
John McCalle66edc12009-11-24 19:00:30 +00004204 if (R.isAmbiguous())
4205 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004206
John McCalle66edc12009-11-24 19:00:30 +00004207 if (R.empty()) {
Richard Smith79810042018-05-11 02:43:08 +00004208 Diag(NameInfo.getLoc(), diag::err_no_member)
4209 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004210 return ExprError();
4211 }
4212
4213 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004214 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00004215 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00004216 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004217 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4218 return ExprError();
4219 }
4220
Abramo Bagnara7945c982012-01-27 09:46:47 +00004221 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00004222}
4223
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004224/// Form a dependent template name.
Douglas Gregorb67535d2009-03-31 00:43:58 +00004225///
4226/// This action forms a dependent template name given the template
4227/// name and its (presumably dependent) scope specifier. For
4228/// example, given "MetaFun::template apply", the scope specifier \p
4229/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4230/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004231TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00004232 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004233 SourceLocation TemplateKWLoc,
Richard Smithc08b6932018-04-27 02:00:13 +00004234 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00004235 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00004236 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00004237 TemplateTy &Result,
4238 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004239 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4240 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004241 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004242 diag::warn_cxx98_compat_template_outside_of_template :
4243 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004244 << FixItHint::CreateRemoval(TemplateKWLoc);
4245
Craig Topperc3ec1492014-05-26 06:22:03 +00004246 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00004247 if (SS.isSet())
4248 LookupCtx = computeDeclContext(SS, EnteringContext);
4249 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00004250 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00004251 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00004252 // C++0x [temp.names]p5:
4253 // If a name prefixed by the keyword template is not the name of
4254 // a template, the program is ill-formed. [Note: the keyword
4255 // template may not be applied to non-template members of class
4256 // templates. -end note ] [ Note: as is the case with the
4257 // typename prefix, the template prefix is allowed in cases
4258 // where it is not strictly necessary; i.e., when the
4259 // nested-name-specifier or the expression on the left of the ->
4260 // or . is not dependent on a template-parameter, or the use
4261 // does not appear in the scope of a template. -end note]
4262 //
4263 // Note: C++03 was more strict here, because it banned the use of
4264 // the "template" keyword prior to a template-name that was not a
4265 // dependent name. C++ DR468 relaxed this requirement (the
4266 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00004267 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00004268 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00004269 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00004270 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00004271 MemberOfUnknownSpecialization);
Richard Smith79810042018-05-11 02:43:08 +00004272 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
Douglas Gregorbb119652010-06-16 23:00:59 +00004273 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00004274 } else if (TNK == TNK_Non_template) {
Richard Smith79810042018-05-11 02:43:08 +00004275 // Do the lookup again to determine if this is a "nothing found" case or
4276 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4277 // need to do this.
4278 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004279 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
Richard Smith79810042018-05-11 02:43:08 +00004280 LookupOrdinaryName);
4281 bool MOUS;
4282 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
Richard Smithafcfb6b2019-02-15 21:53:07 +00004283 MOUS, TemplateKWLoc) && !R.isAmbiguous())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004284 Diag(Name.getBeginLoc(), diag::err_no_member)
Richard Smith79810042018-05-11 02:43:08 +00004285 << DNI.getName() << LookupCtx << SS.getRange();
Douglas Gregorbb119652010-06-16 23:00:59 +00004286 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00004287 } else {
4288 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00004289 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4290 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
Faisal Vali2ab8c152017-12-30 04:15:27 +00004291 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4292 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
Richard Smithfd3dae02017-01-20 00:20:39 +00004293 // C++14 [class.qual]p2:
4294 // In a lookup in which function names are not ignored and the
4295 // nested-name-specifier nominates a class C, if the name specified
4296 // [...] is the injected-class-name of C, [...] the name is instead
4297 // considered to name the constructor
4298 //
4299 // We don't get here if naming the constructor would be valid, so we
4300 // just reject immediately and recover by treating the
4301 // injected-class-name as naming the template.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004302 Diag(Name.getBeginLoc(),
Richard Smithfd3dae02017-01-20 00:20:39 +00004303 diag::ext_out_of_line_qualified_id_type_names_constructor)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004304 << Name.Identifier
4305 << 0 /*injected-class-name used as template name*/
4306 << 1 /*'template' keyword was used*/;
Richard Smithfd3dae02017-01-20 00:20:39 +00004307 }
Douglas Gregorbb119652010-06-16 23:00:59 +00004308 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004309 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00004310 }
4311
Aaron Ballman4a979672014-01-03 13:56:08 +00004312 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313
Douglas Gregor3cf81312009-11-03 23:16:33 +00004314 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00004315 case UnqualifiedIdKind::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004316 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00004317 Name.Identifier));
4318 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319
Faisal Vali2ab8c152017-12-30 04:15:27 +00004320 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00004321 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00004322 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00004323 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00004324
Faisal Vali2ab8c152017-12-30 04:15:27 +00004325 case UnqualifiedIdKind::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00004326 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00004327
Douglas Gregor3cf81312009-11-03 23:16:33 +00004328 default:
4329 break;
4330 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004331
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004332 Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4333 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4334 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004335 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004336}
4337
Mike Stump11289f42009-09-09 15:08:12 +00004338bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004339 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004340 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00004341 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00004342 QualType ArgType;
4343 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00004344
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004345 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004346 switch(Arg.getKind()) {
4347 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004348 // C++ [temp.arg.type]p1:
4349 // A template-argument for a template-parameter which is a
4350 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00004351 ArgType = Arg.getAsType();
4352 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004353 break;
Richard Smith77a9c602018-02-28 03:02:23 +00004354 case TemplateArgument::Template:
4355 case TemplateArgument::TemplateExpansion: {
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004356 // We have a template type parameter but the template argument
4357 // is a template without any arguments.
4358 SourceRange SR = AL.getSourceRange();
Richard Smith77a9c602018-02-28 03:02:23 +00004359 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
Richard Smithecad88d2018-04-26 01:08:00 +00004360 diagnoseMissingTemplateArguments(Name, SR.getEnd());
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004361 return true;
4362 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004363 case TemplateArgument::Expression: {
4364 // We have a template type parameter but the template argument is an
4365 // expression; see if maybe it is missing the "typename" keyword.
4366 CXXScopeSpec SS;
4367 DeclarationNameInfo NameInfo;
4368
4369 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4370 SS.Adopt(ArgExpr->getQualifierLoc());
4371 NameInfo = ArgExpr->getNameInfo();
4372 } else if (DependentScopeDeclRefExpr *ArgExpr =
4373 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4374 SS.Adopt(ArgExpr->getQualifierLoc());
4375 NameInfo = ArgExpr->getNameInfo();
4376 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4377 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004378 if (ArgExpr->isImplicitAccess()) {
4379 SS.Adopt(ArgExpr->getQualifierLoc());
4380 NameInfo = ArgExpr->getMemberNameInfo();
4381 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004382 }
4383
Reid Kleckner377c1592014-06-10 23:29:48 +00004384 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004385 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4386 LookupParsedName(Result, CurScope, &SS);
4387
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004388 if (Result.getAsSingle<TypeDecl>() ||
4389 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00004390 LookupResult::NotFoundInCurrentInstantiation) {
4391 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004392 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00004393 Diag(Loc, getLangOpts().MSVCCompat
4394 ? diag::ext_ms_template_type_arg_missing_typename
4395 : diag::err_template_arg_must_be_type_suggest)
4396 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004397 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00004398
4399 // Recover by synthesizing a type using the location information that we
4400 // already have.
4401 ArgType =
4402 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4403 TypeLocBuilder TLB;
4404 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4405 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4406 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4407 TL.setNameLoc(NameInfo.getLoc());
4408 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4409
4410 // Overwrite our input TemplateArgumentLoc so that we can recover
4411 // properly.
4412 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4413 TemplateArgumentLocInfo(TSI));
4414
4415 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004416 }
4417 }
4418 // fallthrough
Galina Kistanova3779cb32017-06-07 06:25:05 +00004419 LLVM_FALLTHROUGH;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004420 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004421 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004422 // We have a template type parameter but the template argument
4423 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00004424 SourceRange SR = AL.getSourceRange();
4425 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004426 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00004427
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004428 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004429 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004430 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004431
Reid Kleckner377c1592014-06-10 23:29:48 +00004432 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004433 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004434
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004435 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00004436 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004437
Douglas Gregore46db902011-06-17 22:11:49 +00004438 // Objective-C ARC:
4439 // If an explicitly-specified template argument type is a lifetime type
4440 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004441 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00004442 ArgType->isObjCLifetimeType() &&
4443 !ArgType.getObjCLifetime()) {
4444 Qualifiers Qs;
4445 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4446 ArgType = Context.getQualifiedType(ArgType, Qs);
4447 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004448
Douglas Gregore46db902011-06-17 22:11:49 +00004449 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004450 return false;
4451}
4452
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004453/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004454/// the given template type parameter.
4455///
4456/// \param SemaRef the semantic analysis object for which we are performing
4457/// the substitution.
4458///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004459/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004460/// for.
4461///
4462/// \param TemplateLoc the location of the template name that started the
4463/// template-id we are checking.
4464///
4465/// \param RAngleLoc the location of the right angle bracket ('>') that
4466/// terminates the template-id.
4467///
4468/// \param Param the template template parameter whose default we are
4469/// substituting into.
4470///
4471/// \param Converted the list of template arguments provided for template
4472/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004473/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00004474static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004475SubstDefaultTemplateArgument(Sema &SemaRef,
4476 TemplateDecl *Template,
4477 SourceLocation TemplateLoc,
4478 SourceLocation RAngleLoc,
4479 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00004480 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00004481 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004482
4483 // If the argument type is dependent, instantiate it now based
4484 // on the previously-computed template arguments.
Erik Pilkingtonba88e212018-11-12 21:31:06 +00004485 if (ArgType->getType()->isInstantiationDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004486 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004487 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004488 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004489 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004490 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004491
David Majnemer8b622692016-07-03 21:17:51 +00004492 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004493
4494 // Only substitute for the innermost template argument list.
4495 MultiLevelTemplateArgumentList TemplateArgLists;
4496 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4497 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4498 TemplateArgLists.addOuterTemplateArguments(None);
4499
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004500 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004501 ArgType =
4502 SemaRef.SubstType(ArgType, TemplateArgLists,
4503 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004504 }
4505
4506 return ArgType;
4507}
4508
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004509/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004510/// the given non-type template parameter.
4511///
4512/// \param SemaRef the semantic analysis object for which we are performing
4513/// the substitution.
4514///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004515/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004516/// for.
4517///
4518/// \param TemplateLoc the location of the template name that started the
4519/// template-id we are checking.
4520///
4521/// \param RAngleLoc the location of the right angle bracket ('>') that
4522/// terminates the template-id.
4523///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004524/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004525/// substituting into.
4526///
4527/// \param Converted the list of template arguments provided for template
4528/// parameters that precede \p Param in the template parameter list.
4529///
4530/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004531static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004532SubstDefaultTemplateArgument(Sema &SemaRef,
4533 TemplateDecl *Template,
4534 SourceLocation TemplateLoc,
4535 SourceLocation RAngleLoc,
4536 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004537 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004538 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004539 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004540 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004541 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004542 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004543
David Majnemer8b622692016-07-03 21:17:51 +00004544 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004545
4546 // Only substitute for the innermost template argument list.
4547 MultiLevelTemplateArgumentList TemplateArgLists;
4548 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4549 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4550 TemplateArgLists.addOuterTemplateArguments(None);
4551
Faisal Valid143a0c2017-04-01 21:30:49 +00004552 EnterExpressionEvaluationContext ConstantEvaluated(
4553 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004554 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004555}
4556
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004557/// Substitute template arguments into the default template argument for
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004558/// the given template template parameter.
4559///
4560/// \param SemaRef the semantic analysis object for which we are performing
4561/// the substitution.
4562///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004563/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004564/// for.
4565///
4566/// \param TemplateLoc the location of the template name that started the
4567/// template-id we are checking.
4568///
4569/// \param RAngleLoc the location of the right angle bracket ('>') that
4570/// terminates the template-id.
4571///
4572/// \param Param the template template parameter whose default we are
4573/// substituting into.
4574///
4575/// \param Converted the list of template arguments provided for template
4576/// parameters that precede \p Param in the template parameter list.
4577///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004578/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004579/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004580///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004581/// \returns the substituted template argument, or NULL if an error occurred.
4582static TemplateName
4583SubstDefaultTemplateArgument(Sema &SemaRef,
4584 TemplateDecl *Template,
4585 SourceLocation TemplateLoc,
4586 SourceLocation RAngleLoc,
4587 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004588 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004589 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004590 Sema::InstantiatingTemplate Inst(
4591 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4592 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004593 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004594 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004595
David Majnemer8b622692016-07-03 21:17:51 +00004596 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004597
4598 // Only substitute for the innermost template argument list.
4599 MultiLevelTemplateArgumentList TemplateArgLists;
4600 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4601 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4602 TemplateArgLists.addOuterTemplateArguments(None);
4603
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004604 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004605 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004606 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004607 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004608 QualifierLoc =
4609 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004610 if (!QualifierLoc)
4611 return TemplateName();
4612 }
David Majnemer89189202013-08-28 23:48:32 +00004613
4614 return SemaRef.SubstTemplateName(
4615 QualifierLoc,
4616 Param->getDefaultArgument().getArgument().getAsTemplate(),
4617 Param->getDefaultArgument().getTemplateNameLoc(),
4618 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004619}
4620
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004621/// If the given template parameter has a default template
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004622/// argument, substitute into that default template argument and
4623/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004624TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004625Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4626 SourceLocation TemplateLoc,
4627 SourceLocation RAngleLoc,
4628 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004629 SmallVectorImpl<TemplateArgument>
4630 &Converted,
4631 bool &HasDefaultArg) {
4632 HasDefaultArg = false;
4633
4634 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004635 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004636 return TemplateArgumentLoc();
4637
Richard Smithc87b9382013-07-04 01:01:24 +00004638 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004639 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004640 TemplateLoc,
4641 RAngleLoc,
4642 TypeParm,
4643 Converted);
4644 if (DI)
4645 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4646
4647 return TemplateArgumentLoc();
4648 }
4649
4650 if (NonTypeTemplateParmDecl *NonTypeParm
4651 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004652 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004653 return TemplateArgumentLoc();
4654
Richard Smithc87b9382013-07-04 01:01:24 +00004655 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004656 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004657 TemplateLoc,
4658 RAngleLoc,
4659 NonTypeParm,
4660 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004661 if (Arg.isInvalid())
4662 return TemplateArgumentLoc();
4663
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004664 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004665 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4666 }
4667
4668 TemplateTemplateParmDecl *TempTempParm
4669 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004670 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004671 return TemplateArgumentLoc();
4672
Richard Smithc87b9382013-07-04 01:01:24 +00004673 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004674 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004675 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004676 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004677 RAngleLoc,
4678 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004679 Converted,
4680 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004681 if (TName.isNull())
4682 return TemplateArgumentLoc();
4683
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004684 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004685 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004686 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4687}
4688
Richard Smith11255ec2017-01-18 19:19:22 +00004689/// Convert a template-argument that we parsed as a type into a template, if
4690/// possible. C++ permits injected-class-names to perform dual service as
4691/// template template arguments and as template type arguments.
4692static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4693 // Extract and step over any surrounding nested-name-specifier.
4694 NestedNameSpecifierLoc QualLoc;
4695 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4696 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4697 return TemplateArgumentLoc();
4698
4699 QualLoc = ETLoc.getQualifierLoc();
4700 TLoc = ETLoc.getNamedTypeLoc();
4701 }
4702
4703 // If this type was written as an injected-class-name, it can be used as a
4704 // template template argument.
4705 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4706 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4707 QualLoc, InjLoc.getNameLoc());
4708
4709 // If this type was written as an injected-class-name, it may have been
4710 // converted to a RecordType during instantiation. If the RecordType is
4711 // *not* wrapped in a TemplateSpecializationType and denotes a class
4712 // template specialization, it must have come from an injected-class-name.
4713 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4714 if (auto *CTSD =
4715 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4716 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4717 QualLoc, RecLoc.getNameLoc());
4718
4719 return TemplateArgumentLoc();
4720}
4721
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004722/// Check that the given template argument corresponds to the given
Douglas Gregorda0fb532009-11-11 19:31:23 +00004723/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004724///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004725/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004726/// checked.
4727///
Richard Trieu15b66532015-01-24 02:48:32 +00004728/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004729///
4730/// \param Template The template in which the template argument resides.
4731///
4732/// \param TemplateLoc The location of the template name for the template
4733/// whose argument list we're matching.
4734///
4735/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4736/// the template argument list.
4737///
4738/// \param ArgumentPackIndex The index into the argument pack where this
4739/// argument will be placed. Only valid if the parameter is a parameter pack.
4740///
4741/// \param Converted The checked, converted argument will be added to the
4742/// end of this small vector.
4743///
4744/// \param CTAK Describes how we arrived at this particular template argument:
4745/// explicitly written, deduced, etc.
4746///
4747/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004748bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004749 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004750 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004751 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004752 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004753 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004754 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004755 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004756 // Check template type parameters.
4757 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004758 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004759
Douglas Gregoreebed722009-11-11 19:41:09 +00004760 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004761 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004762 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004763 // with the template arguments we've seen thus far. But if the
4764 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004765 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004766 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4767 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004768
Richard Smith5d331022018-03-08 01:07:33 +00004769 // FIXME: Do we need to substitute into parameters here if they're
4770 // instantiation-dependent but not dependent?
Peter Collingbourne01687632010-12-10 17:08:53 +00004771 if (NTTPType->isDependentType() &&
4772 !isa<TemplateTemplateParmDecl>(Template) &&
4773 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004774 // Do substitution on the type of the non-type template parameter.
4775 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004776 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004777 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004778 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004779 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004780
4781 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004782 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004783 NTTPType = SubstType(NTTPType,
4784 MultiLevelTemplateArgumentList(TemplateArgs),
4785 NTTP->getLocation(),
4786 NTTP->getDeclName());
4787 // If that worked, check the non-type template parameter type
4788 // for validity.
4789 if (!NTTPType.isNull())
4790 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4791 NTTP->getLocation());
4792 if (NTTPType.isNull())
4793 return true;
4794 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004795
Douglas Gregorda0fb532009-11-11 19:31:23 +00004796 switch (Arg.getArgument().getKind()) {
4797 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004798 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004799
Douglas Gregorda0fb532009-11-11 19:31:23 +00004800 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004801 TemplateArgument Result;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004802 unsigned CurSFINAEErrors = NumSFINAEErrors;
John Wiegley01296292011-04-08 18:41:53 +00004803 ExprResult Res =
4804 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4805 Result, CTAK);
4806 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004807 return true;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004808 // If the current template argument causes an error, give up now.
4809 if (CurSFINAEErrors < NumSFINAEErrors)
4810 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004811
Richard Trieu15b66532015-01-24 02:48:32 +00004812 // If the resulting expression is new, then use it in place of the
4813 // old expression in the template argument.
4814 if (Res.get() != Arg.getArgument().getAsExpr()) {
4815 TemplateArgument TA(Res.get());
4816 Arg = TemplateArgumentLoc(TA, Res.get());
4817 }
4818
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004819 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004820 break;
4821 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004822
Douglas Gregorda0fb532009-11-11 19:31:23 +00004823 case TemplateArgument::Declaration:
4824 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004825 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004826 // We've already checked this template argument, so just copy
4827 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004828 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004829 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830
Douglas Gregorda0fb532009-11-11 19:31:23 +00004831 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004832 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004833 // We were given a template template argument. It may not be ill-formed;
4834 // see below.
4835 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004836 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4837 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004838 // We have a template argument such as \c T::template X, which we
4839 // parsed as a template template argument. However, since we now
4840 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004841 // template name into an expression.
4842
4843 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4844 Arg.getTemplateNameLoc());
4845
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004846 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004847 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004848 // FIXME: the template-template arg was a DependentTemplateName,
4849 // so it was provided with a template keyword. However, its source
4850 // location is not stored in the template argument structure.
4851 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004852 ExprResult E = DependentScopeDeclRefExpr::Create(
4853 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4854 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004855
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004856 // If we parsed the template argument as a pack expansion, create a
4857 // pack expansion expression.
4858 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004859 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004860 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004861 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004862 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004863
Douglas Gregorda0fb532009-11-11 19:31:23 +00004864 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004865 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004866 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004867 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004868
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004869 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004870 break;
4871 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004872
Douglas Gregorda0fb532009-11-11 19:31:23 +00004873 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004874 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004875 // therefore cannot be a non-type template argument.
4876 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4877 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004878
Douglas Gregorda0fb532009-11-11 19:31:23 +00004879 Diag(Param->getLocation(), diag::note_template_param_here);
4880 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004881
Douglas Gregorda0fb532009-11-11 19:31:23 +00004882 case TemplateArgument::Type: {
4883 // We have a non-type template parameter but the template
4884 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004885
Douglas Gregorda0fb532009-11-11 19:31:23 +00004886 // C++ [temp.arg]p2:
4887 // In a template-argument, an ambiguity between a type-id and
4888 // an expression is resolved to a type-id, regardless of the
4889 // form of the corresponding template-parameter.
4890 //
4891 // We warn specifically about this case, since it can be rather
4892 // confusing for users.
4893 QualType T = Arg.getArgument().getAsType();
4894 SourceRange SR = Arg.getSourceRange();
4895 if (T->isFunctionType())
4896 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4897 else
4898 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4899 Diag(Param->getLocation(), diag::note_template_param_here);
4900 return true;
4901 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004902
Douglas Gregorda0fb532009-11-11 19:31:23 +00004903 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004904 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004906
Douglas Gregorda0fb532009-11-11 19:31:23 +00004907 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004908 }
4909
4910
Douglas Gregorda0fb532009-11-11 19:31:23 +00004911 // Check template template parameters.
4912 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004913
Richard Smith5d331022018-03-08 01:07:33 +00004914 TemplateParameterList *Params = TempParm->getTemplateParameters();
4915 if (TempParm->isExpandedParameterPack())
4916 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
4917
Douglas Gregorda0fb532009-11-11 19:31:23 +00004918 // Substitute into the template parameter list of the template
4919 // template parameter, since previously-supplied template arguments
4920 // may appear within the template template parameter.
Richard Smith5d331022018-03-08 01:07:33 +00004921 //
4922 // FIXME: Skip this if the parameters aren't instantiation-dependent.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004923 {
4924 // Set up a template instantiation context.
4925 LocalInstantiationScope Scope(*this);
4926 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004927 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004928 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004929 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004930 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004931
David Majnemer8b622692016-07-03 21:17:51 +00004932 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Richard Smith5d331022018-03-08 01:07:33 +00004933 Params = SubstTemplateParams(Params, CurContext,
4934 MultiLevelTemplateArgumentList(TemplateArgs));
4935 if (!Params)
Douglas Gregorda0fb532009-11-11 19:31:23 +00004936 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004937 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004938
Richard Smith11255ec2017-01-18 19:19:22 +00004939 // C++1z [temp.local]p1: (DR1004)
4940 // When [the injected-class-name] is used [...] as a template-argument for
4941 // a template template-parameter [...] it refers to the class template
4942 // itself.
4943 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4944 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4945 Arg.getTypeSourceInfo()->getTypeLoc());
4946 if (!ConvertedArg.getArgument().isNull())
4947 Arg = ConvertedArg;
4948 }
4949
Douglas Gregorda0fb532009-11-11 19:31:23 +00004950 switch (Arg.getArgument().getKind()) {
4951 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004952 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004953
Douglas Gregorda0fb532009-11-11 19:31:23 +00004954 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004955 case TemplateArgument::TemplateExpansion:
Richard Smith5d331022018-03-08 01:07:33 +00004956 if (CheckTemplateTemplateArgument(Params, Arg))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004957 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004958
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004959 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004960 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004961
Douglas Gregorda0fb532009-11-11 19:31:23 +00004962 case TemplateArgument::Expression:
4963 case TemplateArgument::Type:
4964 // We have a template template parameter but the template
4965 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004966 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004967 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004968 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969
Douglas Gregorda0fb532009-11-11 19:31:23 +00004970 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004971 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004972 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004973 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004974 case TemplateArgument::NullPtr:
4975 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004976
Douglas Gregorda0fb532009-11-11 19:31:23 +00004977 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004978 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980
Douglas Gregorda0fb532009-11-11 19:31:23 +00004981 return false;
4982}
4983
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004984/// Check whether the template parameter is a pack expansion, and if so,
Richard Smith1fde8ec2012-09-07 02:06:42 +00004985/// determine the number of parameters produced by that expansion. For instance:
4986///
4987/// \code
4988/// template<typename ...Ts> struct A {
4989/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4990/// };
4991/// \endcode
4992///
4993/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4994/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004995static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004996 if (NonTypeTemplateParmDecl *NTTP
4997 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4998 if (NTTP->isExpandedParameterPack())
4999 return NTTP->getNumExpansionTypes();
5000 }
5001
5002 if (TemplateTemplateParmDecl *TTP
5003 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
5004 if (TTP->isExpandedParameterPack())
5005 return TTP->getNumExpansionTemplateParameters();
5006 }
5007
David Blaikie7a30dc52013-02-21 01:47:18 +00005008 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00005009}
5010
Richard Smith35c1df52015-06-17 20:16:32 +00005011/// Diagnose a missing template argument.
5012template<typename TemplateParmDecl>
5013static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5014 TemplateDecl *TD,
5015 const TemplateParmDecl *D,
5016 TemplateArgumentListInfo &Args) {
5017 // Dig out the most recent declaration of the template parameter; there may be
5018 // declarations of the template that are more recent than TD.
5019 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5020 ->getTemplateParameters()
5021 ->getParam(D->getIndex()));
5022
5023 // If there's a default argument that's not visible, diagnose that we're
5024 // missing a module import.
5025 llvm::SmallVector<Module*, 8> Modules;
5026 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5027 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5028 D->getDefaultArgumentLoc(), Modules,
5029 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00005030 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00005031 return true;
5032 }
5033
5034 // FIXME: If there's a more recent default argument that *is* visible,
5035 // diagnose that it was declared too late.
5036
Richard Smith4a8f3512018-07-19 19:00:37 +00005037 TemplateParameterList *Params = TD->getTemplateParameters();
5038
5039 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5040 << /*not enough args*/0
5041 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5042 << TD;
5043 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5044 << Params->getSourceRange();
5045 return true;
Richard Smith35c1df52015-06-17 20:16:32 +00005046}
5047
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005048/// Check that the given template argument list is well-formed
Douglas Gregord32e0282009-02-09 23:23:08 +00005049/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00005050bool Sema::CheckTemplateArgumentList(
5051 TemplateDecl *Template, SourceLocation TemplateLoc,
5052 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5053 SmallVectorImpl<TemplateArgument> &Converted,
5054 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00005055 // Make a copy of the template arguments for processing. Only make the
5056 // changes at the end when successful in matching the arguments to the
5057 // template.
5058 TemplateArgumentListInfo NewArgs = TemplateArgs;
5059
Erich Keaneaf0795b2017-10-24 01:39:56 +00005060 // Make sure we get the template parameter list from the most
5061 // recentdeclaration, since that is the only one that has is guaranteed to
5062 // have all the default template argument information.
5063 TemplateParameterList *Params =
5064 cast<TemplateDecl>(Template->getMostRecentDecl())
5065 ->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00005066
Richard Trieu15b66532015-01-24 02:48:32 +00005067 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00005068
Mike Stump11289f42009-09-09 15:08:12 +00005069 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00005070 // [...] The type and form of each template-argument specified in
5071 // a template-id shall match the type and form specified for the
5072 // corresponding parameter declared by the template in its
5073 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00005074 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005075 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00005076 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00005077 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00005078 for (TemplateParameterList::iterator Param = Params->begin(),
5079 ParamEnd = Params->end();
5080 Param != ParamEnd; /* increment in loop */) {
5081 // If we have an expanded parameter pack, make sure we don't have too
5082 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00005083 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005084 if (*Expansions == ArgumentPack.size()) {
5085 // We're done with this parameter pack. Pack up its arguments and add
5086 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00005087 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00005088 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005089 ArgumentPack.clear();
5090
Richard Smith1fde8ec2012-09-07 02:06:42 +00005091 // This argument is assigned to the next parameter.
5092 ++Param;
5093 continue;
5094 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5095 // Not enough arguments for this parameter pack.
5096 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
Richard Smith4a8f3512018-07-19 19:00:37 +00005097 << /*not enough args*/0
Richard Smith0c062b42017-01-14 02:19:59 +00005098 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00005099 << Template;
5100 Diag(Template->getLocation(), diag::note_template_decl_here)
5101 << Params->getSourceRange();
5102 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005103 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005104 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005105
Richard Smith1fde8ec2012-09-07 02:06:42 +00005106 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00005107 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00005108 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005109 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005110 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00005111 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005112
Richard Smith96d71c32014-11-12 23:38:38 +00005113 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00005114 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00005115 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5116 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00005117 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00005118 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00005119 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00005120 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00005121 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00005122 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00005123 Diag((*Param)->getLocation(), diag::note_template_param_here);
5124 return true;
5125 }
5126
Richard Smith1fde8ec2012-09-07 02:06:42 +00005127 // We're now done with this argument.
5128 ++ArgIdx;
5129
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005130 if ((*Param)->isTemplateParameterPack()) {
5131 // The template parameter was a template parameter pack, so take the
5132 // deduced argument and place it on the argument pack. Note that we
5133 // stay on the same template parameter so that we can deduce more
5134 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00005135 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005136 } else {
5137 // Move to the next template parameter.
5138 ++Param;
5139 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005140
Richard Smith96d71c32014-11-12 23:38:38 +00005141 // If we just saw a pack expansion into a non-pack, then directly convert
5142 // the remaining arguments, because we don't know what parameters they'll
5143 // match up with.
5144 if (PackExpansionIntoNonPack) {
5145 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005146 // If we were part way through filling in an expanded parameter pack,
5147 // fall back to just producing individual arguments.
5148 Converted.insert(Converted.end(),
5149 ArgumentPack.begin(), ArgumentPack.end());
5150 ArgumentPack.clear();
5151 }
5152
5153 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00005154 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00005155 ++ArgIdx;
5156 }
5157
Richard Smith1fde8ec2012-09-07 02:06:42 +00005158 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00005159 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005160
Douglas Gregor84d49a22009-11-11 21:54:23 +00005161 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005163
Douglas Gregor2f157c92011-06-03 02:59:40 +00005164 // If we're checking a partial template argument list, we're done.
5165 if (PartialTemplateArgs) {
5166 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00005167 Converted.push_back(
5168 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5169
Richard Smith1fde8ec2012-09-07 02:06:42 +00005170 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00005171 }
5172
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005173 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005174 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00005175 if ((*Param)->isTemplateParameterPack()) {
5176 assert(!getExpandedPackSize(*Param) &&
5177 "Should have dealt with this already");
5178
5179 // A non-expanded parameter pack before the end of the parameter list
5180 // only occurs for an ill-formed template parameter list, unless we've
5181 // got a partial argument list for a function template, so just bail out.
5182 if (Param + 1 != ParamEnd)
5183 return true;
5184
Benjamin Kramercce63472015-08-05 09:40:22 +00005185 Converted.push_back(
5186 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005187 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00005188
5189 ++Param;
5190 continue;
5191 }
5192
Douglas Gregor8e072612012-02-03 07:34:46 +00005193 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00005194 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005195
Douglas Gregor84d49a22009-11-11 21:54:23 +00005196 // Retrieve the default template argument from the template
5197 // parameter. For each kind of template parameter, we substitute the
5198 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005199 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00005200 // the default argument.
5201 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005202 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005203 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5204 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005205
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005206 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005207 Template,
5208 TemplateLoc,
5209 RAngleLoc,
5210 TTP,
5211 Converted);
5212 if (!ArgType)
5213 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005214
Douglas Gregor84d49a22009-11-11 21:54:23 +00005215 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5216 ArgType);
5217 } else if (NonTypeTemplateParmDecl *NTTP
5218 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005219 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005220 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5221 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005222
John McCalldadc5752010-08-24 06:29:42 +00005223 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005224 TemplateLoc,
5225 RAngleLoc,
5226 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005227 Converted);
5228 if (E.isInvalid())
5229 return true;
5230
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005231 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00005232 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5233 } else {
5234 TemplateTemplateParmDecl *TempParm
5235 = cast<TemplateTemplateParmDecl>(*Param);
5236
Richard Smith95d83952015-06-10 20:36:34 +00005237 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00005238 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5239 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005240
Douglas Gregordf846d12011-03-02 18:46:51 +00005241 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00005242 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005243 TemplateLoc,
5244 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005245 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00005246 Converted,
5247 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005248 if (Name.isNull())
5249 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005250
Douglas Gregor9d802122011-03-02 17:09:35 +00005251 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5252 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00005253 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005254
Douglas Gregor84d49a22009-11-11 21:54:23 +00005255 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00005256 // the default template argument. We're not actually instantiating a
5257 // template here, we just create this object to put a note into the
5258 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00005259 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5260 SourceRange(TemplateLoc, RAngleLoc));
5261 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005262 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005263
Douglas Gregor84d49a22009-11-11 21:54:23 +00005264 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00005265 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005266 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005267 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005268
Richard Trieu15b66532015-01-24 02:48:32 +00005269 // Core issue 150 (assumed resolution): if this is a template template
5270 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00005271 // template definition.
5272 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00005273 NewArgs.addArgument(Arg);
5274
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005275 // Move to the next template parameter and argument.
5276 ++Param;
5277 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00005278 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005279
Richard Smith07f79912014-06-06 16:00:50 +00005280 // If we're performing a partial argument substitution, allow any trailing
5281 // pack expansions; they might be empty. This can happen even if
5282 // PartialTemplateArgs is false (the list of arguments is complete but
5283 // still dependent).
5284 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5285 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00005286 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5287 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00005288 }
5289
Douglas Gregor8e072612012-02-03 07:34:46 +00005290 // If we have any leftover arguments, then there were too many arguments.
5291 // Complain and fail.
Richard Smith4a8f3512018-07-19 19:00:37 +00005292 if (ArgIdx < NumArgs) {
5293 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5294 << /*too many args*/1
5295 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5296 << Template
5297 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5298 Diag(Template->getLocation(), diag::note_template_decl_here)
5299 << Params->getSourceRange();
5300 return true;
5301 }
Richard Trieu15b66532015-01-24 02:48:32 +00005302
5303 // No problems found with the new argument list, propagate changes back
5304 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00005305 if (UpdateArgsWithConversions)
5306 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005307
Richard Smith1fde8ec2012-09-07 02:06:42 +00005308 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00005309}
5310
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005311namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005312 class UnnamedLocalNoLinkageFinder
5313 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005314 {
5315 Sema &S;
5316 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005317
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005318 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005319
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005320 public:
5321 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5322
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005323 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00005324 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005326
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005327#define TYPE(Class, Parent) \
5328 bool Visit##Class##Type(const Class##Type *);
5329#define ABSTRACT_TYPE(Class, Parent) \
5330 bool Visit##Class##Type(const Class##Type *) { return false; }
5331#define NON_CANONICAL_TYPE(Class, Parent) \
5332 bool Visit##Class##Type(const Class##Type *) { return false; }
5333#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005334
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005335 bool VisitTagDecl(const TagDecl *Tag);
5336 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5337 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005338} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005339
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005340bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005341 return false;
5342}
5343
5344bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5345 return Visit(T->getElementType());
5346}
5347
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005348bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005349 return Visit(T->getPointeeType());
5350}
5351
5352bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005353 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005354 return Visit(T->getPointeeType());
5355}
5356
5357bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005358 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005359 return Visit(T->getPointeeType());
5360}
5361
5362bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005363 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005364 return Visit(T->getPointeeType());
5365}
5366
5367bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005368 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005369 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5370}
5371
5372bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005373 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005374 return Visit(T->getElementType());
5375}
5376
5377bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005378 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005379 return Visit(T->getElementType());
5380}
5381
5382bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005383 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005384 return Visit(T->getElementType());
5385}
5386
5387bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005388 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005389 return Visit(T->getElementType());
5390}
5391
5392bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005393 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005394 return Visit(T->getElementType());
5395}
5396
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005397bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5398 const DependentAddressSpaceType *T) {
5399 return Visit(T->getPointeeType());
5400}
5401
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005402bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5403 return Visit(T->getElementType());
5404}
5405
Erich Keanef702b022018-07-13 19:46:04 +00005406bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5407 const DependentVectorType *T) {
5408 return Visit(T->getElementType());
5409}
5410
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005411bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5412 return Visit(T->getElementType());
5413}
5414
5415bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5416 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005417 for (const auto &A : T->param_types()) {
5418 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005419 return true;
5420 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005421
Alp Toker314cc812014-01-25 16:55:45 +00005422 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005423}
5424
5425bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5426 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00005427 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005428}
5429
5430bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5431 const UnresolvedUsingType*) {
5432 return false;
5433}
5434
5435bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5436 return false;
5437}
5438
5439bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5440 return Visit(T->getUnderlyingType());
5441}
5442
5443bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5444 return false;
5445}
5446
Alexis Hunte852b102011-05-24 22:41:36 +00005447bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5448 const UnaryTransformType*) {
5449 return false;
5450}
5451
Richard Smith30482bc2011-02-20 03:19:35 +00005452bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5453 return Visit(T->getDeducedType());
5454}
5455
Richard Smith600b5262017-01-26 20:40:47 +00005456bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5457 const DeducedTemplateSpecializationType *T) {
5458 return Visit(T->getDeducedType());
5459}
5460
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005461bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5462 return VisitTagDecl(T->getDecl());
5463}
5464
5465bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5466 return VisitTagDecl(T->getDecl());
5467}
5468
5469bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5470 const TemplateTypeParmType*) {
5471 return false;
5472}
5473
Douglas Gregorada4b792011-01-14 02:55:32 +00005474bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5475 const SubstTemplateTypeParmPackType *) {
5476 return false;
5477}
5478
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005479bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5480 const TemplateSpecializationType*) {
5481 return false;
5482}
5483
5484bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5485 const InjectedClassNameType* T) {
5486 return VisitTagDecl(T->getDecl());
5487}
5488
5489bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5490 const DependentNameType* T) {
5491 return VisitNestedNameSpecifier(T->getQualifier());
5492}
5493
5494bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5495 const DependentTemplateSpecializationType* T) {
5496 return VisitNestedNameSpecifier(T->getQualifier());
5497}
5498
Douglas Gregord2fa7662010-12-20 02:24:11 +00005499bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5500 const PackExpansionType* T) {
5501 return Visit(T->getPattern());
5502}
5503
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005504bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5505 return false;
5506}
5507
5508bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5509 const ObjCInterfaceType *) {
5510 return false;
5511}
5512
5513bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5514 const ObjCObjectPointerType *) {
5515 return false;
5516}
5517
Eli Friedman0dfb8892011-10-06 23:00:33 +00005518bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5519 return Visit(T->getValueType());
5520}
5521
Xiuli Pan9c14e282016-01-09 12:53:17 +00005522bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5523 return false;
5524}
5525
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005526bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5527 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005528 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005529 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005530 diag::warn_cxx98_compat_template_arg_local_type :
5531 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005532 << S.Context.getTypeDeclType(Tag) << SR;
5533 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005534 }
5535
John McCall5ea95772013-03-09 00:54:27 +00005536 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005537 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005538 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005539 diag::warn_cxx98_compat_template_arg_unnamed_type :
5540 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005541 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5542 return true;
5543 }
5544
5545 return false;
5546}
5547
5548bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5549 NestedNameSpecifier *NNS) {
5550 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5551 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005552
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005553 switch (NNS->getKind()) {
5554 case NestedNameSpecifier::Identifier:
5555 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005556 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005557 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005558 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005559 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005560
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005561 case NestedNameSpecifier::TypeSpec:
5562 case NestedNameSpecifier::TypeSpecWithTemplate:
5563 return Visit(QualType(NNS->getAsType(), 0));
5564 }
David Blaikie8a40f702012-01-17 06:56:22 +00005565 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005566}
5567
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005568/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00005569/// template type parameter.
5570///
5571/// This routine implements the semantics of C++ [temp.arg.type]. It
5572/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005573bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005574 TypeSourceInfo *ArgInfo) {
5575 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005576 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005577 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005578
5579 if (Arg->isVariablyModifiedType()) {
5580 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005581 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005582 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005583 }
5584
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005585 // C++03 [temp.arg.type]p2:
5586 // A local type, a type with no linkage, an unnamed type or a type
5587 // compounded from any of these types shall not be used as a
5588 // template-argument for a template type-parameter.
5589 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005590 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005591 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005592 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005593 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5594 (void)Finder.Visit(Context.getCanonicalType(Arg));
5595 }
5596
Douglas Gregord32e0282009-02-09 23:23:08 +00005597 return false;
5598}
5599
Douglas Gregor20fdef32012-04-10 17:08:25 +00005600enum NullPointerValueKind {
5601 NPV_NotNullPointer,
5602 NPV_NullPointer,
5603 NPV_Error
5604};
5605
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005606/// Determine whether the given template argument is a null pointer
Douglas Gregor20fdef32012-04-10 17:08:25 +00005607/// value of the appropriate type.
5608static NullPointerValueKind
5609isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
Reid Klecknercd016d82017-07-07 22:04:29 +00005610 QualType ParamType, Expr *Arg,
5611 Decl *Entity = nullptr) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005612 if (Arg->isValueDependent() || Arg->isTypeDependent())
5613 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005614
Reid Klecknercd016d82017-07-07 22:04:29 +00005615 // dllimport'd entities aren't constant but are available inside of template
5616 // arguments.
5617 if (Entity && Entity->hasAttr<DLLImportAttr>())
5618 return NPV_NotNullPointer;
5619
Richard Smithdb0ac552015-12-18 22:40:25 +00005620 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005621 llvm_unreachable(
5622 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005623
David Majnemer5c734ad2014-08-14 00:49:23 +00005624 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005625 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005626
Douglas Gregor20fdef32012-04-10 17:08:25 +00005627 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005628 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5629 if (ArgRV.isInvalid())
5630 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005631 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005632
Douglas Gregor20fdef32012-04-10 17:08:25 +00005633 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005634 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005635 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005636 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005637 EvalResult.HasSideEffects) {
5638 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005639
Douglas Gregor350880c2012-04-10 19:03:30 +00005640 // If our only note is the usual "invalid subexpression" note, just point
5641 // the caret at its location rather than producing an essentially
5642 // redundant note.
5643 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5644 diag::note_invalid_subexpr_in_const_expr) {
5645 DiagLoc = Notes[0].first;
5646 Notes.clear();
5647 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005648
Douglas Gregor350880c2012-04-10 19:03:30 +00005649 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5650 << Arg->getType() << Arg->getSourceRange();
5651 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5652 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005653
Douglas Gregor350880c2012-04-10 19:03:30 +00005654 S.Diag(Param->getLocation(), diag::note_template_param_here);
5655 return NPV_Error;
5656 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005657
Douglas Gregor20fdef32012-04-10 17:08:25 +00005658 // C++11 [temp.arg.nontype]p1:
5659 // - an address constant expression of type std::nullptr_t
5660 if (Arg->getType()->isNullPtrType())
5661 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005662
Douglas Gregor20fdef32012-04-10 17:08:25 +00005663 // - a constant expression that evaluates to a null pointer value (4.10); or
5664 // - a constant expression that evaluates to a null member pointer value
5665 // (4.11); or
5666 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5667 (EvalResult.Val.isMemberPointer() &&
5668 !EvalResult.Val.getMemberPointerDecl())) {
5669 // If our expression has an appropriate type, we've succeeded.
5670 bool ObjCLifetimeConversion;
5671 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5672 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5673 ObjCLifetimeConversion))
5674 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005675
Douglas Gregor20fdef32012-04-10 17:08:25 +00005676 // The types didn't match, but we know we got a null pointer; complain,
5677 // then recover as if the types were correct.
5678 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5679 << Arg->getType() << ParamType << Arg->getSourceRange();
5680 S.Diag(Param->getLocation(), diag::note_template_param_here);
5681 return NPV_NullPointer;
5682 }
5683
5684 // If we don't have a null pointer value, but we do have a NULL pointer
5685 // constant, suggest a cast to the appropriate type.
5686 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5687 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5688 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005689 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005690 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
Alp Tokerb6cc5922014-05-03 03:45:55 +00005691 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005692 S.Diag(Param->getLocation(), diag::note_template_param_here);
5693 return NPV_NullPointer;
5694 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005695
Douglas Gregor20fdef32012-04-10 17:08:25 +00005696 // FIXME: If we ever want to support general, address-constant expressions
5697 // as non-type template arguments, we should return the ExprResult here to
5698 // be interpreted by the caller.
5699 return NPV_NotNullPointer;
5700}
5701
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005702/// Checks whether the given template argument is compatible with its
David Majnemer61c39a12013-08-23 05:39:39 +00005703/// template parameter.
5704static bool CheckTemplateArgumentIsCompatibleWithParameter(
5705 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5706 Expr *Arg, QualType ArgType) {
5707 bool ObjCLifetimeConversion;
5708 if (ParamType->isPointerType() &&
5709 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5710 S.IsQualificationConversion(ArgType, ParamType, false,
5711 ObjCLifetimeConversion)) {
5712 // For pointer-to-object types, qualification conversions are
5713 // permitted.
5714 } else {
5715 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5716 if (!ParamRef->getPointeeType()->isFunctionType()) {
5717 // C++ [temp.arg.nontype]p5b3:
5718 // For a non-type template-parameter of type reference to
5719 // object, no conversions apply. The type referred to by the
5720 // reference may be more cv-qualified than the (otherwise
5721 // identical) type of the template- argument. The
5722 // template-parameter is bound directly to the
5723 // template-argument, which shall be an lvalue.
5724
5725 // FIXME: Other qualifiers?
5726 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5727 unsigned ArgQuals = ArgType.getCVRQualifiers();
5728
5729 if ((ParamQuals | ArgQuals) != ParamQuals) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005730 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005731 diag::err_template_arg_ref_bind_ignores_quals)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005732 << ParamType << Arg->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005733 S.Diag(Param->getLocation(), diag::note_template_param_here);
5734 return true;
5735 }
5736 }
5737 }
5738
5739 // At this point, the template argument refers to an object or
5740 // function with external linkage. We now need to check whether the
5741 // argument and parameter types are compatible.
5742 if (!S.Context.hasSameUnqualifiedType(ArgType,
5743 ParamType.getNonReferenceType())) {
5744 // We can't perform this conversion or binding.
5745 if (ParamType->isReferenceType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005746 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
5747 << ParamType << ArgIn->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005748 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005749 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
5750 << ArgIn->getType() << ParamType << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005751 S.Diag(Param->getLocation(), diag::note_template_param_here);
5752 return true;
5753 }
5754 }
5755
5756 return false;
5757}
5758
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005759/// Checks whether the given template argument is the address
Douglas Gregorccb07762009-02-11 19:52:55 +00005760/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005761static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005762CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5763 NonTypeTemplateParmDecl *Param,
5764 QualType ParamType,
5765 Expr *ArgIn,
5766 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005767 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005768 Expr *Arg = ArgIn;
5769 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005770
Douglas Gregorb242683d2010-04-01 18:32:35 +00005771 bool AddressTaken = false;
5772 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005773 if (S.getLangOpts().MicrosoftExt) {
5774 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5775 // dereference and address-of operators.
5776 Arg = Arg->IgnoreParenCasts();
5777
5778 bool ExtWarnMSTemplateArg = false;
5779 UnaryOperatorKind FirstOpKind;
5780 SourceLocation FirstOpLoc;
5781 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5782 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5783 if (UnOpKind == UO_Deref)
5784 ExtWarnMSTemplateArg = true;
5785 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5786 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5787 if (!AddrOpLoc.isValid()) {
5788 FirstOpKind = UnOpKind;
5789 FirstOpLoc = UnOp->getOperatorLoc();
5790 }
5791 } else
5792 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005793 }
David Majnemer61c39a12013-08-23 05:39:39 +00005794 if (FirstOpLoc.isValid()) {
5795 if (ExtWarnMSTemplateArg)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005796 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
5797 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005798
David Majnemer61c39a12013-08-23 05:39:39 +00005799 if (FirstOpKind == UO_AddrOf)
5800 AddressTaken = true;
5801 else if (Arg->getType()->isPointerType()) {
5802 // We cannot let pointers get dereferenced here, that is obviously not a
5803 // constant expression.
5804 assert(FirstOpKind == UO_Deref);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005805 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5806 << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005807 }
5808 }
5809 } else {
5810 // See through any implicit casts we added to fix the type.
5811 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005812
David Majnemer61c39a12013-08-23 05:39:39 +00005813 // C++ [temp.arg.nontype]p1:
5814 //
5815 // A template-argument for a non-type, non-template
5816 // template-parameter shall be one of: [...]
5817 //
5818 // -- the address of an object or function with external
5819 // linkage, including function templates and function
5820 // template-ids but excluding non-static class members,
5821 // expressed as & id-expression where the & is optional if
5822 // the name refers to a function or array, or if the
5823 // corresponding template-parameter is a reference; or
5824
5825 // In C++98/03 mode, give an extension warning on any extra parentheses.
5826 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5827 bool ExtraParens = false;
5828 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5829 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005830 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005831 S.getLangOpts().CPlusPlus11
5832 ? diag::warn_cxx98_compat_template_arg_extra_parens
5833 : diag::ext_template_arg_extra_parens)
5834 << Arg->getSourceRange();
5835 ExtraParens = true;
5836 }
5837
5838 Arg = Parens->getSubExpr();
5839 }
5840
5841 while (SubstNonTypeTemplateParmExpr *subst =
5842 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5843 Arg = subst->getReplacement()->IgnoreImpCasts();
5844
5845 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5846 if (UnOp->getOpcode() == UO_AddrOf) {
5847 Arg = UnOp->getSubExpr();
5848 AddressTaken = true;
5849 AddrOpLoc = UnOp->getOperatorLoc();
5850 }
5851 }
5852
5853 while (SubstNonTypeTemplateParmExpr *subst =
5854 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5855 Arg = subst->getReplacement()->IgnoreImpCasts();
5856 }
John McCall7c454bb2011-07-15 05:09:51 +00005857
David Majnemer07910d62014-06-26 07:48:46 +00005858 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5859 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5860
5861 // If our parameter has pointer type, check for a null template value.
5862 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
Reid Klecknercd016d82017-07-07 22:04:29 +00005863 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5864 Entity)) {
David Majnemer07910d62014-06-26 07:48:46 +00005865 case NPV_NullPointer:
5866 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005867 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5868 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005869 return false;
5870
5871 case NPV_Error:
5872 return true;
5873
5874 case NPV_NotNullPointer:
5875 break;
5876 }
5877 }
5878
Chandler Carruth724a8a12010-01-31 10:01:20 +00005879 // Stop checking the precise nature of the argument if it is value dependent,
5880 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005881 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005882 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005883 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005884 }
David Majnemer61c39a12013-08-23 05:39:39 +00005885
5886 if (isa<CXXUuidofExpr>(Arg)) {
5887 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5888 ArgIn, Arg, ArgType))
5889 return true;
5890
5891 Converted = TemplateArgument(ArgIn);
5892 return false;
5893 }
5894
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005895 if (!DRE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005896 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5897 << Arg->getSourceRange();
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005898 S.Diag(Param->getLocation(), diag::note_template_param_here);
5899 return true;
5900 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00005901
Douglas Gregorccb07762009-02-11 19:52:55 +00005902 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00005903 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005904 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
5905 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005906 S.Diag(Param->getLocation(), diag::note_template_param_here);
5907 return true;
5908 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005909
5910 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00005911 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005912 if (!Method->isStatic()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005913 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
5914 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005915 S.Diag(Param->getLocation(), diag::note_template_param_here);
5916 return true;
5917 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005918 }
Mike Stump11289f42009-09-09 15:08:12 +00005919
Richard Smith9380e0e2012-04-04 21:11:30 +00005920 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5921 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00005922
Richard Smith9380e0e2012-04-04 21:11:30 +00005923 // A non-type template argument must refer to an object or function.
5924 if (!Func && !Var) {
5925 // We found something, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005926 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
5927 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005928 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5929 return true;
5930 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005931
Richard Smith9380e0e2012-04-04 21:11:30 +00005932 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00005933 if (Entity->getFormalLinkage() == InternalLinkage) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005934 S.Diag(Arg->getBeginLoc(),
5935 S.getLangOpts().CPlusPlus11
5936 ? diag::warn_cxx98_compat_template_arg_object_internal
5937 : diag::ext_template_arg_object_internal)
5938 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005939 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5940 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00005941 } else if (!Entity->hasLinkage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005942 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
5943 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005944 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5945 << !Func;
5946 return true;
5947 }
5948
5949 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005950 // If the template parameter has pointer type, the function decays.
5951 if (ParamType->isPointerType() && !AddressTaken)
5952 ArgType = S.Context.getPointerType(Func->getType());
5953 else if (AddressTaken && ParamType->isReferenceType()) {
5954 // If we originally had an address-of operator, but the
5955 // parameter has reference type, complain and (if things look
5956 // like they will work) drop the address-of operator.
5957 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5958 ParamType.getNonReferenceType())) {
5959 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5960 << ParamType;
5961 S.Diag(Param->getLocation(), diag::note_template_param_here);
5962 return true;
5963 }
5964
5965 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5966 << ParamType
5967 << FixItHint::CreateRemoval(AddrOpLoc);
5968 S.Diag(Param->getLocation(), diag::note_template_param_here);
5969
5970 ArgType = Func->getType();
5971 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005972 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005973 // A value of reference type is not an object.
5974 if (Var->getType()->isReferenceType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005975 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
5976 << Var->getType() << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005977 S.Diag(Param->getLocation(), diag::note_template_param_here);
5978 return true;
5979 }
5980
Richard Smith9380e0e2012-04-04 21:11:30 +00005981 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005982 if (Var->getTLSKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005983 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
5984 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005985 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5986 return true;
5987 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005988
5989 // If the template parameter has pointer type, we must have taken
5990 // the address of this object.
5991 if (ParamType->isReferenceType()) {
5992 if (AddressTaken) {
5993 // If we originally had an address-of operator, but the
5994 // parameter has reference type, complain and (if things look
5995 // like they will work) drop the address-of operator.
5996 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5997 ParamType.getNonReferenceType())) {
5998 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5999 << ParamType;
6000 S.Diag(Param->getLocation(), diag::note_template_param_here);
6001 return true;
6002 }
6003
6004 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6005 << ParamType
6006 << FixItHint::CreateRemoval(AddrOpLoc);
6007 S.Diag(Param->getLocation(), diag::note_template_param_here);
6008
6009 ArgType = Var->getType();
6010 }
6011 } else if (!AddressTaken && ParamType->isPointerType()) {
6012 if (Var->getType()->isArrayType()) {
6013 // Array-to-pointer decay.
6014 ArgType = S.Context.getArrayDecayedType(Var->getType());
6015 } else {
6016 // If the template parameter has pointer type but the address of
6017 // this object was not taken, complain and (possibly) recover by
6018 // taking the address of the entity.
6019 ArgType = S.Context.getPointerType(Var->getType());
6020 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006021 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6022 << ParamType;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006023 S.Diag(Param->getLocation(), diag::note_template_param_here);
6024 return true;
6025 }
6026
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006027 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6028 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
Douglas Gregorb242683d2010-04-01 18:32:35 +00006029
6030 S.Diag(Param->getLocation(), diag::note_template_param_here);
6031 }
6032 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006033 }
Mike Stump11289f42009-09-09 15:08:12 +00006034
David Majnemer61c39a12013-08-23 05:39:39 +00006035 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6036 Arg, ArgType))
6037 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006038
6039 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00006040 Converted =
6041 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006042 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00006043 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006044}
6045
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006046/// Checks whether the given template argument is a pointer to
Douglas Gregorccb07762009-02-11 19:52:55 +00006047/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00006048static bool CheckTemplateArgumentPointerToMember(Sema &S,
6049 NonTypeTemplateParmDecl *Param,
6050 QualType ParamType,
6051 Expr *&ResultArg,
6052 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006053 bool Invalid = false;
6054
Douglas Gregor20fdef32012-04-10 17:08:25 +00006055 Expr *Arg = ResultArg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006056 bool ObjCLifetimeConversion;
Douglas Gregorccb07762009-02-11 19:52:55 +00006057
6058 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006059 //
Douglas Gregorccb07762009-02-11 19:52:55 +00006060 // A template-argument for a non-type, non-template
6061 // template-parameter shall be one of: [...]
6062 //
6063 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00006064 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00006065
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006066 // In C++98/03 mode, give an extension warning on any extra parentheses.
6067 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6068 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006069 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00006070 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006071 S.Diag(Arg->getBeginLoc(),
6072 S.getLangOpts().CPlusPlus11
6073 ? diag::warn_cxx98_compat_template_arg_extra_parens
6074 : diag::ext_template_arg_extra_parens)
6075 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006076 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00006077 }
6078
6079 Arg = Parens->getSubExpr();
6080 }
6081
John McCall7c454bb2011-07-15 05:09:51 +00006082 while (SubstNonTypeTemplateParmExpr *subst =
6083 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6084 Arg = subst->getReplacement()->IgnoreImpCasts();
6085
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006086 // A pointer-to-member constant written &Class::member.
6087 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00006088 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006089 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6090 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00006091 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006093 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006094 // A constant of pointer-to-member type.
6095 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006096 ValueDecl *VD = DRE->getDecl();
6097 if (VD->getType()->isMemberPointerType()) {
6098 if (isa<NonTypeTemplateParmDecl>(VD)) {
6099 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6100 Converted = TemplateArgument(Arg);
6101 } else {
6102 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6103 Converted = TemplateArgument(VD, ParamType);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006104 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00006105 return Invalid;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006106 }
6107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006108
Craig Topperc3ec1492014-05-26 06:22:03 +00006109 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006111
Reid Klecknercd016d82017-07-07 22:04:29 +00006112 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6113
6114 // Check for a null pointer value.
6115 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6116 Entity)) {
6117 case NPV_Error:
6118 return true;
6119 case NPV_NullPointer:
6120 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6121 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6122 /*isNullPtr*/true);
6123 return false;
6124 case NPV_NotNullPointer:
6125 break;
6126 }
6127
6128 if (S.IsQualificationConversion(ResultArg->getType(),
6129 ParamType.getNonReferenceType(), false,
6130 ObjCLifetimeConversion)) {
6131 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6132 ResultArg->getValueKind())
6133 .get();
6134 } else if (!S.Context.hasSameUnqualifiedType(
6135 ResultArg->getType(), ParamType.getNonReferenceType())) {
6136 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006137 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
Reid Klecknercd016d82017-07-07 22:04:29 +00006138 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6139 S.Diag(Param->getLocation(), diag::note_template_param_here);
6140 return true;
6141 }
6142
Douglas Gregorccb07762009-02-11 19:52:55 +00006143 if (!DRE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006144 return S.Diag(Arg->getBeginLoc(),
Douglas Gregor20fdef32012-04-10 17:08:25 +00006145 diag::err_template_arg_not_pointer_to_member_form)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006146 << Arg->getSourceRange();
Douglas Gregorccb07762009-02-11 19:52:55 +00006147
David Majnemer3ac84e62013-10-22 21:56:38 +00006148 if (isa<FieldDecl>(DRE->getDecl()) ||
6149 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6150 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006151 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00006152 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00006153 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6154 "Only non-static member pointers can make it here");
6155
6156 // Okay: this is the address of a non-static member, and therefore
6157 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00006158 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00006159 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00006160 } else {
6161 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00006162 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00006163 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006164 return Invalid;
6165 }
6166
6167 // We found something else, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006168 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6169 << Arg->getSourceRange();
Douglas Gregor20fdef32012-04-10 17:08:25 +00006170 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00006171 return true;
6172}
6173
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006174/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006175/// non-type template parameter.
6176///
Douglas Gregor463421d2009-03-03 04:44:36 +00006177/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00006178/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00006179/// returns the converted template argument. \p ParamType is the
6180/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00006181ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00006182 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00006183 TemplateArgument &Converted,
6184 CheckTemplateArgumentKind CTAK) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006185 SourceLocation StartLoc = Arg->getBeginLoc();
Douglas Gregorc40290e2009-03-09 23:48:35 +00006186
Richard Smith5f274382016-09-28 23:55:27 +00006187 // If the parameter type somehow involves auto, deduce the type now.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006188 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
Richard Smith4ae5ec82017-02-22 20:01:55 +00006189 // During template argument deduction, we allow 'decltype(auto)' to
6190 // match an arbitrary dependent argument.
6191 // FIXME: The language rules don't say what happens in this case.
6192 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6193 // expression is merely instantiation-dependent; is this enough?
6194 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6195 auto *AT = dyn_cast<AutoType>(ParamType);
6196 if (AT && AT->isDecltypeAuto()) {
6197 Converted = TemplateArgument(Arg);
6198 return Arg;
6199 }
6200 }
6201
Richard Smith87d263e2016-12-25 08:05:23 +00006202 // When checking a deduced template argument, deduce from its type even if
6203 // the type is dependent, in order to check the types of non-type template
6204 // arguments line up properly in partial ordering.
6205 Optional<unsigned> Depth;
6206 if (CTAK != CTAK_Specified)
6207 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00006208 if (DeduceAutoType(
6209 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00006210 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00006211 Diag(Arg->getExprLoc(),
6212 diag::err_non_type_template_parm_type_deduction_failure)
6213 << Param->getDeclName() << Param->getType() << Arg->getType()
6214 << Arg->getSourceRange();
6215 Diag(Param->getLocation(), diag::note_template_param_here);
6216 return ExprError();
6217 }
6218 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6219 // an error. The error message normally references the parameter
6220 // declaration, but here we'll pass the argument location because that's
6221 // where the parameter type is deduced.
6222 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6223 if (ParamType.isNull()) {
6224 Diag(Param->getLocation(), diag::note_template_param_here);
6225 return ExprError();
6226 }
6227 }
6228
Richard Smithd663fdd2014-12-17 20:42:37 +00006229 // We should have already dropped all cv-qualifiers by now.
6230 assert(!ParamType.hasQualifiers() &&
6231 "non-type template parameter type cannot be qualified");
6232
6233 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00006234 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00006235 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00006236 // FIXME: If either type is dependent, we skip the check. This isn't
6237 // correct, since during deduction we're supposed to have replaced each
6238 // template parameter with some unique (non-dependent) placeholder.
6239 // FIXME: If the argument type contains 'auto', we carry on and fail the
6240 // type check in order to force specific types to be more specialized than
6241 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6242 // work.
6243 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6244 !Arg->getType()->getContainedAutoType()) {
6245 Converted = TemplateArgument(Arg);
6246 return Arg;
6247 }
6248 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6249 // we should actually be checking the type of the template argument in P,
6250 // not the type of the template argument deduced from A, against the
6251 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00006252 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00006253 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00006254 << ParamType.getUnqualifiedType();
6255 Diag(Param->getLocation(), diag::note_template_param_here);
6256 return ExprError();
6257 }
6258
Richard Smith87d263e2016-12-25 08:05:23 +00006259 // If either the parameter has a dependent type or the argument is
6260 // type-dependent, there's nothing we can check now.
6261 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6262 // FIXME: Produce a cloned, canonical expression?
6263 Converted = TemplateArgument(Arg);
6264 return Arg;
6265 }
6266
Richard Smithe5945872017-01-06 22:52:53 +00006267 // The initialization of the parameter from the argument is
6268 // a constant-evaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006269 EnterExpressionEvaluationContext ConstantEvaluated(
6270 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smithe5945872017-01-06 22:52:53 +00006271
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006272 if (getLangOpts().CPlusPlus17) {
6273 // C++17 [temp.arg.nontype]p1:
Richard Smith410cc892014-11-26 03:26:53 +00006274 // A template-argument for a non-type template parameter shall be
6275 // a converted constant expression of the type of the template-parameter.
6276 APValue Value;
6277 ExprResult ArgResult = CheckConvertedConstantExpression(
6278 Arg, ParamType, Value, CCEK_TemplateArg);
6279 if (ArgResult.isInvalid())
6280 return ExprError();
6281
Richard Smith52e624f2016-12-21 21:42:57 +00006282 // For a value-dependent argument, CheckConvertedConstantExpression is
6283 // permitted (and expected) to be unable to determine a value.
6284 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00006285 Converted = TemplateArgument(ArgResult.get());
6286 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00006287 }
6288
Richard Smithd663fdd2014-12-17 20:42:37 +00006289 QualType CanonParamType = Context.getCanonicalType(ParamType);
6290
Richard Smith410cc892014-11-26 03:26:53 +00006291 // Convert the APValue to a TemplateArgument.
6292 switch (Value.getKind()) {
6293 case APValue::Uninitialized:
6294 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006295 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006296 break;
6297 case APValue::Int:
6298 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006299 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00006300 break;
6301 case APValue::MemberPointer: {
6302 assert(ParamType->isMemberPointerType());
6303
6304 // FIXME: We need TemplateArgument representation and mangling for these.
6305 if (!Value.getMemberPointerPath().empty()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006306 Diag(Arg->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00006307 diag::err_template_arg_member_ptr_base_derived_not_supported)
6308 << Value.getMemberPointerDecl() << ParamType
6309 << Arg->getSourceRange();
6310 return ExprError();
6311 }
6312
6313 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00006314 Converted = VD ? TemplateArgument(VD, CanonParamType)
6315 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006316 break;
6317 }
6318 case APValue::LValue: {
6319 // For a non-type template-parameter of pointer or reference type,
6320 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00006321 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6322 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00006323 // -- a temporary object
6324 // -- a string literal
6325 // -- the result of a typeid expression, or
Eric Christopher0d2c56a2017-03-31 01:45:39 +00006326 // -- a predefined __func__ variable
Richard Smith410cc892014-11-26 03:26:53 +00006327 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6328 if (isa<CXXUuidofExpr>(E)) {
Bill Wendlingff573072019-01-27 07:24:03 +00006329 Converted = TemplateArgument(ArgResult.get()->IgnoreImpCasts());
Richard Smith410cc892014-11-26 03:26:53 +00006330 break;
6331 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006332 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6333 << Arg->getSourceRange();
Richard Smith410cc892014-11-26 03:26:53 +00006334 return ExprError();
6335 }
6336 auto *VD = const_cast<ValueDecl *>(
6337 Value.getLValueBase().dyn_cast<const ValueDecl *>());
6338 // -- a subobject
6339 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6340 VD && VD->getType()->isArrayType() &&
6341 Value.getLValuePath()[0].ArrayIndex == 0 &&
6342 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6343 // Per defect report (no number yet):
6344 // ... other than a pointer to the first element of a complete array
6345 // object.
6346 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6347 Value.isLValueOnePastTheEnd()) {
6348 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6349 << Value.getAsString(Context, ParamType);
6350 return ExprError();
6351 }
Richard Smithd663fdd2014-12-17 20:42:37 +00006352 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00006353 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00006354 assert((!VD || !ParamType->isNullPtrType()) &&
6355 "non-null value of type nullptr_t?");
6356 Converted = VD ? TemplateArgument(VD, CanonParamType)
6357 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006358 break;
6359 }
6360 case APValue::AddrLabelDiff:
6361 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
Leonard Chan86285d22019-01-16 18:53:05 +00006362 case APValue::FixedPoint:
Richard Smith410cc892014-11-26 03:26:53 +00006363 case APValue::Float:
6364 case APValue::ComplexInt:
6365 case APValue::ComplexFloat:
6366 case APValue::Vector:
6367 case APValue::Array:
6368 case APValue::Struct:
6369 case APValue::Union:
6370 llvm_unreachable("invalid kind for template argument");
6371 }
6372
6373 return ArgResult.get();
6374 }
6375
Douglas Gregor86560402009-02-10 23:36:10 +00006376 // C++ [temp.arg.nontype]p5:
6377 // The following conversions are performed on each expression used
6378 // as a non-type template-argument. If a non-type
6379 // template-argument cannot be converted to the type of the
6380 // corresponding template-parameter then the program is
6381 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00006382 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00006383 // C++11:
6384 // -- for a non-type template-parameter of integral or
6385 // enumeration type, conversions permitted in a converted
6386 // constant expression are applied.
6387 //
6388 // C++98:
6389 // -- for a non-type template-parameter of integral or
6390 // enumeration type, integral promotions (4.5) and integral
6391 // conversions (4.7) are applied.
6392
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006393 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00006394 // C++ [temp.arg.nontype]p1:
6395 // A template-argument for a non-type, non-template template-parameter
6396 // shall be one of:
6397 //
6398 // -- for a non-type template-parameter of integral or enumeration
6399 // type, a converted constant expression of the type of the
6400 // template-parameter; or
6401 llvm::APSInt Value;
6402 ExprResult ArgResult =
6403 CheckConvertedConstantExpression(Arg, ParamType, Value,
6404 CCEK_TemplateArg);
6405 if (ArgResult.isInvalid())
6406 return ExprError();
6407
Richard Smith01bfa682016-12-27 02:02:09 +00006408 // We can't check arbitrary value-dependent arguments.
6409 if (ArgResult.get()->isValueDependent()) {
6410 Converted = TemplateArgument(ArgResult.get());
6411 return ArgResult;
6412 }
6413
Richard Smithf8379a02012-01-18 23:55:52 +00006414 // Widen the argument value to sizeof(parameter type). This is almost
6415 // always a no-op, except when the parameter type is bool. In
6416 // that case, this may extend the argument from 1 bit to 8 bits.
6417 QualType IntegerType = ParamType;
6418 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6419 IntegerType = Enum->getDecl()->getIntegerType();
6420 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6421
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006422 Converted = TemplateArgument(Context, Value,
6423 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00006424 return ArgResult;
6425 }
6426
Richard Smith08b12f12011-10-27 22:11:44 +00006427 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6428 if (ArgResult.isInvalid())
6429 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006430 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00006431
6432 QualType ArgType = Arg->getType();
6433
Douglas Gregor86560402009-02-10 23:36:10 +00006434 // C++ [temp.arg.nontype]p1:
6435 // A template-argument for a non-type, non-template
6436 // template-parameter shall be one of:
6437 //
6438 // -- an integral constant-expression of integral or enumeration
6439 // type; or
6440 // -- the name of a non-type template-parameter; or
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006441 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00006442 if (!ArgType->isIntegralOrEnumerationType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006443 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6444 << ArgType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006445 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006446 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00006447 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00006448 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6449 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006450
Douglas Gregore2b37442012-05-04 22:38:52 +00006451 public:
6452 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00006453
6454 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6455 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00006456 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6457 }
6458 } Diagnoser(ArgType);
6459
6460 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006461 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00006462 if (!Arg)
6463 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006464 }
6465
Richard Smithd663fdd2014-12-17 20:42:37 +00006466 // From here on out, all we care about is the unqualified form
6467 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006468 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00006469
6470 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00006471 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00006472 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00006473 } else if (ParamType->isBooleanType()) {
6474 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006475 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006476 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6477 !ParamType->isEnumeralType()) {
6478 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006479 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006480 } else {
6481 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006482 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6483 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006484 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006485 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006486 }
6487
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006488 // Add the value of this argument to the list of converted
6489 // arguments. We use the bitwidth and signedness of the template
6490 // parameter.
6491 if (Arg->isValueDependent()) {
6492 // The argument is value-dependent. Create a new
6493 // TemplateArgument with the converted expression.
6494 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006495 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006496 }
6497
Douglas Gregor52aba872009-03-14 00:20:21 +00006498 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00006499 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00006500 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00006501
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006502 if (ParamType->isBooleanType()) {
6503 // Value must be zero or one.
6504 Value = Value != 0;
6505 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6506 if (Value.getBitWidth() != AllowedBits)
6507 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006508 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006509 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006510 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006511
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006512 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006513 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006514 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006515 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006516 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006517 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00006518
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006519 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006520 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006521 && (OldValue.isSigned() && OldValue.isNegative())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006522 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6523 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6524 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006525 Diag(Param->getLocation(), diag::note_template_param_here);
6526 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006527
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006528 // Complain if we overflowed the template parameter's type.
6529 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006530 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006531 RequiredBits = OldValue.getActiveBits();
6532 else if (OldValue.isUnsigned())
6533 RequiredBits = OldValue.getActiveBits() + 1;
6534 else
6535 RequiredBits = OldValue.getMinSignedBits();
6536 if (RequiredBits > AllowedBits) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006537 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6538 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6539 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006540 Diag(Param->getLocation(), diag::note_template_param_here);
6541 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006542 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006543
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006544 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006545 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006546 ? Context.getCanonicalType(ParamType)
6547 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006548 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006549 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006550
Richard Smith08b12f12011-10-27 22:11:44 +00006551 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006552 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6553
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006554 // Handle pointer-to-function, reference-to-function, and
6555 // pointer-to-member-function all in (roughly) the same way.
6556 if (// -- For a non-type template-parameter of type pointer to
6557 // function, only the function-to-pointer conversion (4.3) is
6558 // applied. If the template-argument represents a set of
6559 // overloaded functions (or a pointer to such), the matching
6560 // function is selected from the set (13.4).
6561 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006562 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006563 // -- For a non-type template-parameter of type reference to
6564 // function, no conversions apply. If the template-argument
6565 // represents a set of overloaded functions, the matching
6566 // function is selected from the set (13.4).
6567 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006568 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006569 // -- For a non-type template-parameter of type pointer to
6570 // member function, no conversions apply. If the
6571 // template-argument represents a set of overloaded member
6572 // functions, the matching member function is selected from
6573 // the set (13.4).
6574 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006575 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006576 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006577
Douglas Gregor064fdb22010-04-14 23:11:21 +00006578 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006579 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006580 true,
6581 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006582 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006583 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006584
6585 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6586 ArgType = Arg->getType();
6587 } else
John Wiegley01296292011-04-08 18:41:53 +00006588 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006590
John Wiegley01296292011-04-08 18:41:53 +00006591 if (!ParamType->isMemberPointerType()) {
6592 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6593 ParamType,
6594 Arg, Converted))
6595 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006596 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006597 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006598
Douglas Gregor20fdef32012-04-10 17:08:25 +00006599 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6600 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006601 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006602 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006603 }
6604
Chris Lattner696197c2009-02-20 21:37:53 +00006605 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006606 // -- for a non-type template-parameter of type pointer to
6607 // object, qualification conversions (4.4) and the
6608 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006609 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006610 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006611 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006612
John Wiegley01296292011-04-08 18:41:53 +00006613 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6614 ParamType,
6615 Arg, Converted))
6616 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006617 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006618 }
Mike Stump11289f42009-09-09 15:08:12 +00006619
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006620 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006621 // -- For a non-type template-parameter of type reference to
6622 // object, no conversions apply. The type referred to by the
6623 // reference may be more cv-qualified than the (otherwise
6624 // identical) type of the template-argument. The
6625 // template-parameter is bound directly to the
6626 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006627 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006628 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006629
Douglas Gregor064fdb22010-04-14 23:11:21 +00006630 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006631 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6632 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006633 true,
6634 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006635 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006636 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006637
6638 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6639 ArgType = Arg->getType();
6640 } else
John Wiegley01296292011-04-08 18:41:53 +00006641 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006642 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006643
John Wiegley01296292011-04-08 18:41:53 +00006644 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6645 ParamType,
6646 Arg, Converted))
6647 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006648 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006649 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006650
Douglas Gregor20fdef32012-04-10 17:08:25 +00006651 // Deal with parameters of type std::nullptr_t.
6652 if (ParamType->isNullPtrType()) {
6653 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6654 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006655 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006656 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006657
Douglas Gregor20fdef32012-04-10 17:08:25 +00006658 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6659 case NPV_NotNullPointer:
6660 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6661 << Arg->getType() << ParamType;
6662 Diag(Param->getLocation(), diag::note_template_param_here);
6663 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006664
Douglas Gregor20fdef32012-04-10 17:08:25 +00006665 case NPV_Error:
6666 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006667
Douglas Gregor20fdef32012-04-10 17:08:25 +00006668 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006669 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006670 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6671 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006672 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006673 }
6674 }
6675
Douglas Gregor0e558532009-02-11 16:16:59 +00006676 // -- For a non-type template-parameter of type pointer to data
6677 // member, qualification conversions (4.4) are applied.
6678 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6679
Douglas Gregor20fdef32012-04-10 17:08:25 +00006680 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6681 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006682 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006683 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006684}
6685
Richard Smith26b86ea2016-12-31 21:41:23 +00006686static void DiagnoseTemplateParameterListArityMismatch(
6687 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6688 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6689
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006690/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006691/// template template parameter.
6692///
6693/// This routine implements the semantics of C++ [temp.arg.template].
6694/// It returns true if an error occurred, and false otherwise.
Richard Smith5d331022018-03-08 01:07:33 +00006695bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6696 TemplateArgumentLoc &Arg) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006697 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006698 TemplateDecl *Template = Name.getAsTemplateDecl();
6699 if (!Template) {
6700 // Any dependent template name is fine.
6701 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6702 return false;
6703 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006704
Richard Smith26b86ea2016-12-31 21:41:23 +00006705 if (Template->isInvalidDecl())
6706 return true;
6707
Richard Smith3f1b5d02011-05-05 21:57:07 +00006708 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006709 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006710 // the name of a class template or an alias template, expressed as an
6711 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006712 // primary class templates are considered when matching the
6713 // template template argument with the corresponding parameter;
6714 // partial specializations are not considered even if their
6715 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006716 //
6717 // Note that we also allow template template parameters here, which
6718 // will happen when we are dealing with, e.g., class template
6719 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006720 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006721 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006722 !isa<TypeAliasTemplateDecl>(Template) &&
6723 !isa<BuiltinTemplateDecl>(Template)) {
6724 assert(isa<FunctionTemplateDecl>(Template) &&
6725 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006726 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006727 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6728 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006729 }
6730
Richard Smith26b86ea2016-12-31 21:41:23 +00006731 // C++1z [temp.arg.template]p3: (DR 150)
6732 // A template-argument matches a template template-parameter P when P
6733 // is at least as specialized as the template-argument A.
6734 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6735 // Quick check for the common case:
6736 // If P contains a parameter pack, then A [...] matches P if each of A's
6737 // template parameters matches the corresponding template parameter in
6738 // the template-parameter-list of P.
6739 if (TemplateParameterListsAreEqual(
6740 Template->getTemplateParameters(), Params, false,
6741 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6742 return false;
6743
6744 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6745 Arg.getLocation()))
6746 return false;
6747 // FIXME: Produce better diagnostics for deduction failures.
6748 }
6749
Douglas Gregor85e0f662009-02-10 00:24:35 +00006750 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006751 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006752 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006753 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006754 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006755}
6756
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006757/// Given a non-type template argument that refers to a
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006758/// declaration and the type of its corresponding non-type template
6759/// parameter, produce an expression that properly refers to that
6760/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006761ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006762Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6763 QualType ParamType,
6764 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006765 // C++ [temp.param]p8:
6766 //
6767 // A non-type template-parameter of type "array of T" or
6768 // "function returning T" is adjusted to be of type "pointer to
6769 // T" or "pointer to function returning T", respectively.
6770 if (ParamType->isArrayType())
6771 ParamType = Context.getArrayDecayedType(ParamType);
6772 else if (ParamType->isFunctionType())
6773 ParamType = Context.getPointerType(ParamType);
6774
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006775 // For a NULL non-type template argument, return nullptr casted to the
6776 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006777 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006778 return ImpCastExprToType(
6779 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6780 ParamType,
6781 ParamType->getAs<MemberPointerType>()
6782 ? CK_NullToMemberPointer
6783 : CK_NullToPointer);
6784 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006785 assert(Arg.getKind() == TemplateArgument::Declaration &&
6786 "Only declaration template arguments permitted here");
6787
George Burgess IV00f70bd2018-03-01 05:43:23 +00006788 ValueDecl *VD = Arg.getAsDecl();
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006789
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006790 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006791 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6792 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006793 // If the value is a class member, we might have a pointer-to-member.
6794 // Determine whether the non-type template template parameter is of
6795 // pointer-to-member type. If so, we need to build an appropriate
6796 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6797 // would refer to the member itself.
6798 if (ParamType->isMemberPointerType()) {
6799 QualType ClassType
6800 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6801 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006802 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006803 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006804 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006805 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006806
6807 // The actual value-ness of this is unimportant, but for
6808 // internal consistency's sake, references to instance methods
6809 // are r-values.
6810 ExprValueKind VK = VK_LValue;
6811 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6812 VK = VK_RValue;
6813
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006814 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006815 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006816 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006817 Loc,
6818 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006819 if (RefExpr.isInvalid())
6820 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006821
John McCalle3027922010-08-25 11:45:40 +00006822 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006823
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006824 // We might need to perform a trailing qualification conversion, since
6825 // the element type on the parameter could be more qualified than the
6826 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006827 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006828 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006829 ParamType.getUnqualifiedType(), false,
6830 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006831 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006832
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006833 assert(!RefExpr.isInvalid() &&
6834 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006835 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006836 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006837 }
6838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006839
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006840 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006841
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006842 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006843 // When the non-type template parameter is a pointer, take the
6844 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006845 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006846 if (RefExpr.isInvalid())
6847 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006848
Richard Smithfc6fca12017-01-28 00:38:35 +00006849 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6850 (T->isFunctionType() || T->isArrayType())) {
6851 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006852 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006853 if (RefExpr.isInvalid())
6854 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006855
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006856 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006857 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006858
Douglas Gregorb242683d2010-04-01 18:32:35 +00006859 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006860 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006861 }
6862
John McCall7decc9e2010-11-18 06:31:45 +00006863 ExprValueKind VK = VK_RValue;
6864
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006865 // If the non-type template parameter has reference type, qualify the
6866 // resulting declaration reference with the extra qualifiers on the
6867 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006868 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6869 VK = VK_LValue;
6870 T = Context.getQualifiedType(T,
6871 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006872 } else if (isa<FunctionDecl>(VD)) {
6873 // References to functions are always lvalues.
6874 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006875 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006876
John McCall7decc9e2010-11-18 06:31:45 +00006877 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006878}
6879
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006880/// Construct a new expression that refers to the given
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006881/// integral template argument with the given source-location
6882/// information.
6883///
6884/// This routine takes care of the mapping from an integral template
6885/// argument (which may have any integral type) to the appropriate
6886/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006887ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006888Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6889 SourceLocation Loc) {
6890 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006891 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006892 QualType OrigT = Arg.getIntegralType();
6893
6894 // If this is an enum type that we're instantiating, we need to use an integer
6895 // type the same size as the enumerator. We don't want to build an
6896 // IntegerLiteral with enum type. The integer type of an enum type can be of
6897 // any integral type with C++11 enum classes, make sure we create the right
6898 // type of literal for it.
6899 QualType T = OrigT;
6900 if (const EnumType *ET = OrigT->getAs<EnumType>())
6901 T = ET->getDecl()->getIntegerType();
6902
6903 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006904 if (T->isAnyCharacterType()) {
6905 CharacterLiteral::CharacterKind Kind;
6906 if (T->isWideCharType())
6907 Kind = CharacterLiteral::Wide;
Richard Smith3a8244d2018-05-01 05:02:45 +00006908 else if (T->isChar8Type() && getLangOpts().Char8)
6909 Kind = CharacterLiteral::UTF8;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006910 else if (T->isChar16Type())
6911 Kind = CharacterLiteral::UTF16;
6912 else if (T->isChar32Type())
6913 Kind = CharacterLiteral::UTF32;
6914 else
6915 Kind = CharacterLiteral::Ascii;
6916
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006917 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6918 Kind, T, Loc);
6919 } else if (T->isBooleanType()) {
6920 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6921 T, Loc);
6922 } else if (T->isNullPtrType()) {
6923 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6924 } else {
6925 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00006926 }
6927
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006928 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00006929 // FIXME: This is a hack. We need a better way to handle substituted
6930 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00006931 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6932 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006933 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00006934 Loc, Loc);
6935 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006936
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006937 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006938}
6939
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006940/// Match two template parameters within template parameter lists.
Douglas Gregor641040a2011-01-12 23:45:44 +00006941static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6942 bool Complain,
6943 Sema::TemplateParameterListEqualKind Kind,
6944 SourceLocation TemplateArgLoc) {
6945 // Check the actual kind (type, non-type, template).
6946 if (Old->getKind() != New->getKind()) {
6947 if (Complain) {
6948 unsigned NextDiag = diag::err_template_param_different_kind;
6949 if (TemplateArgLoc.isValid()) {
6950 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6951 NextDiag = diag::note_template_param_different_kind;
6952 }
6953 S.Diag(New->getLocation(), NextDiag)
6954 << (Kind != Sema::TPL_TemplateMatch);
6955 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6956 << (Kind != Sema::TPL_TemplateMatch);
6957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006958
Douglas Gregor641040a2011-01-12 23:45:44 +00006959 return false;
6960 }
6961
Richard Smith26b86ea2016-12-31 21:41:23 +00006962 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006963 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006964 // template template parameter, the template template parameter can have
6965 // a parameter pack where the template template argument does not.
6966 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6967 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6968 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006969 if (Complain) {
6970 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6971 if (TemplateArgLoc.isValid()) {
6972 S.Diag(TemplateArgLoc,
6973 diag::err_template_arg_template_params_mismatch);
6974 NextDiag = diag::note_template_parameter_pack_non_pack;
6975 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006976
Douglas Gregor641040a2011-01-12 23:45:44 +00006977 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6978 : isa<NonTypeTemplateParmDecl>(New)? 1
6979 : 2;
6980 S.Diag(New->getLocation(), NextDiag)
6981 << ParamKind << New->isParameterPack();
6982 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6983 << ParamKind << Old->isParameterPack();
6984 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006985
Douglas Gregor641040a2011-01-12 23:45:44 +00006986 return false;
6987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006988
Douglas Gregor641040a2011-01-12 23:45:44 +00006989 // For non-type template parameters, check the type of the parameter.
6990 if (NonTypeTemplateParmDecl *OldNTTP
6991 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6992 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006993
Douglas Gregor641040a2011-01-12 23:45:44 +00006994 // If we are matching a template template argument to a template
6995 // template parameter and one of the non-type template parameter types
Richard Smith13894182017-04-13 21:37:24 +00006996 // is dependent, then we must wait until template instantiation time
6997 // to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00006998 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith13894182017-04-13 21:37:24 +00006999 (OldNTTP->getType()->isDependentType() ||
7000 NewNTTP->getType()->isDependentType()))
Douglas Gregor641040a2011-01-12 23:45:44 +00007001 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007002
Douglas Gregor641040a2011-01-12 23:45:44 +00007003 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
7004 if (Complain) {
7005 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7006 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007007 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00007008 diag::err_template_arg_template_params_mismatch);
7009 NextDiag = diag::note_template_nontype_parm_different_type;
7010 }
7011 S.Diag(NewNTTP->getLocation(), NextDiag)
7012 << NewNTTP->getType()
7013 << (Kind != Sema::TPL_TemplateMatch);
7014 S.Diag(OldNTTP->getLocation(),
7015 diag::note_template_nontype_parm_prev_declaration)
7016 << OldNTTP->getType();
7017 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007018
Douglas Gregor641040a2011-01-12 23:45:44 +00007019 return false;
7020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007021
Douglas Gregor641040a2011-01-12 23:45:44 +00007022 return true;
7023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007024
Douglas Gregor641040a2011-01-12 23:45:44 +00007025 // For template template parameters, check the template parameter types.
7026 // The template parameter lists of template template
7027 // parameters must agree.
7028 if (TemplateTemplateParmDecl *OldTTP
7029 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007030 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00007031 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7032 OldTTP->getTemplateParameters(),
7033 Complain,
7034 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007035 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00007036 : Kind),
7037 TemplateArgLoc);
7038 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007039
Douglas Gregor641040a2011-01-12 23:45:44 +00007040 return true;
7041}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007042
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007043/// Diagnose a known arity mismatch when comparing template argument
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007044/// lists.
7045static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007046void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007047 TemplateParameterList *New,
7048 TemplateParameterList *Old,
7049 Sema::TemplateParameterListEqualKind Kind,
7050 SourceLocation TemplateArgLoc) {
7051 unsigned NextDiag = diag::err_template_param_list_different_arity;
7052 if (TemplateArgLoc.isValid()) {
7053 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7054 NextDiag = diag::note_template_param_list_different_arity;
7055 }
7056 S.Diag(New->getTemplateLoc(), NextDiag)
7057 << (New->size() > Old->size())
7058 << (Kind != Sema::TPL_TemplateMatch)
7059 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7060 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7061 << (Kind != Sema::TPL_TemplateMatch)
7062 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7063}
7064
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007065/// Determine whether the given template parameter lists are
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007066/// equivalent.
7067///
Mike Stump11289f42009-09-09 15:08:12 +00007068/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007069/// source code as part of a new template declaration.
7070///
7071/// \param Old The old template parameter list, typically found via
7072/// name lookup of the template declared with this template parameter
7073/// list.
7074///
7075/// \param Complain If true, this routine will produce a diagnostic if
7076/// the template parameter lists are not equivalent.
7077///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007078/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00007079///
7080/// \param TemplateArgLoc If this source location is valid, then we
7081/// are actually checking the template parameter list of a template
7082/// argument (New) against the template parameter list of its
7083/// corresponding template template parameter (Old). We produce
7084/// slightly different diagnostics in this scenario.
7085///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007086/// \returns True if the template parameter lists are equal, false
7087/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00007088bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007089Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7090 TemplateParameterList *Old,
7091 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007092 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00007093 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007094 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7095 if (Complain)
7096 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7097 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007098
7099 return false;
7100 }
7101
Douglas Gregor641040a2011-01-12 23:45:44 +00007102 // C++0x [temp.arg.template]p3:
7103 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007104 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00007105 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007106 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007107 // template-parameter-list of P. [...]
7108 TemplateParameterList::iterator NewParm = New->begin();
7109 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007110 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007111 OldParmEnd = Old->end();
7112 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00007113 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7114 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007115 if (NewParm == NewParmEnd) {
7116 if (Complain)
7117 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7118 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007119
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007120 return false;
7121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007122
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007123 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7124 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007125 return false;
7126
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007127 ++NewParm;
7128 continue;
7129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007130
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007131 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007132 // [...] When P's template- parameter-list contains a template parameter
7133 // pack (14.5.3), the template parameter pack will match zero or more
7134 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007135 // template-parameter-list of A with the same type and form as the
7136 // template parameter pack in P (ignoring whether those template
7137 // parameters are template parameter packs).
7138 for (; NewParm != NewParmEnd; ++NewParm) {
7139 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7140 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007141 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007142 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007143 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007144
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007145 // Make sure we exhausted all of the arguments.
7146 if (NewParm != NewParmEnd) {
7147 if (Complain)
7148 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7149 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007150
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007151 return false;
7152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007153
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007154 return true;
7155}
7156
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007157/// Check whether a template can be declared within this scope.
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007158///
7159/// If the template declaration is valid in this scope, returns
7160/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00007161bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007162Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00007163 if (!S)
7164 return false;
7165
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007166 // Find the nearest enclosing declaration scope.
7167 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7168 (S->getFlags() & Scope::TemplateParamScope) != 0)
7169 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00007170
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007171 // C++ [temp]p4:
7172 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007173 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00007174 if (Ctx && Ctx->isExternCContext()) {
7175 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7176 << TemplateParams->getSourceRange();
7177 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7178 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7179 return true;
7180 }
Richard Smith8df390f2016-09-08 23:14:54 +00007181 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007182
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007183 // C++ [temp]p2:
7184 // A template-declaration can appear only as a namespace scope or
7185 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00007186 if (Ctx) {
7187 if (Ctx->isFileContext())
7188 return false;
7189 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7190 // C++ [temp.mem]p2:
7191 // A local class shall not have member templates.
7192 if (RD->isLocalClass())
7193 return Diag(TemplateParams->getTemplateLoc(),
7194 diag::err_template_inside_local_class)
7195 << TemplateParams->getSourceRange();
7196 else
7197 return false;
7198 }
7199 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007200
Mike Stump11289f42009-09-09 15:08:12 +00007201 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007202 diag::err_template_outside_namespace_or_class_scope)
7203 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007204}
Douglas Gregor67a65642009-02-17 23:15:12 +00007205
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007206/// Determine what kind of template specialization the given declaration
Douglas Gregor54888652009-10-07 00:13:32 +00007207/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007208static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00007209 if (!D)
7210 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007211
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007212 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7213 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00007214 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7215 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007216 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7217 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007218
Douglas Gregor54888652009-10-07 00:13:32 +00007219 return TSK_Undeclared;
7220}
7221
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007222/// Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007223/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00007224///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007225/// This routine determines whether a template specialization can be declared
7226/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00007227///
7228/// \param S the semantic analysis object for which this check is being
7229/// performed.
7230///
7231/// \param Specialized the entity being specialized or instantiated, which
7232/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007233/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00007234/// member class).
7235///
7236/// \param PrevDecl the previous declaration of this entity, if any.
7237///
7238/// \param Loc the location of the explicit specialization or instantiation of
7239/// this entity.
7240///
7241/// \param IsPartialSpecialization whether this is a partial specialization of
7242/// a class template.
7243///
Douglas Gregor54888652009-10-07 00:13:32 +00007244/// \returns true if there was an error that we cannot recover from, false
7245/// otherwise.
7246static bool CheckTemplateSpecializationScope(Sema &S,
7247 NamedDecl *Specialized,
7248 NamedDecl *PrevDecl,
7249 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007250 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00007251 // Keep these "kind" numbers in sync with the %select statements in the
7252 // various diagnostics emitted by this routine.
7253 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007254 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007255 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007256 else if (isa<VarTemplateDecl>(Specialized))
7257 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007258 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007259 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007260 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007261 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007262 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00007263 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007264 else if (isa<RecordDecl>(Specialized))
7265 EntityKind = 7;
7266 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7267 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00007268 else {
Richard Smith7d137e32012-03-23 03:33:32 +00007269 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007270 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007271 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00007272 return true;
7273 }
7274
Douglas Gregorf47b9112009-02-25 22:02:03 +00007275 // C++ [temp.expl.spec]p2:
Richard Smithc660c8f2018-03-16 13:36:56 +00007276 // An explicit specialization may be declared in any scope in which
7277 // the corresponding primary template may be defined.
Sebastian Redl50c68252010-08-31 00:36:30 +00007278 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00007279 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007280 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007281 return true;
7282 }
Douglas Gregore4b05162009-10-07 17:21:34 +00007283
7284 // C++ [temp.class.spec]p6:
Richard Smithc660c8f2018-03-16 13:36:56 +00007285 // A class template partial specialization may be declared in any
7286 // scope in which the primary template may be defined.
7287 DeclContext *SpecializedContext =
7288 Specialized->getDeclContext()->getRedeclContext();
7289 DeclContext *DC = S.CurContext->getRedeclContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00007290
Richard Smithc660c8f2018-03-16 13:36:56 +00007291 // Make sure that this redeclaration (or definition) occurs in the same
7292 // scope or an enclosing namespace.
7293 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7294 : DC->Equals(SpecializedContext))) {
Richard Smitha98f8fc2013-12-07 05:09:50 +00007295 if (isa<TranslationUnitDecl>(SpecializedContext))
7296 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7297 << EntityKind << Specialized;
Richard Smithc660c8f2018-03-16 13:36:56 +00007298 else {
7299 auto *ND = cast<NamedDecl>(SpecializedContext);
Alexey Bataev0068cb22015-03-20 07:21:46 +00007300 int Diag = diag::err_template_spec_redecl_out_of_scope;
Richard Smithc660c8f2018-03-16 13:36:56 +00007301 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
Alexey Bataev0068cb22015-03-20 07:21:46 +00007302 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7303 S.Diag(Loc, Diag) << EntityKind << Specialized
Richard Smithc660c8f2018-03-16 13:36:56 +00007304 << ND << isa<CXXRecordDecl>(ND);
7305 }
Richard Smitha98f8fc2013-12-07 05:09:50 +00007306
7307 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007308
Richard Smithc660c8f2018-03-16 13:36:56 +00007309 // Don't allow specializing in the wrong class during error recovery.
7310 // Otherwise, things can go horribly wrong.
7311 if (DC->isRecord())
7312 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007314
Douglas Gregorf47b9112009-02-25 22:02:03 +00007315 return false;
7316}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007317
Richard Smith57aae072016-12-28 02:37:25 +00007318static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7319 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00007320 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007321 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007322 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00007323 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007324 return E->getSourceRange();
7325 return Checker.MatchLoc;
7326}
7327
7328static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7329 if (!TL.getType()->isDependentType())
7330 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007331 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007332 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00007333 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007334 return TL.getSourceRange();
7335 return Checker.MatchLoc;
7336}
7337
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007338/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007339/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007340static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007341 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7342 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007343 for (unsigned I = 0; I != NumArgs; ++I) {
7344 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007345 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007346 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7347 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007348 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007349
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007350 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007351 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007352
Eli Friedmanb826a002012-09-26 02:36:12 +00007353 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007354 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00007355
7356 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007357
Douglas Gregor98318c22011-01-03 21:37:45 +00007358 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007359 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7360 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00007361
7362 // Strip off any implicit casts we added as part of type checking.
7363 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7364 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007365
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007366 // C++ [temp.class.spec]p8:
7367 // A non-type argument is non-specialized if it is the name of a
7368 // non-type parameter. All other non-type arguments are
7369 // specialized.
7370 //
7371 // Below, we check the two conditions that only apply to
7372 // specialized non-type arguments, so skip any non-specialized
7373 // arguments.
7374 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00007375 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007376 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007377
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007378 // C++ [temp.class.spec]p9:
7379 // Within the argument list of a class template partial
7380 // specialization, the following restrictions apply:
7381 // -- A partially specialized non-type argument expression
7382 // shall not involve a template parameter of the partial
7383 // specialization except when the argument expression is a
7384 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00007385 // -- The type of a template parameter corresponding to a
7386 // specialized non-type argument shall not be dependent on a
7387 // parameter of the specialization.
7388 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7389 // We implement a compromise between the original rules and DR1315:
7390 // -- A specialized non-type template argument shall not be
7391 // type-dependent and the corresponding template parameter
7392 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00007393 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00007394 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00007395 if (ParamUseRange.isValid()) {
7396 if (IsDefaultArgument) {
7397 S.Diag(TemplateNameLoc,
7398 diag::err_dependent_non_type_arg_in_partial_spec);
7399 S.Diag(ParamUseRange.getBegin(),
7400 diag::note_dependent_non_type_default_arg_in_partial_spec)
7401 << ParamUseRange;
7402 } else {
7403 S.Diag(ParamUseRange.getBegin(),
7404 diag::err_dependent_non_type_arg_in_partial_spec)
7405 << ParamUseRange;
7406 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007407 return true;
7408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007409
Richard Smith6056d5e2014-02-09 00:54:43 +00007410 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00007411 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00007412 if (ParamUseRange.isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007413 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
Richard Smith6056d5e2014-02-09 00:54:43 +00007414 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007415 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00007416 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00007417 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7418 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007419 return true;
7420 }
7421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007422
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007423 return false;
7424}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007425
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007426/// Check the non-type template arguments of a class template
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007427/// partial specialization according to C++ [temp.class.spec]p9.
7428///
Richard Smith6056d5e2014-02-09 00:54:43 +00007429/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00007430/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00007431/// template.
7432/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00007433/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00007434/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007435///
Richard Smith6056d5e2014-02-09 00:54:43 +00007436/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00007437bool Sema::CheckTemplatePartialSpecializationArgs(
7438 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7439 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7440 // We have to be conservative when checking a template in a dependent
7441 // context.
7442 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7443 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007444
Richard Smith57aae072016-12-28 02:37:25 +00007445 TemplateParameterList *TemplateParams =
7446 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007447 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7448 NonTypeTemplateParmDecl *Param
7449 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7450 if (!Param)
7451 continue;
7452
Richard Smith57aae072016-12-28 02:37:25 +00007453 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7454 Param, &TemplateArgs[I],
7455 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007456 return true;
7457 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007458
7459 return false;
7460}
7461
Erich Keanec480f302018-07-12 21:09:05 +00007462DeclResult Sema::ActOnClassTemplateSpecialization(
7463 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7464 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7465 const ParsedAttributesView &Attr,
7466 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007467 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007468
Richard Smith4b55a9c2014-04-17 03:29:33 +00007469 CXXScopeSpec &SS = TemplateId.SS;
7470
Abramo Bagnara60804e12011-03-18 15:16:37 +00007471 // NOTE: KWLoc is the location of the tag keyword. This will instead
7472 // store the location of the outermost template keyword in the declaration.
7473 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007474 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7475 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7476 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7477 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007478
Douglas Gregor67a65642009-02-17 23:15:12 +00007479 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007480 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007481 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007482 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7483
7484 if (!ClassTemplate) {
7485 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007486 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007487 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7488 return true;
7489 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007490
Richard Smithf445f192017-02-09 21:04:43 +00007491 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007492 bool isPartialSpecialization = false;
7493
Douglas Gregorf47b9112009-02-25 22:02:03 +00007494 // Check the validity of the template headers that introduce this
7495 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007496 // FIXME: We probably shouldn't complain about these headers for
7497 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007498 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007499 TemplateParameterList *TemplateParams =
7500 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007501 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007502 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007503 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007504 if (Invalid)
7505 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007506
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007507 if (TemplateParams && TemplateParams->size() > 0) {
7508 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007509
Douglas Gregorec9518b2010-12-21 08:14:57 +00007510 if (TUK == TUK_Friend) {
7511 Diag(KWLoc, diag::err_partial_specialization_friend)
7512 << SourceRange(LAngleLoc, RAngleLoc);
7513 return true;
7514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007515
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007516 // C++ [temp.class.spec]p10:
7517 // The template parameter list of a specialization shall not
7518 // contain default template argument values.
7519 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7520 Decl *Param = TemplateParams->getParam(I);
7521 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7522 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007523 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007524 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007525 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007526 }
7527 } else if (NonTypeTemplateParmDecl *NTTP
7528 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7529 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007530 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007531 diag::err_default_arg_in_partial_spec)
7532 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007533 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007534 }
7535 } else {
7536 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007537 if (TTP->hasDefaultArgument()) {
7538 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007539 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007540 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007541 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007542 }
7543 }
7544 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007545 } else if (TemplateParams) {
7546 if (TUK == TUK_Friend)
7547 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007548 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007549 SourceRange(TemplateParams->getTemplateLoc(),
7550 TemplateParams->getRAngleLoc()))
7551 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007552 } else {
7553 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007554 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007555
Douglas Gregor67a65642009-02-17 23:15:12 +00007556 // Check that the specialization uses the same tag kind as the
7557 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007558 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7559 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007560 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007561 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007562 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007563 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007564 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007565 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007566 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007567 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007568 diag::note_previous_use);
7569 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7570 }
7571
Douglas Gregorc40290e2009-03-09 23:48:35 +00007572 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007573 TemplateArgumentListInfo TemplateArgs =
7574 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007575
Douglas Gregor14406932011-01-03 20:35:03 +00007576 // Check for unexpanded parameter packs in any of the template arguments.
7577 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007578 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007579 UPPC_PartialSpecialization))
7580 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007581
Douglas Gregor67a65642009-02-17 23:15:12 +00007582 // Check that the template argument list is well-formed for this
7583 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007584 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007585 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7586 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007587 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007588
Douglas Gregor2373c592009-05-31 09:31:02 +00007589 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007590 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007591 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007592 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7593 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007594 return true;
7595
Richard Smith57aae072016-12-28 02:37:25 +00007596 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7597 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007598 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007599 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007600 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007601 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007602 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7603 << ClassTemplate->getDeclName();
7604 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007605 }
7606 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007607
Craig Topperc3ec1492014-05-26 06:22:03 +00007608 void *InsertPos = nullptr;
7609 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007610
7611 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007612 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007613 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007614 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007615 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007616
Craig Topperc3ec1492014-05-26 06:22:03 +00007617 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007618
Douglas Gregorf47b9112009-02-25 22:02:03 +00007619 // Check whether we can declare a class template specialization in
7620 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007621 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007622 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7623 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007624 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007625 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007626
Douglas Gregor15301382009-07-30 17:40:51 +00007627 // The canonical type
7628 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007629 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007630 // Build the canonical type that describes the converted template
7631 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007632 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7633 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007634 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007635
7636 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007637 ClassTemplate->getInjectedClassNameSpecialization())) {
7638 // C++ [temp.class.spec]p9b3:
7639 //
7640 // -- The argument list of the specialization shall not be identical
7641 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007642 //
7643 // This rule has since been removed, because it's redundant given DR1495,
7644 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007645 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007646 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007647 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007648 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7649 ClassTemplate->getIdentifier(),
7650 TemplateNameLoc,
7651 Attr,
7652 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007653 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007654 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007655 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007656 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007657 }
Douglas Gregor15301382009-07-30 17:40:51 +00007658
Douglas Gregor2373c592009-05-31 09:31:02 +00007659 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007660 ClassTemplatePartialSpecializationDecl *PrevPartial
7661 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007662 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007663 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007664 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007665 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007666 TemplateParams,
7667 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007668 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007669 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007670 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007671 PrevPartial);
Bruno Ricci4224c872018-12-21 14:35:24 +00007672 SetNestedNameSpecifier(*this, Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007673 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007674 Partial->setTemplateParameterListsInfo(
7675 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007676 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007677
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007678 if (!PrevPartial)
7679 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007680 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007681
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007682 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007683 // template specialization, make a note of that.
7684 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7685 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007686
Richard Smith57aae072016-12-28 02:37:25 +00007687 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007688 } else {
7689 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007690 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007691 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007692 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007693 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007694 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007695 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007696 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007697 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00007698 SetNestedNameSpecifier(*this, Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007699 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007700 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007701 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007702 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007703
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007704 if (!PrevDecl)
7705 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007706
David Majnemer678f50b2015-11-18 19:49:19 +00007707 if (CurContext->isDependentContext()) {
David Majnemer678f50b2015-11-18 19:49:19 +00007708 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7709 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007710 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007711 } else {
7712 CanonType = Context.getTypeDeclType(Specialization);
7713 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007714 }
7715
Douglas Gregor06db9f52009-10-12 20:18:28 +00007716 // C++ [temp.expl.spec]p6:
7717 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007718 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007719 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007720 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007721 // use occurs; no diagnostic is required.
7722 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007723 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007724 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007725 // Is there any previous explicit specialization declaration?
7726 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7727 Okay = true;
7728 break;
7729 }
7730 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007731
Douglas Gregorc854c662010-02-26 06:03:23 +00007732 if (!Okay) {
7733 SourceRange Range(TemplateNameLoc, RAngleLoc);
7734 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7735 << Context.getTypeDeclType(Specialization) << Range;
7736
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007737 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007738 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007739 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007740 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007741 return true;
7742 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007743 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007744
Douglas Gregor2208a292009-09-26 20:57:03 +00007745 // If this is not a friend, note that this is an explicit specialization.
7746 if (TUK != TUK_Friend)
7747 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007748
7749 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007750 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007751 RecordDecl *Def = Specialization->getDefinition();
7752 NamedDecl *Hidden = nullptr;
7753 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7754 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00007755 SkipBody->Previous = Def;
Richard Smith858e0e02017-05-11 23:11:16 +00007756 makeMergedDefinitionVisible(Hidden);
Richard Smithc7e6ff02015-05-18 20:36:47 +00007757 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007758 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007759 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007760 Diag(Def->getLocation(), diag::note_previous_definition);
7761 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007762 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007763 }
7764 }
7765
Erich Keanec480f302018-07-12 21:09:05 +00007766 ProcessDeclAttributeList(S, Specialization, Attr);
John McCall659a3372010-12-18 03:30:47 +00007767
Richard Smith034b94a2012-08-17 03:20:55 +00007768 // Add alignment attributes if necessary; these attributes are checked when
7769 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00007770 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Richard Smith034b94a2012-08-17 03:20:55 +00007771 AddAlignmentAttributesForRecord(Specialization);
7772 AddMsStructLayoutForRecord(Specialization);
7773 }
7774
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007775 if (ModulePrivateLoc.isValid())
7776 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7777 << (isPartialSpecialization? 1 : 0)
7778 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007779
Douglas Gregord56a91e2009-02-26 22:19:44 +00007780 // Build the fully-sugared type for this class template
7781 // specialization as the user wrote in the specialization
7782 // itself. This means that we'll pretty-print the type retrieved
7783 // from the specialization's declaration the way that the user
7784 // actually wrote the specialization, rather than formatting the
7785 // name based on the "canonical" representation used to store the
7786 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007787 TypeSourceInfo *WrittenTy
7788 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7789 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007790 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007791 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007792 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007793 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007794
Douglas Gregor1e249f82009-02-25 22:18:32 +00007795 // C++ [temp.expl.spec]p9:
7796 // A template explicit specialization is in the scope of the
7797 // namespace in which the template was defined.
7798 //
7799 // We actually implement this paragraph where we set the semantic
7800 // context (in the creation of the ClassTemplateSpecializationDecl),
7801 // but we also maintain the lexical context where the actual
7802 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007803 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007804
Douglas Gregor67a65642009-02-17 23:15:12 +00007805 // We may be starting the definition of this specialization.
Richard Smithc4577662018-09-12 02:13:47 +00007806 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregor67a65642009-02-17 23:15:12 +00007807 Specialization->startDefinition();
7808
Douglas Gregor2208a292009-09-26 20:57:03 +00007809 if (TUK == TUK_Friend) {
7810 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7811 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007812 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007813 /*FIXME:*/KWLoc);
7814 Friend->setAccess(AS_public);
7815 CurContext->addDecl(Friend);
7816 } else {
7817 // Add the specialization into its lexical context, so that it can
7818 // be seen when iterating through the list of declarations in that
7819 // context. However, specializations are not found by name lookup.
7820 CurContext->addDecl(Specialization);
7821 }
Richard Smithc4577662018-09-12 02:13:47 +00007822
7823 if (SkipBody && SkipBody->ShouldSkip)
7824 return SkipBody->Previous;
7825
John McCall48871652010-08-21 09:40:31 +00007826 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007827}
Douglas Gregor333489b2009-03-27 23:10:48 +00007828
John McCall48871652010-08-21 09:40:31 +00007829Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007830 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007831 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007832 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007833 ActOnDocumentableDecl(NewDecl);
7834 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007835}
7836
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007837/// Strips various properties off an implicit instantiation
John McCall4f7ced62010-02-11 01:33:53 +00007838/// that has just been explicitly specialized.
7839static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007840 D->dropAttr<DLLImportAttr>();
7841 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007842
Nico Webere4974382014-12-19 23:52:45 +00007843 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007844 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007845}
7846
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007847/// Compute the diagnostic location for an explicit instantiation
Nico Webera8f80b32012-01-09 19:52:25 +00007848// declaration or definition.
7849static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007850 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007851 // Explicit instantiations following a specialization have no effect and
7852 // hence no PointOfInstantiation. In that case, walk decl backwards
7853 // until a valid name loc is found.
7854 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007855 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7856 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007857 PrevDiagLoc = Prev->getLocation();
7858 }
7859 assert(PrevDiagLoc.isValid() &&
7860 "Explicit instantiation without point of instantiation?");
7861 return PrevDiagLoc;
7862}
7863
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007864/// Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007865/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007866/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007867/// new specialization/instantiation will have any effect.
7868///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007869/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007870/// instantiation.
7871///
7872/// \param NewTSK the kind of the new explicit specialization or instantiation.
7873///
7874/// \param PrevDecl the previous declaration of the entity.
7875///
7876/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7877///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007878/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007879/// declaration was instantiated (either implicitly or explicitly).
7880///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007881/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007882/// specialization or instantiation has no effect and should be ignored.
7883///
7884/// \returns true if there was an error that should prevent the introduction of
7885/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007886bool
7887Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7888 TemplateSpecializationKind NewTSK,
7889 NamedDecl *PrevDecl,
7890 TemplateSpecializationKind PrevTSK,
7891 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007892 bool &HasNoEffect) {
7893 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007894
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007895 switch (NewTSK) {
7896 case TSK_Undeclared:
7897 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007898 assert(
7899 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7900 "previous declaration must be implicit!");
7901 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007902
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007903 case TSK_ExplicitSpecialization:
7904 switch (PrevTSK) {
7905 case TSK_Undeclared:
7906 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007907 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007908 // explicitly specialized or has merely been mentioned without any
7909 // instantiation.
7910 return false;
7911
7912 case TSK_ImplicitInstantiation:
7913 if (PrevPointOfInstantiation.isInvalid()) {
7914 // The declaration itself has not actually been instantiated, so it is
7915 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007916 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007917 return false;
7918 }
7919 // Fall through
Galina Kistanova3779cb32017-06-07 06:25:05 +00007920 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007921
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007922 case TSK_ExplicitInstantiationDeclaration:
7923 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007924 assert((PrevTSK == TSK_ImplicitInstantiation ||
7925 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007926 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007927
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007928 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007929 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007930 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007931 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007932 // implicit instantiation to take place, in every translation unit in
7933 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007934 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007935 // Is there any previous explicit specialization declaration?
7936 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7937 return false;
7938 }
7939
Douglas Gregor1d957a32009-10-27 18:42:08 +00007940 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007941 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007942 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007943 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007944
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007945 return true;
7946 }
Galina Kistanova1d36e832017-06-08 18:20:32 +00007947 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007948
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007949 case TSK_ExplicitInstantiationDeclaration:
7950 switch (PrevTSK) {
7951 case TSK_ExplicitInstantiationDeclaration:
7952 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007953 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007954 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007955
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007956 case TSK_Undeclared:
7957 case TSK_ImplicitInstantiation:
7958 // We're explicitly instantiating something that may have already been
7959 // implicitly instantiated; that's fine.
7960 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007961
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007962 case TSK_ExplicitSpecialization:
7963 // C++0x [temp.explicit]p4:
7964 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007965 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007966 // specialization for that template, the explicit instantiation has no
7967 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007968 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007969 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007970
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007971 case TSK_ExplicitInstantiationDefinition:
7972 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007973 // If an entity is the subject of both an explicit instantiation
7974 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007975 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007976 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007977 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007978
7979 // Explicit instantiations following a specialization have no effect and
7980 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7981 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007982 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7983 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007984 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007985 return false;
7986 }
Bruno Riccid8c17672018-12-21 20:38:06 +00007987 llvm_unreachable("Unexpected TemplateSpecializationKind!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007988
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007989 case TSK_ExplicitInstantiationDefinition:
7990 switch (PrevTSK) {
7991 case TSK_Undeclared:
7992 case TSK_ImplicitInstantiation:
7993 // We're explicitly instantiating something that may have already been
7994 // implicitly instantiated; that's fine.
7995 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007996
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007997 case TSK_ExplicitSpecialization:
7998 // C++ DR 259, C++0x [temp.explicit]p4:
7999 // For a given set of template parameters, if an explicit
8000 // instantiation of a template appears after a declaration of
8001 // an explicit specialization for that template, the explicit
8002 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00008003 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00008004 << PrevDecl;
8005 Diag(PrevDecl->getLocation(),
8006 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008007 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008008 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008009
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008010 case TSK_ExplicitInstantiationDeclaration:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008011 // We're explicitly instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008012 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00008013
8014 // C++0x [temp.explicit]p4:
8015 // For a given set of template parameters, if an explicit instantiation
8016 // of a template appears after a declaration of an explicit
8017 // specialization for that template, the explicit instantiation has no
8018 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00008019 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00008020 // Is there any previous explicit specialization declaration?
8021 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8022 HasNoEffect = true;
8023 break;
8024 }
8025 }
8026
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008027 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008028
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008029 case TSK_ExplicitInstantiationDefinition:
8030 // C++0x [temp.spec]p5:
8031 // For a given template and a given set of template-arguments,
8032 // - an explicit instantiation definition shall appear at most once
8033 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008034
8035 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8036 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00008037 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008038 : diag::err_explicit_instantiation_duplicate)
8039 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00008040 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00008041 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008042 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008043 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008044 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008046
David Blaikie83d382b2011-09-23 05:06:16 +00008047 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008048}
8049
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008050/// Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00008051/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00008052///
James Dennettf14a6e52012-06-15 22:23:43 +00008053/// The only possible way to get a dependent function template specialization
8054/// is with a friend declaration, like so:
8055///
8056/// \code
8057/// template \<class T> void foo(T);
8058/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00008059/// friend void foo<>(T);
8060/// };
James Dennettf14a6e52012-06-15 22:23:43 +00008061/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00008062///
8063/// There really isn't any useful analysis we can do here, so we
8064/// just store the information.
8065bool
8066Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8067 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8068 LookupResult &Previous) {
8069 // Remove anything from Previous that isn't a function template in
8070 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00008071 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00008072 LookupResult::Filter F = Previous.makeFilter();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008073 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8074 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
John McCallb9c78482010-04-08 09:05:18 +00008075 while (F.hasNext()) {
8076 NamedDecl *D = F.next()->getUnderlyingDecl();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008077 if (!isa<FunctionTemplateDecl>(D)) {
John McCallb9c78482010-04-08 09:05:18 +00008078 F.erase();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008079 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8080 continue;
8081 }
8082
8083 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8084 D->getDeclContext()->getRedeclContext())) {
8085 F.erase();
8086 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8087 continue;
8088 }
John McCallb9c78482010-04-08 09:05:18 +00008089 }
8090 F.done();
8091
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008092 if (Previous.empty()) {
8093 Diag(FD->getLocation(),
8094 diag::err_dependent_function_template_spec_no_match);
8095 for (auto &P : DiscardedCandidates)
8096 Diag(P.second->getLocation(),
8097 diag::note_dependent_function_template_spec_discard_reason)
8098 << P.first;
8099 return true;
8100 }
John McCallb9c78482010-04-08 09:05:18 +00008101
8102 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8103 ExplicitTemplateArgs);
8104 return false;
8105}
8106
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008107/// Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008108/// specialization.
8109///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008110/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008111/// explicit function template specialization. On successful completion,
8112/// the function declaration \p FD will become a function template
8113/// specialization.
8114///
8115/// \param FD the function declaration, which will be updated to become a
8116/// function template specialization.
8117///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008118/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8119/// if any. Note that this may be valid info even when 0 arguments are
8120/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8121/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008122///
Francois Pichet3a44e432011-07-08 06:21:47 +00008123/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008124/// this function specialization.
Richard Smith8ce732b2019-01-07 06:00:46 +00008125///
8126/// \param QualifiedFriend whether this is a lookup for a qualified friend
8127/// declaration with no explicit template argument list that might be
8128/// befriending a function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008129bool Sema::CheckFunctionTemplateSpecialization(
8130 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smith8ce732b2019-01-07 06:00:46 +00008131 LookupResult &Previous, bool QualifiedFriend) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008132 // The set of function template specializations that could match this
8133 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00008134 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008135 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8136 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008137
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008138 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8139 ConvertedTemplateArgs;
8140
Sebastian Redl50c68252010-08-31 00:36:30 +00008141 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00008142 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8143 I != E; ++I) {
8144 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8145 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008146 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008147 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00008148 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8149 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008150 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008151
Richard Smith574f4f62013-01-14 05:37:29 +00008152 // When matching a constexpr member function template specialization
8153 // against the primary template, we don't yet know whether the
8154 // specialization has an implicit 'const' (because we don't know whether
8155 // it will be a static member function until we know which template it
8156 // specializes), so adjust it now assuming it specializes this template.
8157 QualType FT = FD->getType();
8158 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008159 CXXMethodDecl *OldMD =
8160 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00008161 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008162 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00008163 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00008164 EPI.TypeQuals.addConst();
Alp Toker314cc812014-01-25 16:55:45 +00008165 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008166 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00008167 }
8168 }
8169
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008170 TemplateArgumentListInfo Args;
8171 if (ExplicitTemplateArgs)
8172 Args = *ExplicitTemplateArgs;
8173
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008174 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008175 // A trailing template-argument can be left unspecified in the
8176 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008177 // provided it can be deduced from the function argument type.
8178 // Perform template argument deduction to determine whether we may be
8179 // specializing this template.
8180 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00008181 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008182 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00008183 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8184 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00008185 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8186 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008187 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008188 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00008189 FailedCandidates.addCandidate().set(
8190 I.getPair(), FunTmpl->getTemplatedDecl(),
8191 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008192 (void)TDK;
8193 continue;
8194 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008195
Artem Belevich64135c32016-12-08 19:38:13 +00008196 // Target attributes are part of the cuda function signature, so
8197 // the deduced template's cuda target must match that of the
8198 // specialization. Given that C++ template deduction does not
8199 // take target attributes into account, we reject candidates
8200 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008201 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00008202 IdentifyCUDATarget(Specialization,
8203 /* IgnoreImplicitHDAttributes = */ true) !=
8204 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008205 FailedCandidates.addCandidate().set(
8206 I.getPair(), FunTmpl->getTemplatedDecl(),
8207 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8208 continue;
8209 }
8210
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008211 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008212 if (ExplicitTemplateArgs)
8213 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00008214 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008215 }
8216 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008217
Richard Smith8ce732b2019-01-07 06:00:46 +00008218 // For a qualified friend declaration (with no explicit marker to indicate
8219 // that a template specialization was intended), note all (template and
8220 // non-template) candidates.
8221 if (QualifiedFriend && Candidates.empty()) {
8222 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8223 << FD->getDeclName() << FDLookupContext;
8224 // FIXME: We should form a single candidate list and diagnose all
8225 // candidates at once, to get proper sorting and limiting.
8226 for (auto *OldND : Previous) {
8227 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8228 NoteOverloadCandidate(OldND, OldFD, FD->getType(), false);
8229 }
8230 FailedCandidates.NoteCandidates(*this, FD->getLocation());
8231 return true;
8232 }
8233
Douglas Gregor5de279c2009-09-26 03:41:46 +00008234 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008235 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith8ce732b2019-01-07 06:00:46 +00008236 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008237 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8238 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00008239 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008240 PDiag(diag::note_function_template_spec_matched));
8241
John McCall58cc69d2010-01-27 01:50:18 +00008242 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008243 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008244
8245 // Ignore access information; it doesn't figure into redeclaration checking.
8246 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00008247
8248 FunctionTemplateSpecializationInfo *SpecInfo
8249 = Specialization->getTemplateSpecializationInfo();
8250 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00008251
8252 // Note: do not overwrite location info if previous template
8253 // specialization kind was explicit.
8254 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00008255 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00008256 Specialization->setLocation(FD->getLocation());
Richard Smith54f04402017-05-18 02:29:20 +00008257 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
Richard Smith5b8b3db2012-02-20 23:28:05 +00008258 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8259 // function can differ from the template declaration with respect to
8260 // the constexpr specifier.
Richard Smith77e9e842017-05-09 23:02:10 +00008261 // FIXME: We need an update record for this AST mutation.
8262 // FIXME: What if there are multiple such prior declarations (for instance,
8263 // from different modules)?
Richard Smith5b8b3db2012-02-20 23:28:05 +00008264 Specialization->setConstexpr(FD->isConstexpr());
8265 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008266
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008267 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00008268 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00008269
8270 // If this is a friend declaration, then we're not really declaring
8271 // an explicit specialization.
8272 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008273
Douglas Gregor54888652009-10-07 00:13:32 +00008274 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00008275 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008276 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00008277 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008278 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008279 false))
Douglas Gregor54888652009-10-07 00:13:32 +00008280 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008281
8282 // C++ [temp.expl.spec]p6:
8283 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008284 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008285 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008286 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008287 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008288 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00008289 if (!isFriend &&
8290 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00008291 TSK_ExplicitSpecialization,
8292 Specialization,
8293 SpecInfo->getTemplateSpecializationKind(),
8294 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008295 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008296 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008297
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008298 // Mark the prior declaration as an explicit specialization, so that later
8299 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008300 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00008301 // Since explicit specializations do not inherit '=delete' from their
8302 // primary function template - check if the 'specialization' that was
8303 // implicitly generated (during template argument deduction for partial
8304 // ordering) from the most specialized of all the function templates that
8305 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8306 // first check that it was implicitly generated during template argument
8307 // deduction by making sure it wasn't referenced, and then reset the deleted
8308 // flag to not-deleted, so that we can inherit that information from 'FD'.
8309 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8310 !Specialization->getCanonicalDecl()->isReferenced()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008311 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali81a88be2016-06-14 03:23:15 +00008312 assert(
8313 Specialization->getCanonicalDecl() == Specialization &&
8314 "This must be the only existing declaration of this specialization");
Richard Smith77e9e842017-05-09 23:02:10 +00008315 // FIXME: We need an update record for this AST mutation.
Faisal Vali81a88be2016-06-14 03:23:15 +00008316 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008317 }
Richard Smith54f04402017-05-18 02:29:20 +00008318 // FIXME: We need an update record for this AST mutation.
John McCall816d75b2010-03-24 07:46:06 +00008319 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008320 MarkUnusedFileScopedDecl(Specialization);
8321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008322
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008323 // Turn the given function declaration into a function template
8324 // specialization, with the template arguments from the previous
8325 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008326 // Take copies of (semantic and syntactic) template argument lists.
8327 const TemplateArgumentList* TemplArgs = new (Context)
8328 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008329 FD->setFunctionTemplateSpecialization(
8330 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8331 SpecInfo->getTemplateSpecializationKind(),
8332 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008333
Artem Belevich64135c32016-12-08 19:38:13 +00008334 // A function template specialization inherits the target attributes
8335 // of its template. (We require the attributes explicitly in the
8336 // code to match, but a template may have implicit attributes by
8337 // virtue e.g. of being constexpr, and it passes these implicit
8338 // attributes on to its specializations.)
8339 if (LangOpts.CUDA)
8340 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8341
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008342 // The "previous declaration" for this function template specialization is
8343 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00008344 Previous.clear();
8345 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008346 return false;
8347}
8348
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008349/// Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008350/// specialization.
8351///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008352/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008353/// explicit member function specialization. On successful completion,
8354/// the function declaration \p FD will become a member function
8355/// specialization.
8356///
Douglas Gregor86d142a2009-10-08 07:24:58 +00008357/// \param Member the member declaration, which will be updated to become a
8358/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008359///
John McCall1f82f242009-11-18 22:49:29 +00008360/// \param Previous the set of declarations, one of which may be specialized
8361/// by this function specialization; the set will be modified to contain the
8362/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008363bool
John McCall1f82f242009-11-18 22:49:29 +00008364Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008365 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00008366
Douglas Gregor86d142a2009-10-08 07:24:58 +00008367 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00008368 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00008369 NamedDecl *Instantiation = nullptr;
8370 NamedDecl *InstantiatedFrom = nullptr;
8371 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008372
John McCall1f82f242009-11-18 22:49:29 +00008373 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008374 // Nowhere to look anyway.
8375 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008376 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8377 I != E; ++I) {
8378 NamedDecl *D = (*I)->getUnderlyingDecl();
8379 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00008380 QualType Adjusted = Function->getType();
8381 if (!hasExplicitCallingConv(Adjusted))
8382 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
Richard Smith4576a772018-09-10 06:35:32 +00008383 // This doesn't handle deduced return types, but both function
8384 // declarations should be undeduced at this point.
Rafael Espindola66747222013-12-10 00:59:31 +00008385 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008386 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008387 Instantiation = Method;
8388 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008389 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008390 break;
8391 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008392 }
8393 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00008394 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008395 VarDecl *PrevVar;
8396 if (Previous.isSingleResult() &&
8397 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00008398 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008399 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008400 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008401 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008402 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008403 }
8404 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008405 CXXRecordDecl *PrevRecord;
8406 if (Previous.isSingleResult() &&
8407 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008408 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008409 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008410 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008411 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008412 }
Richard Smith7d137e32012-03-23 03:33:32 +00008413 } else if (isa<EnumDecl>(Member)) {
8414 EnumDecl *PrevEnum;
8415 if (Previous.isSingleResult() &&
8416 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008417 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00008418 Instantiation = PrevEnum;
8419 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8420 MSInfo = PrevEnum->getMemberSpecializationInfo();
8421 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008423
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008424 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008425 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008426 // specializations are always out-of-line, the caller will complain about
8427 // this mismatch later.
8428 return false;
8429 }
John McCalle820e5e2010-04-13 20:37:33 +00008430
Richard Smith77e9e842017-05-09 23:02:10 +00008431 // A member specialization in a friend declaration isn't really declaring
8432 // an explicit specialization, just identifying a specific (possibly implicit)
8433 // specialization. Don't change the template specialization kind.
8434 //
8435 // FIXME: Is this really valid? Other compilers reject.
John McCalle820e5e2010-04-13 20:37:33 +00008436 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8437 // Preserve instantiation information.
8438 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8439 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8440 cast<CXXMethodDecl>(InstantiatedFrom),
8441 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8442 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8443 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8444 cast<CXXRecordDecl>(InstantiatedFrom),
8445 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8446 }
8447
8448 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008449 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00008450 return false;
8451 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008452
Douglas Gregor86d142a2009-10-08 07:24:58 +00008453 // Make sure that this is a specialization of a member.
8454 if (!InstantiatedFrom) {
8455 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8456 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008457 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8458 return true;
8459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008460
Douglas Gregor06db9f52009-10-12 20:18:28 +00008461 // C++ [temp.expl.spec]p6:
8462 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00008463 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008464 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008465 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008466 // use occurs; no diagnostic is required.
8467 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00008468
Abramo Bagnara8075c852010-06-12 07:44:57 +00008469 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00008470 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8471 TSK_ExplicitSpecialization,
8472 Instantiation,
8473 MSInfo->getTemplateSpecializationKind(),
8474 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008475 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008476 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008477
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008478 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008479 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008480 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008481 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008482 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008483 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008484
Richard Smith77e9e842017-05-09 23:02:10 +00008485 // Note that this member specialization is an "instantiation of" the
8486 // corresponding member of the original template.
8487 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008488 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8489 if (InstantiationFunction->getTemplateSpecializationKind() ==
8490 TSK_ImplicitInstantiation) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008491 // Explicit specializations of member functions of class templates do not
8492 // inherit '=delete' from the member function they are specializing.
8493 if (InstantiationFunction->isDeleted()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008494 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008495 assert(InstantiationFunction->getCanonicalDecl() ==
8496 InstantiationFunction);
Richard Smith77e9e842017-05-09 23:02:10 +00008497 // FIXME: We need an update record for this AST mutation.
Richard Smith5f274382016-09-28 23:55:27 +00008498 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008499 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008501
Richard Smith77e9e842017-05-09 23:02:10 +00008502 MemberFunction->setInstantiationOfMemberFunction(
8503 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8504 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8505 MemberVar->setInstantiationOfStaticDataMember(
Larisse Voufo39a1e502013-08-06 01:03:05 +00008506 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008507 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8508 MemberClass->setInstantiationOfMemberClass(
8509 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8510 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8511 MemberEnum->setInstantiationOfMemberEnum(
Richard Smith7d137e32012-03-23 03:33:32 +00008512 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008513 } else {
8514 llvm_unreachable("unknown member specialization kind");
Douglas Gregor86d142a2009-10-08 07:24:58 +00008515 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008516
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008517 // Save the caller the trouble of having to figure out which declaration
8518 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008519 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008520 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008521 return false;
8522}
8523
Richard Smith77e9e842017-05-09 23:02:10 +00008524/// Complete the explicit specialization of a member of a class template by
8525/// updating the instantiated member to be marked as an explicit specialization.
8526///
8527/// \param OrigD The member declaration instantiated from the template.
8528/// \param Loc The location of the explicit specialization of the member.
8529template<typename DeclT>
8530static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8531 SourceLocation Loc) {
8532 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8533 return;
8534
8535 // FIXME: Inform AST mutation listeners of this AST mutation.
8536 // FIXME: If there are multiple in-class declarations of the member (from
8537 // multiple modules, or a declaration and later definition of a member type),
8538 // should we update all of them?
8539 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8540 OrigD->setLocation(Loc);
8541}
8542
8543void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8544 LookupResult &Previous) {
8545 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8546 if (Instantiation == Member)
8547 return;
8548
8549 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8550 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8551 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8552 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8553 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8554 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8555 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8556 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8557 else
8558 llvm_unreachable("unknown member specialization kind");
8559}
8560
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008561/// Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008562///
8563/// \returns true if a serious error occurs, false otherwise.
8564static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008565 SourceLocation InstLoc,
8566 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008567 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8568 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008569
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008570 if (CurContext->isRecord()) {
8571 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8572 << D;
8573 return true;
8574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008575
Richard Smith050d2612011-10-18 02:28:33 +00008576 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008577 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008578 // template. If the name declared in the explicit instantiation is an
8579 // unqualified name, the explicit instantiation shall appear in the
8580 // namespace where its template is declared or, if that namespace is inline
8581 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008582 //
8583 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008584 if (WasQualifiedName) {
8585 if (CurContext->Encloses(OrigContext))
8586 return false;
8587 } else {
8588 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8589 return false;
8590 }
8591
8592 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8593 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008594 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008595 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008596 diag::err_explicit_instantiation_out_of_scope :
8597 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008598 << D << NS;
8599 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008600 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008601 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008602 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8603 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8604 << D << NS;
8605 } else
8606 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008607 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008608 diag::err_explicit_instantiation_must_be_global :
8609 diag::warn_explicit_instantiation_must_be_global_0x)
8610 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008611 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008612 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008613}
8614
Richard Smith0d923af2019-04-26 01:51:07 +00008615/// Common checks for whether an explicit instantiation of \p D is valid.
8616static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
8617 SourceLocation InstLoc,
8618 bool WasQualifiedName,
8619 TemplateSpecializationKind TSK) {
8620 // C++ [temp.explicit]p13:
8621 // An explicit instantiation declaration shall not name a specialization of
8622 // a template with internal linkage.
8623 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8624 D->getFormalLinkage() == InternalLinkage) {
8625 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
8626 return true;
8627 }
8628
8629 // C++11 [temp.explicit]p3: [DR 275]
8630 // An explicit instantiation shall appear in an enclosing namespace of its
8631 // template.
8632 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
8633 return true;
8634
8635 return false;
8636}
8637
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008638/// Determine whether the given scope specifier has a template-id in it.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008639static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8640 if (!SS.isSet())
8641 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008642
Richard Smith050d2612011-10-18 02:28:33 +00008643 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008644 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008645 // or a static data member of a class template specialization, the name of
8646 // the class template specialization in the qualified-id for the member
8647 // name shall be a simple-template-id.
8648 //
8649 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008650 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8651 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008652 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008653 if (isa<TemplateSpecializationType>(T))
8654 return true;
8655
8656 return false;
8657}
8658
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008659/// Make a dllexport or dllimport attr on a class template specialization take
8660/// effect.
8661static void dllExportImportClassTemplateSpecialization(
8662 Sema &S, ClassTemplateSpecializationDecl *Def) {
8663 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8664 assert(A && "dllExportImportClassTemplateSpecialization called "
8665 "on Def without dllexport or dllimport");
8666
8667 // We reject explicit instantiations in class scope, so there should
8668 // never be any delayed exported classes to worry about.
8669 assert(S.DelayedDllExportClasses.empty() &&
8670 "delayed exports present at explicit instantiation");
8671 S.checkClassLevelDLLAttribute(Def);
8672
8673 // Propagate attribute to base class templates.
8674 for (auto &B : Def->bases()) {
8675 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8676 B.getType()->getAsCXXRecordDecl()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008677 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008678 }
8679
8680 S.referenceDLLExportedClassMethods();
8681}
8682
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008683// Explicit instantiation of a class template specialization
Erich Keanec480f302018-07-12 21:09:05 +00008684DeclResult Sema::ActOnExplicitInstantiation(
8685 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8686 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8687 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
8688 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
8689 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008690 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008691 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008692 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008693 // Check that the specialization uses the same tag kind as the
8694 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008695 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8696 assert(Kind != TTK_Enum &&
8697 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008698
Richard Trieu265c3442016-04-05 21:13:54 +00008699 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8700
8701 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008702 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8703 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008704 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008705 return true;
8706 }
8707
Douglas Gregord9034f02009-05-14 16:41:31 +00008708 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008709 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008710 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008711 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008712 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008713 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008714 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008715 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008716 diag::note_previous_use);
8717 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8718 }
8719
Douglas Gregore47f5a72009-10-14 23:41:34 +00008720 // C++0x [temp.explicit]p2:
8721 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008722 // definition and an explicit instantiation declaration. An explicit
8723 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008724 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8725 ? TSK_ExplicitInstantiationDefinition
8726 : TSK_ExplicitInstantiationDeclaration;
8727
Martin Storsjo5be69bc2019-04-26 08:09:51 +00008728 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8729 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
8730 // Check for dllexport class template instantiation declarations,
8731 // except for MinGW mode.
Erich Keanee891aa92018-07-13 15:07:47 +00008732 for (const ParsedAttr &AL : Attr) {
8733 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00008734 Diag(ExternLoc,
8735 diag::warn_attribute_dllexport_explicit_instantiation_decl);
Erich Keanec480f302018-07-12 21:09:05 +00008736 Diag(AL.getLoc(), diag::note_attribute);
Hans Wennborgfd76d912015-01-15 21:18:30 +00008737 break;
8738 }
8739 }
8740
8741 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8742 Diag(ExternLoc,
8743 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8744 Diag(A->getLocation(), diag::note_attribute);
8745 }
8746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008747
Hans Wennborga86a83b2016-05-26 19:42:56 +00008748 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8749 // instantiation declarations for most purposes.
8750 bool DLLImportExplicitInstantiationDef = false;
8751 if (TSK == TSK_ExplicitInstantiationDefinition &&
8752 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8753 // Check for dllimport class template instantiation definitions.
8754 bool DLLImport =
8755 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
Erich Keanee891aa92018-07-13 15:07:47 +00008756 for (const ParsedAttr &AL : Attr) {
8757 if (AL.getKind() == ParsedAttr::AT_DLLImport)
Hans Wennborga86a83b2016-05-26 19:42:56 +00008758 DLLImport = true;
Erich Keanee891aa92018-07-13 15:07:47 +00008759 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborga86a83b2016-05-26 19:42:56 +00008760 // dllexport trumps dllimport here.
8761 DLLImport = false;
8762 break;
8763 }
8764 }
8765 if (DLLImport) {
8766 TSK = TSK_ExplicitInstantiationDeclaration;
8767 DLLImportExplicitInstantiationDef = true;
8768 }
8769 }
8770
Douglas Gregora1f49972009-05-13 00:25:59 +00008771 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008772 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008773 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008774
8775 // Check that the template argument list is well-formed for this
8776 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008777 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008778 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8779 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008780 return true;
8781
Douglas Gregora1f49972009-05-13 00:25:59 +00008782 // Find the class template specialization declaration that
8783 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008784 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008785 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008786 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008787
Abramo Bagnara8075c852010-06-12 07:44:57 +00008788 TemplateSpecializationKind PrevDecl_TSK
8789 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8790
Martin Storsjo5be69bc2019-04-26 08:09:51 +00008791 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
8792 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
8793 // Check for dllexport class template instantiation definitions in MinGW
8794 // mode, if a previous declaration of the instantiation was seen.
8795 for (const ParsedAttr &AL : Attr) {
8796 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
8797 Diag(AL.getLoc(),
8798 diag::warn_attribute_dllexport_explicit_instantiation_def);
8799 break;
8800 }
8801 }
8802 }
8803
Richard Smith0d923af2019-04-26 01:51:07 +00008804 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
8805 SS.isSet(), TSK))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008806 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008807
Craig Topperc3ec1492014-05-26 06:22:03 +00008808 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008809
Abramo Bagnara8075c852010-06-12 07:44:57 +00008810 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008811 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008812 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008813 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008814 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008815 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008816 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008817
Abramo Bagnara8075c852010-06-12 07:44:57 +00008818 // Even though HasNoEffect == true means that this explicit instantiation
8819 // has no effect on semantics, we go on to put its syntax in the AST.
8820
8821 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8822 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008823 // Since the only prior class template specialization with these
8824 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008825 // declaration node as our own, updating the source location
8826 // for the template name to reflect our new declaration.
8827 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008828 Specialization = PrevDecl;
8829 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008830 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008831 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008832
8833 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8834 DLLImportExplicitInstantiationDef) {
8835 // The new specialization might add a dllimport attribute.
8836 HasNoEffect = false;
8837 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008838 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008839
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008840 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008841 // Create a new class template specialization declaration node for
8842 // this explicit specialization.
8843 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008844 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008845 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008846 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008847 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008848 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008849 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00008850 SetNestedNameSpecifier(*this, Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008851
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008852 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008853 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008854 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008855 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008856 }
8857
8858 // Build the fully-sugared type for this explicit instantiation as
8859 // the user wrote in the explicit instantiation itself. This means
8860 // that we'll pretty-print the type retrieved from the
8861 // specialization's declaration the way that the user actually wrote
8862 // the explicit instantiation, rather than formatting the name based
8863 // on the "canonical" representation used to store the template
8864 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008865 TypeSourceInfo *WrittenTy
8866 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8867 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008868 Context.getTypeDeclType(Specialization));
8869 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008870
Abramo Bagnara8075c852010-06-12 07:44:57 +00008871 // Set source locations for keywords.
8872 Specialization->setExternLoc(ExternLoc);
8873 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008874 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008875
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008876 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Erich Keanec480f302018-07-12 21:09:05 +00008877 ProcessDeclAttributeList(S, Specialization, Attr);
Rafael Espindola0b062072012-01-03 06:04:21 +00008878
Abramo Bagnara8075c852010-06-12 07:44:57 +00008879 // Add the explicit instantiation into its lexical context. However,
8880 // since explicit instantiations are never found by name lookup, we
8881 // just put it into the declaration context directly.
8882 Specialization->setLexicalDeclContext(CurContext);
8883 CurContext->addDecl(Specialization);
8884
8885 // Syntax is now OK, so return if it has no other effect on semantics.
8886 if (HasNoEffect) {
8887 // Set the template specialization kind.
8888 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008889 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008890 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008891
8892 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008893 // A definition of a class template or class member template
8894 // shall be in scope at the point of the explicit instantiation of
8895 // the class template or class member template.
8896 //
8897 // This check comes when we actually try to perform the
8898 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008899 ClassTemplateSpecializationDecl *Def
8900 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008901 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008902 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00008903 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008904 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008905 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008906 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8907 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008908
Douglas Gregor1d957a32009-10-27 18:42:08 +00008909 // Instantiate the members of this class template specialization.
8910 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008911 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00008912 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008913 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008914 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8915 // TSK_ExplicitInstantiationDefinition
8916 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00008917 (TSK == TSK_ExplicitInstantiationDefinition ||
8918 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00008919 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008920 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008921
Hans Wennborgc0875502015-06-09 00:39:05 +00008922 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00008923 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8924 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00008925 // In the MS ABI, an explicit instantiation definition can add a dll
8926 // attribute to a template with a previous instantiation declaration.
8927 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008928 auto *A = cast<InheritableAttr>(
8929 getDLLAttr(Specialization)->clone(getASTContext()));
8930 A->setInherited(true);
8931 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008932 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008933 }
8934 }
8935
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008936 // Fix a TSK_ImplicitInstantiation followed by a
8937 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008938 bool NewlyDLLExported =
8939 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8940 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008941 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8942 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8943 // In the MS ABI, an explicit instantiation definition can add a dll
8944 // attribute to a template with a previous implicit instantiation.
8945 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8946 // avoid potentially strange codegen behavior. For example, if we extend
8947 // this conditional to dllimport, and we have a source file calling a
8948 // method on an implicitly instantiated template class instance and then
8949 // declaring a dllimport explicit instantiation definition for the same
8950 // template class, the codegen for the method call will not respect the
8951 // dllimport, while it will with cl. The Def will already have the DLL
8952 // attribute, since the Def and Specialization will be the same in the
8953 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8954 // attribute to the Specialization; we just need to make it take effect.
8955 assert(Def == Specialization &&
8956 "Def and Specialization should match for implicit instantiation");
8957 dllExportImportClassTemplateSpecialization(*this, Def);
8958 }
8959
Martin Storsjo5be69bc2019-04-26 08:09:51 +00008960 // In MinGW mode, export the template instantiation if the declaration
8961 // was marked dllexport.
8962 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8963 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
8964 PrevDecl->hasAttr<DLLExportAttr>()) {
8965 dllExportImportClassTemplateSpecialization(*this, Def);
8966 }
8967
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008968 // Set the template specialization kind. Make sure it is set before
8969 // instantiating the members which will trigger ASTConsumer callbacks.
8970 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008971 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008972 } else {
8973
8974 // Set the template specialization kind.
8975 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008976 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008977
John McCall48871652010-08-21 09:40:31 +00008978 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008979}
8980
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008981// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008982DeclResult
Erich Keanec480f302018-07-12 21:09:05 +00008983Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
8984 SourceLocation TemplateLoc, unsigned TagSpec,
8985 SourceLocation KWLoc, CXXScopeSpec &SS,
8986 IdentifierInfo *Name, SourceLocation NameLoc,
8987 const ParsedAttributesView &Attr) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008988
Douglas Gregord6ab8742009-05-28 23:31:59 +00008989 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008990 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008991 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008992 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008993 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008994 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008995 SourceLocation(), false, TypeResult(),
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00008996 /*IsTypeSpecifier*/false,
8997 /*IsTemplateParamOrArg*/false);
John McCall7f41d982009-09-11 04:59:25 +00008998 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8999
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009000 if (!TagD)
9001 return true;
9002
John McCall48871652010-08-21 09:40:31 +00009003 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00009004 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009005
Douglas Gregorb8006faf2009-05-27 17:30:49 +00009006 if (Tag->isInvalidDecl())
9007 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009008
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009009 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9010 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
9011 if (!Pattern) {
9012 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9013 << Context.getTypeDeclType(Record);
9014 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
9015 return true;
9016 }
9017
Douglas Gregore47f5a72009-10-14 23:41:34 +00009018 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009019 // If the explicit instantiation is for a class or member class, the
9020 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00009021 // simple-template-id.
9022 //
9023 // C++98 has the same restriction, just worded differently.
9024 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00009025 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009026 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009027
Douglas Gregore47f5a72009-10-14 23:41:34 +00009028 // C++0x [temp.explicit]p2:
9029 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009030 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00009031 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00009032 TemplateSpecializationKind TSK
9033 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9034 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009035
Richard Smith0d923af2019-04-26 01:51:07 +00009036 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009037
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009038 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009039 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00009040 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009041 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00009042 PrevDecl = Record;
9043 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009044 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009045 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009046 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009047 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009048 PrevDecl,
9049 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009050 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009051 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009052 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00009053 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009054 return TagD;
9055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009056
Douglas Gregor12e49d32009-10-15 22:53:21 +00009057 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009058 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00009059 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00009060 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009061 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00009062 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009063 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009064 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00009065 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00009066 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9067 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00009068 Diag(Pattern->getLocation(), diag::note_forward_declaration)
9069 << Pattern;
9070 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009071 } else {
9072 if (InstantiateClass(NameLoc, Record, Def,
9073 getTemplateInstantiationArgs(Record),
9074 TSK))
9075 return true;
9076
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009077 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00009078 if (!RecordDef)
9079 return true;
9080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009081 }
9082
Douglas Gregor1d957a32009-10-27 18:42:08 +00009083 // Instantiate all of the members of the class.
9084 InstantiateClassMembers(NameLoc, RecordDef,
9085 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009086
Douglas Gregor88d292c2010-05-13 16:44:06 +00009087 if (TSK == TSK_ExplicitInstantiationDefinition)
9088 MarkVTableUsed(NameLoc, RecordDef, true);
9089
Mike Stump87c57ac2009-05-16 07:39:55 +00009090 // FIXME: We don't have any representation for explicit instantiations of
9091 // member classes. Such a representation is not needed for compilation, but it
9092 // should be available for clients that want to see all of the declarations in
9093 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009094 return TagD;
9095}
9096
John McCallfaf5fb42010-08-26 23:41:50 +00009097DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9098 SourceLocation ExternLoc,
9099 SourceLocation TemplateLoc,
9100 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009101 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009102 // TODO: check if/when DNInfo should replace Name.
9103 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9104 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00009105 if (!Name) {
9106 if (!D.isInvalidType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009107 Diag(D.getDeclSpec().getBeginLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009108 diag::err_explicit_instantiation_requires_name)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009109 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009110
Douglas Gregor450f00842009-09-25 18:43:00 +00009111 return true;
9112 }
9113
9114 // The scope passed in may not be a decl scope. Zip up the scope tree until
9115 // we find one that is.
9116 while ((S->getFlags() & Scope::DeclScope) == 0 ||
9117 (S->getFlags() & Scope::TemplateParamScope) != 0)
9118 S = S->getParent();
9119
9120 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00009121 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9122 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00009123 if (R.isNull())
9124 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009125
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009126 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00009127 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009128 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00009129 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009130 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9131 << Name;
9132 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009133 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009134 != DeclSpec::SCS_unspecified) {
9135 // Complain about then remove the storage class specifier.
9136 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9137 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009138
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009139 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00009140 }
9141
Douglas Gregor3c74d412009-10-14 20:14:33 +00009142 // C++0x [temp.explicit]p1:
9143 // [...] An explicit instantiation of a function template shall not use the
9144 // inline or constexpr specifiers.
9145 // Presumably, this also applies to member functions of class templates as
9146 // well.
Richard Smith83c19292011-10-18 03:44:03 +00009147 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009148 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009149 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00009150 diag::err_explicit_instantiation_inline :
9151 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00009152 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009153 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00009154 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9155 // not already specified.
9156 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9157 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009158
Richard Smith19a311a2017-02-09 22:47:51 +00009159 // A deduction guide is not on the list of entities that can be explicitly
9160 // instantiated.
9161 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009162 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9163 << /*explicit instantiation*/ 0;
Richard Smith19a311a2017-02-09 22:47:51 +00009164 return true;
9165 }
9166
Douglas Gregore47f5a72009-10-14 23:41:34 +00009167 // C++0x [temp.explicit]p2:
9168 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009169 // definition and an explicit instantiation declaration. An explicit
9170 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00009171 TemplateSpecializationKind TSK
9172 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9173 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009174
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009175 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00009176 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00009177
9178 if (!R->isFunctionType()) {
9179 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009180 // A [...] static data member of a class template can be explicitly
9181 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009182 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009183 // C++1y [temp.explicit]p1:
9184 // A [...] variable [...] template specialization can be explicitly
9185 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00009186 if (Previous.isAmbiguous())
9187 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009188
John McCall67c00872009-12-02 08:25:40 +00009189 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00009190 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009191
Larisse Voufo39a1e502013-08-06 01:03:05 +00009192 if (!PrevTemplate) {
9193 if (!Prev || !Prev->isStaticDataMember()) {
Richard Smitha6b41d72019-05-03 23:51:38 +00009194 // We expect to see a static data member here.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009195 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9196 << Name;
9197 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9198 P != PEnd; ++P)
9199 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9200 return true;
9201 }
9202
9203 if (!Prev->getInstantiatedFromStaticDataMember()) {
9204 // FIXME: Check for explicit specialization?
9205 Diag(D.getIdentifierLoc(),
9206 diag::err_explicit_instantiation_data_member_not_instantiated)
9207 << Prev;
9208 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9209 // FIXME: Can we provide a note showing where this was declared?
9210 return true;
9211 }
9212 } else {
9213 // Explicitly instantiate a variable template.
9214
9215 // C++1y [dcl.spec.auto]p6:
9216 // ... A program that uses auto or decltype(auto) in a context not
9217 // explicitly allowed in this section is ill-formed.
9218 //
9219 // This includes auto-typed variable template instantiations.
9220 if (R->isUndeducedType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009221 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009222 diag::err_auto_not_allowed_var_inst);
9223 return true;
9224 }
9225
Faisal Vali2ab8c152017-12-30 04:15:27 +00009226 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Richard Smithef985ac2013-09-18 02:10:12 +00009227 // C++1y [temp.explicit]p3:
9228 // If the explicit instantiation is for a variable, the unqualified-id
9229 // in the declaration shall be a template-id.
9230 Diag(D.getIdentifierLoc(),
9231 diag::err_explicit_instantiation_without_template_id)
9232 << PrevTemplate;
9233 Diag(PrevTemplate->getLocation(),
9234 diag::note_explicit_instantiation_here);
9235 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00009236 }
9237
Richard Smithef985ac2013-09-18 02:10:12 +00009238 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00009239 TemplateArgumentListInfo TemplateArgs =
9240 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00009241
Larisse Voufo39a1e502013-08-06 01:03:05 +00009242 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9243 D.getIdentifierLoc(), TemplateArgs);
9244 if (Res.isInvalid())
9245 return true;
9246
9247 // Ignore access control bits, we don't need them for redeclaration
9248 // checking.
9249 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00009250 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009251
Douglas Gregore47f5a72009-10-14 23:41:34 +00009252 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009253 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009254 // or a static data member of a class template specialization, the name of
9255 // the class template specialization in the qualified-id for the member
9256 // name shall be a simple-template-id.
9257 //
9258 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009259 //
Richard Smith5977d872013-09-18 21:55:14 +00009260 // This does not apply to variable template specializations, where the
9261 // template-id is in the unqualified-id instead.
9262 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009263 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009264 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009265 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009266
Richard Smith0d923af2019-04-26 01:51:07 +00009267 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009268
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009269 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00009270 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9271 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009272 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009273 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00009274 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009275 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009276
Larisse Voufo39a1e502013-08-06 01:03:05 +00009277 if (!HasNoEffect) {
9278 // Instantiate static data member or variable template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009279 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Louis Dionnee6e81752018-10-10 15:32:29 +00009280 // Merge attributes.
9281 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009282 if (TSK == TSK_ExplicitInstantiationDefinition)
9283 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9284 }
9285
9286 // Check the new variable specialization against the parsed input.
9287 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009288 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009289 diag::err_invalid_var_template_spec_type)
9290 << 0 << PrevTemplate << R << Prev->getType();
9291 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9292 << 2 << PrevTemplate->getDeclName();
9293 return true;
9294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009295
Douglas Gregor450f00842009-09-25 18:43:00 +00009296 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00009297 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009299
9300 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00009301 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00009302 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00009303 TemplateArgumentListInfo TemplateArgs;
Faisal Vali2ab8c152017-12-30 04:15:27 +00009304 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00009305 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00009306 HasExplicitTemplateArgs = true;
9307 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009308
Douglas Gregor450f00842009-09-25 18:43:00 +00009309 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009310 // A [...] function [...] can be explicitly instantiated from its template.
9311 // A member function [...] of a class template can be explicitly
9312 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009313 // template.
John McCall27c11dd2017-06-07 23:00:05 +00009314 UnresolvedSet<8> TemplateMatches;
9315 FunctionDecl *NonTemplateMatch = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009316 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00009317 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9318 P != PEnd; ++P) {
9319 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00009320 if (!HasExplicitTemplateArgs) {
9321 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00009322 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9323 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00009324 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
John McCall27c11dd2017-06-07 23:00:05 +00009325 if (Method->getPrimaryTemplate()) {
9326 TemplateMatches.addDecl(Method, P.getAccess());
9327 } else {
9328 // FIXME: Can this assert ever happen? Needs a test.
9329 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9330 NonTemplateMatch = Method;
9331 }
Douglas Gregord90fd522009-09-25 21:45:23 +00009332 }
Douglas Gregor450f00842009-09-25 18:43:00 +00009333 }
9334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009335
Douglas Gregor450f00842009-09-25 18:43:00 +00009336 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9337 if (!FunTmpl)
9338 continue;
9339
Larisse Voufo98b20f12013-07-19 23:00:19 +00009340 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00009341 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009342 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009343 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00009344 (HasExplicitTemplateArgs ? &TemplateArgs
9345 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00009346 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009347 // Keep track of almost-matches.
9348 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00009349 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009350 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00009351 (void)TDK;
9352 continue;
9353 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009354
Artem Belevich64135c32016-12-08 19:38:13 +00009355 // Target attributes are part of the cuda function signature, so
9356 // the cuda target of the instantiated function must match that of its
9357 // template. Given that C++ template deduction does not take
9358 // target attributes into account, we reject candidates here that
9359 // have a different target.
9360 if (LangOpts.CUDA &&
9361 IdentifyCUDATarget(Specialization,
9362 /* IgnoreImplicitHDAttributes = */ true) !=
Erich Keanec480f302018-07-12 21:09:05 +00009363 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
Artem Belevich64135c32016-12-08 19:38:13 +00009364 FailedCandidates.addCandidate().set(
9365 P.getPair(), FunTmpl->getTemplatedDecl(),
9366 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9367 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009368 }
9369
John McCall27c11dd2017-06-07 23:00:05 +00009370 TemplateMatches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00009371 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009372
John McCall27c11dd2017-06-07 23:00:05 +00009373 FunctionDecl *Specialization = NonTemplateMatch;
9374 if (!Specialization) {
9375 // Find the most specialized function template specialization.
9376 UnresolvedSetIterator Result = getMostSpecialized(
9377 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9378 D.getIdentifierLoc(),
9379 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9380 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9381 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00009382
John McCall27c11dd2017-06-07 23:00:05 +00009383 if (Result == TemplateMatches.end())
9384 return true;
John McCall58cc69d2010-01-27 01:50:18 +00009385
John McCall27c11dd2017-06-07 23:00:05 +00009386 // Ignore access control bits, we don't need them for redeclaration checking.
9387 Specialization = cast<FunctionDecl>(*Result);
9388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009389
Alexey Bataev73983912014-11-06 10:10:50 +00009390 // C++11 [except.spec]p4
9391 // In an explicit instantiation an exception-specification may be specified,
9392 // but is not required.
9393 // If an exception-specification is specified in an explicit instantiation
9394 // directive, it shall be compatible with the exception-specifications of
9395 // other declarations of that function.
9396 if (auto *FPT = R->getAs<FunctionProtoType>())
9397 if (FPT->hasExceptionSpec()) {
9398 unsigned DiagID =
9399 diag::err_mismatched_exception_spec_explicit_instantiation;
9400 if (getLangOpts().MicrosoftExt)
9401 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9402 bool Result = CheckEquivalentExceptionSpec(
9403 PDiag(DiagID) << Specialization->getType(),
9404 PDiag(diag::note_explicit_instantiation_here),
9405 Specialization->getType()->getAs<FunctionProtoType>(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009406 Specialization->getLocation(), FPT, D.getBeginLoc());
Alexey Bataev73983912014-11-06 10:10:50 +00009407 // In Microsoft mode, mismatching exception specifications just cause a
9408 // warning.
9409 if (!getLangOpts().MicrosoftExt && Result)
9410 return true;
9411 }
9412
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009413 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009414 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009415 diag::err_explicit_instantiation_member_function_not_instantiated)
9416 << Specialization
9417 << (Specialization->getTemplateSpecializationKind() ==
9418 TSK_ExplicitSpecialization);
9419 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9420 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009421 }
9422
Douglas Gregorec9fd132012-01-14 16:38:05 +00009423 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00009424 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9425 PrevDecl = Specialization;
9426
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009427 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00009428 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009429 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009430 PrevDecl,
9431 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009432 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009433 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009434 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009435
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009436 // FIXME: We may still want to build some representation of this
9437 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00009438 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00009439 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009440 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00009441
Richard Smith0d923af2019-04-26 01:51:07 +00009442 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
9443 // functions
9444 // valarray<size_t>::valarray(size_t) and
9445 // valarray<size_t>::~valarray()
9446 // that it declared to have internal linkage with the internal_linkage
9447 // attribute. Ignore the explicit instantiation declaration in this case.
9448 if (Specialization->hasAttr<InternalLinkageAttr>() &&
9449 TSK == TSK_ExplicitInstantiationDeclaration) {
9450 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
9451 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
9452 RD->isInStdNamespace())
9453 return (Decl*) nullptr;
9454 }
9455
Erich Keanec480f302018-07-12 21:09:05 +00009456 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009457
Hans Wennborgb8304a62017-11-29 23:44:11 +00009458 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9459 // instantiation declarations.
9460 if (TSK == TSK_ExplicitInstantiationDefinition &&
9461 Specialization->hasAttr<DLLImportAttr>() &&
9462 Context.getTargetInfo().getCXXABI().isMicrosoft())
9463 TSK = TSK_ExplicitInstantiationDeclaration;
9464
9465 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9466
Richard Smitheb36ddf2014-04-24 22:45:46 +00009467 if (Specialization->isDefined()) {
9468 // Let the ASTConsumer know that this function has been explicitly
9469 // instantiated now, and its linkage might have changed.
9470 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9471 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00009472 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009473
Douglas Gregore47f5a72009-10-14 23:41:34 +00009474 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009475 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009476 // or a static data member of a class template specialization, the name of
9477 // the class template specialization in the qualified-id for the member
9478 // name shall be a simple-template-id.
9479 //
9480 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009481 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Faisal Vali2ab8c152017-12-30 04:15:27 +00009482 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009483 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00009484 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009485 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009486 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009487 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009488
Richard Smith0d923af2019-04-26 01:51:07 +00009489 CheckExplicitInstantiation(
9490 *this,
9491 FunTmpl ? (NamedDecl *)FunTmpl
9492 : Specialization->getInstantiatedFromMemberFunction(),
9493 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009494
Douglas Gregor450f00842009-09-25 18:43:00 +00009495 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00009496 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009497}
9498
John McCallfaf5fb42010-08-26 23:41:50 +00009499TypeResult
Faisal Vali090da2d2018-01-01 18:23:28 +00009500Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
John McCall7f41d982009-09-11 04:59:25 +00009501 const CXXScopeSpec &SS, IdentifierInfo *Name,
9502 SourceLocation TagLoc, SourceLocation NameLoc) {
9503 // This has to hold, because SS is expected to be defined.
9504 assert(Name && "Expected a name in a dependent tag");
9505
Aaron Ballman4a979672014-01-03 13:56:08 +00009506 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009507 if (!NNS)
9508 return true;
9509
Abramo Bagnara6150c882010-05-11 21:36:43 +00009510 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009511
Douglas Gregorba41d012010-04-24 16:38:41 +00009512 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9513 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009514 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009515 return true;
9516 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009517
Douglas Gregore7c20652011-03-02 00:47:37 +00009518 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009519 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009520 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009521
Douglas Gregore7c20652011-03-02 00:47:37 +00009522 // Create type-source location information for this type.
9523 TypeLocBuilder TLB;
9524 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009525 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009526 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9527 TL.setNameLoc(NameLoc);
9528 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009529}
9530
John McCallfaf5fb42010-08-26 23:41:50 +00009531TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009532Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9533 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009534 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009535 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009536 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009537
Richard Smith0bf8a4922011-10-18 20:49:44 +00009538 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9539 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009540 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009541 diag::warn_cxx98_compat_typename_outside_of_template :
9542 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009543 << FixItHint::CreateRemoval(TypenameLoc);
9544
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009545 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009546 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9547 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009548 if (T.isNull())
9549 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009550
9551 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9552 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009553 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009554 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009555 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009556 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009557 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009558 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009559 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009560 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009561 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009563
John McCallba7bf592010-08-24 05:47:05 +00009564 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009565}
9566
John McCallfaf5fb42010-08-26 23:41:50 +00009567TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009568Sema::ActOnTypenameType(Scope *S,
9569 SourceLocation TypenameLoc,
9570 const CXXScopeSpec &SS,
9571 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009572 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009573 IdentifierInfo *TemplateII,
9574 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009575 SourceLocation LAngleLoc,
9576 ASTTemplateArgsPtr TemplateArgsIn,
9577 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009578 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9579 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009580 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009581 diag::warn_cxx98_compat_typename_outside_of_template :
9582 diag::ext_typename_outside_of_template)
9583 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009584
Richard Smith74f02342017-01-19 21:00:13 +00009585 // Strangely, non-type results are not ignored by this lookup, so the
9586 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009587 if (TypenameLoc.isValid()) {
9588 auto *LookupRD =
9589 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9590 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9591 Diag(TemplateIILoc,
9592 diag::ext_out_of_line_qualified_id_type_names_constructor)
9593 << TemplateII << 0 /*injected-class-name used as template name*/
9594 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9595 }
Richard Smith74f02342017-01-19 21:00:13 +00009596 }
9597
Douglas Gregorb09518c2011-02-27 22:46:49 +00009598 // Translate the parser's template argument list in our AST format.
9599 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9600 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009601
Douglas Gregorb09518c2011-02-27 22:46:49 +00009602 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009603 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9604 // Construct a dependent template specialization type.
9605 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009606 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009607 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9608 DTN->getQualifier(),
9609 DTN->getIdentifier(),
9610 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009611
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009612 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009613 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009614 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009615 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009616 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9617 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009618 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009619 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009620 SpecTL.setLAngleLoc(LAngleLoc);
9621 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009622 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9623 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009624 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009625 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009626
Richard Smith74f02342017-01-19 21:00:13 +00009627 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009628 if (T.isNull())
9629 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009630
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009631 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009632 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009633 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009634 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009635 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009636 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009637 SpecTL.setLAngleLoc(LAngleLoc);
9638 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009639 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9640 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009641
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009642 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9643 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009644 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009645 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009646
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009647 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9648 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009649}
9650
Douglas Gregorb09518c2011-02-27 22:46:49 +00009651
Richard Smith6f8d2c62012-05-09 05:17:00 +00009652/// Determine whether this failed name lookup should be treated as being
9653/// disabled by a usage of std::enable_if.
9654static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009655 SourceRange &CondRange, Expr *&Cond) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009656 // We must be looking for a ::type...
9657 if (!II.isStr("type"))
9658 return false;
9659
9660 // ... within an explicitly-written template specialization...
9661 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9662 return false;
9663 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009664 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9665 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9666 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009667 return false;
George Burgess IV00f70bd2018-03-01 05:43:23 +00009668 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009669
9670 // ... which names a complete class template declaration...
9671 const TemplateDecl *EnableIfDecl =
9672 EnableIfTST->getTemplateName().getAsTemplateDecl();
9673 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9674 return false;
9675
9676 // ... called "enable_if".
9677 const IdentifierInfo *EnableIfII =
9678 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9679 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9680 return false;
9681
9682 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009683 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009684
9685 // Dig out the condition.
9686 Cond = nullptr;
9687 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9688 != TemplateArgument::Expression)
9689 return true;
9690
9691 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9692
9693 // Ignore Boolean literals; they add no value.
9694 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9695 Cond = nullptr;
9696
Richard Smith6f8d2c62012-05-09 05:17:00 +00009697 return true;
9698}
9699
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009700/// Build the type that describes a C++ typename specifier,
Douglas Gregor333489b2009-03-27 23:10:48 +00009701/// e.g., "typename T::type".
9702QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009703Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009704 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009705 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009706 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009707 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009708 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009709 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009710
John McCall0b66eb32010-05-01 00:40:08 +00009711 DeclContext *Ctx = computeDeclContext(SS);
9712 if (!Ctx) {
9713 // If the nested-name-specifier is dependent and couldn't be
9714 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009715 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009716 return Context.getDependentNameType(Keyword,
9717 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009718 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009719 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009720
John McCall0b66eb32010-05-01 00:40:08 +00009721 // If the nested-name-specifier refers to the current instantiation,
9722 // the "typename" keyword itself is superfluous. In C++03, the
9723 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9724 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009725 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009726
John McCall0b66eb32010-05-01 00:40:08 +00009727 if (RequireCompleteDeclContext(SS, Ctx))
9728 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009729
9730 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009731 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009732 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009733 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009734 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009735 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009736 case LookupResult::NotFound: {
9737 // If we're looking up 'type' within a template named 'enable_if', produce
9738 // a more specific diagnostic.
9739 SourceRange CondRange;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009740 Expr *Cond = nullptr;
9741 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9742 // If we have a condition, narrow it down to the specific failed
9743 // condition.
9744 if (Cond) {
9745 Expr *FailedCond;
9746 std::string FailedDescription;
9747 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00009748 findFailedBooleanCondition(Cond);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009749
9750 Diag(FailedCond->getExprLoc(),
9751 diag::err_typename_nested_not_found_requirement)
9752 << FailedDescription
9753 << FailedCond->getSourceRange();
9754 return QualType();
9755 }
9756
Richard Smith6f8d2c62012-05-09 05:17:00 +00009757 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009758 << Ctx << CondRange;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009759 return QualType();
9760 }
9761
Douglas Gregore40876a2009-10-13 21:16:44 +00009762 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009763 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009764 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009765
9766 case LookupResult::FoundUnresolvedValue: {
9767 // We found a using declaration that is a value. Most likely, the using
9768 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009769 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009770 IILoc);
9771 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9772 << Name << Ctx << FullRange;
9773 if (UnresolvedUsingValueDecl *Using
9774 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009775 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009776 Diag(Loc, diag::note_using_value_decl_missing_typename)
9777 << FixItHint::CreateInsertion(Loc, "typename ");
9778 }
9779 }
9780 // Fall through to create a dependent typename type, from which we can recover
9781 // better.
Galina Kistanova3779cb32017-06-07 06:25:05 +00009782 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009783
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009784 case LookupResult::NotFoundInCurrentInstantiation:
9785 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009786 return Context.getDependentNameType(Keyword,
9787 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009788 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009789
9790 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009791 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009792 // C++ [class.qual]p2:
9793 // In a lookup in which function names are not ignored and the
9794 // nested-name-specifier nominates a class C, if the name specified
9795 // after the nested-name-specifier, when looked up in C, is the
9796 // injected-class-name of C [...] then the name is instead considered
9797 // to name the constructor of class C.
9798 //
9799 // Unlike in an elaborated-type-specifier, function names are not ignored
9800 // in typename-specifier lookup. However, they are ignored in all the
9801 // contexts where we form a typename type with no keyword (that is, in
9802 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9803 //
9804 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9805 // ignore functions, but that appears to be an oversight.
9806 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9807 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9808 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9809 FoundRD->isInjectedClassName() &&
9810 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9811 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9812 << &II << 1 << 0 /*'typename' keyword used*/;
9813
Abramo Bagnara6150c882010-05-11 21:36:43 +00009814 // We found a type. Build an ElaboratedType, since the
9815 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009816 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009817 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009818 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009819 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009820 }
9821
Richard Smithee579842017-01-30 20:39:26 +00009822 // C++ [dcl.type.simple]p2:
9823 // A type-specifier of the form
9824 // typename[opt] nested-name-specifier[opt] template-name
9825 // is a placeholder for a deduced class type [...].
Aaron Ballmanc351fba2017-12-04 20:27:34 +00009826 if (getLangOpts().CPlusPlus17) {
Richard Smithee579842017-01-30 20:39:26 +00009827 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9828 return Context.getElaboratedType(
9829 Keyword, QualifierLoc.getNestedNameSpecifier(),
9830 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9831 QualType(), false));
9832 }
9833 }
Richard Smith600b5262017-01-26 20:40:47 +00009834
Douglas Gregor333489b2009-03-27 23:10:48 +00009835 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009836 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009837 break;
9838
9839 case LookupResult::FoundOverloaded:
9840 DiagID = diag::err_typename_nested_not_type;
9841 Referenced = *Result.begin();
9842 break;
9843
John McCall6538c932009-10-10 05:48:19 +00009844 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009845 return QualType();
9846 }
9847
9848 // If we get here, it's because name lookup did not find a
9849 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009850 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009851 IILoc);
9852 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009853 if (Referenced)
9854 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9855 << Name;
9856 return QualType();
9857}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009858
9859namespace {
9860 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009861 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009862 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009863 SourceLocation Loc;
9864 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009865
Douglas Gregor15acfb92009-08-06 16:20:37 +00009866 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009867 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009868
Mike Stump11289f42009-09-09 15:08:12 +00009869 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009870 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009871 DeclarationName Entity)
9872 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009873 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009874
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009875 /// Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009876 /// transformed.
9877 ///
9878 /// For the purposes of type reconstruction, a type has already been
9879 /// transformed if it is NULL or if it is not dependent.
9880 bool AlreadyTransformed(QualType T) {
9881 return T.isNull() || !T->isDependentType();
9882 }
Mike Stump11289f42009-09-09 15:08:12 +00009883
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009884 /// Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009885 /// rebuilt.
9886 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009887
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009888 /// Returns the name of the entity whose type is being rebuilt.
Douglas Gregor15acfb92009-08-06 16:20:37 +00009889 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009890
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009891 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +00009892 /// information is known based on another transformation.
9893 void setBase(SourceLocation Loc, DeclarationName Entity) {
9894 this->Loc = Loc;
9895 this->Entity = Entity;
9896 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009897
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00009898 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9899 // Lambdas never need to be transformed.
9900 return E;
9901 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00009902 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009903} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00009904
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009905/// Rebuilds a type within the context of the current instantiation.
Douglas Gregor15acfb92009-08-06 16:20:37 +00009906///
Mike Stump11289f42009-09-09 15:08:12 +00009907/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00009908/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00009909/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00009910/// partial specialization thereof). This routine will rebuild that type now
9911/// that we have entered the declarator's scope, which may produce different
9912/// canonical types, e.g.,
9913///
9914/// \code
9915/// template<typename T>
9916/// struct X {
9917/// typedef T* pointer;
9918/// pointer data();
9919/// };
9920///
9921/// template<typename T>
9922/// typename X<T>::pointer X<T>::data() { ... }
9923/// \endcode
9924///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00009925/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009926/// since we do not know that we can look into X<T> when we parsed the type.
9927/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00009928/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00009929/// as the canonical type of T*, allowing the return types of the out-of-line
9930/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00009931TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9932 SourceLocation Loc,
9933 DeclarationName Name) {
9934 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00009935 return T;
Mike Stump11289f42009-09-09 15:08:12 +00009936
Douglas Gregor15acfb92009-08-06 16:20:37 +00009937 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9938 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00009939}
Douglas Gregorbe999392009-09-15 16:23:51 +00009940
John McCalldadc5752010-08-24 06:29:42 +00009941ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00009942 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9943 DeclarationName());
9944 return Rebuilder.TransformExpr(E);
9945}
9946
John McCall99b2fe52010-04-29 23:50:39 +00009947bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00009948 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009949 return true;
John McCall2408e322010-04-27 00:57:59 +00009950
Douglas Gregor10176412011-02-25 16:07:42 +00009951 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009952 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9953 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009954 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009955 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009956 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009957 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009958
Douglas Gregor10176412011-02-25 16:07:42 +00009959 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009960 return false;
John McCall2408e322010-04-27 00:57:59 +00009961}
9962
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009963/// Rebuild the template parameters now that we know we're in a current
Douglas Gregor041b0842011-10-14 15:31:12 +00009964/// instantiation.
9965bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9966 TemplateParameterList *Params) {
9967 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9968 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009969
Douglas Gregor041b0842011-10-14 15:31:12 +00009970 // There is nothing to rebuild in a type parameter.
9971 if (isa<TemplateTypeParmDecl>(Param))
9972 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009973
Douglas Gregor041b0842011-10-14 15:31:12 +00009974 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009975 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009976 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9977 if (RebuildTemplateParamsInCurrentInstantiation(
9978 TTP->getTemplateParameters()))
9979 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009980
Douglas Gregor041b0842011-10-14 15:31:12 +00009981 continue;
9982 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009983
Douglas Gregor041b0842011-10-14 15:31:12 +00009984 // Rebuild the type of a non-type template parameter.
9985 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009986 TypeSourceInfo *NewTSI
9987 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9988 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009989 NTTP->getDeclName());
9990 if (!NewTSI)
9991 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009992
Erik Pilkington9f9462a2018-08-07 22:59:02 +00009993 if (NewTSI->getType()->isUndeducedType()) {
9994 // C++17 [temp.dep.expr]p3:
9995 // An id-expression is type-dependent if it contains
9996 // - an identifier associated by name lookup with a non-type
9997 // template-parameter declared with a type that contains a
9998 // placeholder type (7.1.7.4),
9999 NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
10000 }
10001
Douglas Gregor041b0842011-10-14 15:31:12 +000010002 if (NewTSI != NTTP->getTypeSourceInfo()) {
10003 NTTP->setTypeSourceInfo(NewTSI);
10004 NTTP->setType(NewTSI->getType());
10005 }
10006 }
Simon Pilgrim6905d222016-12-30 22:55:33 +000010007
Douglas Gregor041b0842011-10-14 15:31:12 +000010008 return false;
10009}
10010
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010011/// Produces a formatted string that describes the binding of
Douglas Gregorbe999392009-09-15 16:23:51 +000010012/// template parameters to template arguments.
10013std::string
10014Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10015 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010016 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +000010017}
10018
10019std::string
10020Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10021 const TemplateArgument *Args,
10022 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000010023 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +000010024 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +000010025
Douglas Gregore62e6a02009-11-11 19:13:48 +000010026 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +000010027 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010028
Douglas Gregorbe999392009-09-15 16:23:51 +000010029 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +000010030 if (I >= NumArgs)
10031 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010032
Douglas Gregorbe999392009-09-15 16:23:51 +000010033 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +000010034 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +000010035 else
Douglas Gregor0192c232010-12-20 16:52:59 +000010036 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010037
Douglas Gregorbe999392009-09-15 16:23:51 +000010038 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +000010039 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +000010040 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +000010041 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +000010042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010043
Douglas Gregor0192c232010-12-20 16:52:59 +000010044 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +000010045 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +000010046 }
Douglas Gregor0192c232010-12-20 16:52:59 +000010047
10048 Out << ']';
10049 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +000010050}
Francois Pichet1c229c02011-04-22 22:18:13 +000010051
Richard Smithe40f2ba2013-08-07 21:41:30 +000010052void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
10053 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +000010054 if (!FD)
10055 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +000010056
Justin Lebar28f09c52016-10-10 16:26:08 +000010057 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +000010058
10059 // Take tokens to avoid allocations
10060 LPT->Toks.swap(Toks);
10061 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +000010062 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +000010063
10064 FD->setLateTemplateParsed(true);
10065}
10066
10067void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
10068 if (!FD)
10069 return;
10070 FD->setLateTemplateParsed(false);
10071}
Francois Pichet1c229c02011-04-22 22:18:13 +000010072
10073bool Sema::IsInsideALocalClassWithinATemplateFunction() {
10074 DeclContext *DC = CurContext;
10075
10076 while (DC) {
10077 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10078 const FunctionDecl *FD = RD->isLocalClass();
10079 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10080 } else if (DC->isTranslationUnit() || DC->isNamespace())
10081 return false;
10082
10083 DC = DC->getParent();
10084 }
10085 return false;
10086}
Richard Smith6739a102016-05-05 00:56:12 +000010087
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010088namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010089/// Walk the path from which a declaration was instantiated, and check
Richard Smith6739a102016-05-05 00:56:12 +000010090/// that every explicit specialization along that path is visible. This enforces
10091/// C++ [temp.expl.spec]/6:
10092///
10093/// If a template, a member template or a member of a class template is
10094/// explicitly specialized then that specialization shall be declared before
10095/// the first use of that specialization that would cause an implicit
10096/// instantiation to take place, in every translation unit in which such a
10097/// use occurs; no diagnostic is required.
10098///
10099/// and also C++ [temp.class.spec]/1:
10100///
10101/// A partial specialization shall be declared before the first use of a
10102/// class template specialization that would make use of the partial
10103/// specialization as the result of an implicit or explicit instantiation
10104/// in every translation unit in which such a use occurs; no diagnostic is
10105/// required.
10106class ExplicitSpecializationVisibilityChecker {
10107 Sema &S;
10108 SourceLocation Loc;
10109 llvm::SmallVector<Module *, 8> Modules;
10110
10111public:
10112 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10113 : S(S), Loc(Loc) {}
10114
10115 void check(NamedDecl *ND) {
10116 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10117 return checkImpl(FD);
10118 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10119 return checkImpl(RD);
10120 if (auto *VD = dyn_cast<VarDecl>(ND))
10121 return checkImpl(VD);
10122 if (auto *ED = dyn_cast<EnumDecl>(ND))
10123 return checkImpl(ED);
10124 }
10125
10126private:
10127 void diagnose(NamedDecl *D, bool IsPartialSpec) {
10128 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10129 : Sema::MissingImportKind::ExplicitSpecialization;
10130 const bool Recover = true;
10131
10132 // If we got a custom set of modules (because only a subset of the
10133 // declarations are interesting), use them, otherwise let
10134 // diagnoseMissingImport intelligently pick some.
10135 if (Modules.empty())
10136 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10137 else
10138 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10139 }
10140
10141 // Check a specific declaration. There are three problematic cases:
10142 //
10143 // 1) The declaration is an explicit specialization of a template
10144 // specialization.
10145 // 2) The declaration is an explicit specialization of a member of an
10146 // templated class.
10147 // 3) The declaration is an instantiation of a template, and that template
10148 // is an explicit specialization of a member of a templated class.
10149 //
10150 // We don't need to go any deeper than that, as the instantiation of the
10151 // surrounding class / etc is not triggered by whatever triggered this
10152 // instantiation, and thus should be checked elsewhere.
10153 template<typename SpecDecl>
10154 void checkImpl(SpecDecl *Spec) {
10155 bool IsHiddenExplicitSpecialization = false;
10156 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10157 IsHiddenExplicitSpecialization =
10158 Spec->getMemberSpecializationInfo()
10159 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
Richard Smith54f04402017-05-18 02:29:20 +000010160 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
Richard Smith6739a102016-05-05 00:56:12 +000010161 } else {
10162 checkInstantiated(Spec);
10163 }
10164
10165 if (IsHiddenExplicitSpecialization)
10166 diagnose(Spec->getMostRecentDecl(), false);
10167 }
10168
10169 void checkInstantiated(FunctionDecl *FD) {
10170 if (auto *TD = FD->getPrimaryTemplate())
10171 checkTemplate(TD);
10172 }
10173
10174 void checkInstantiated(CXXRecordDecl *RD) {
10175 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10176 if (!SD)
10177 return;
10178
10179 auto From = SD->getSpecializedTemplateOrPartial();
10180 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10181 checkTemplate(TD);
10182 else if (auto *TD =
10183 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10184 if (!S.hasVisibleDeclaration(TD))
10185 diagnose(TD, true);
10186 checkTemplate(TD);
10187 }
10188 }
10189
10190 void checkInstantiated(VarDecl *RD) {
10191 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10192 if (!SD)
10193 return;
10194
10195 auto From = SD->getSpecializedTemplateOrPartial();
10196 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10197 checkTemplate(TD);
10198 else if (auto *TD =
10199 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10200 if (!S.hasVisibleDeclaration(TD))
10201 diagnose(TD, true);
10202 checkTemplate(TD);
10203 }
10204 }
10205
10206 void checkInstantiated(EnumDecl *FD) {}
10207
10208 template<typename TemplDecl>
10209 void checkTemplate(TemplDecl *TD) {
10210 if (TD->isMemberSpecialization()) {
10211 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10212 diagnose(TD->getMostRecentDecl(), false);
10213 }
10214 }
10215};
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010216} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +000010217
10218void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10219 if (!getLangOpts().Modules)
10220 return;
10221
10222 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10223}
10224
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010225/// Check whether a template partial specialization that we've discovered
Richard Smith6739a102016-05-05 00:56:12 +000010226/// is hidden, and produce suitable diagnostics if so.
10227void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10228 NamedDecl *Spec) {
10229 llvm::SmallVector<Module *, 8> Modules;
10230 if (!hasVisibleDeclaration(Spec, &Modules))
10231 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10232 MissingImportKind::PartialSpecialization,
10233 /*Recover*/true);
10234}