blob: 2483a28b252f0dceb9017d9f7a9b2d53dd50ae23 [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,
Richard Smithb23c5e82019-05-09 03:31:27 +0000133 bool AllowDependent,
134 bool AllowNonTemplateFunctions) {
135 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000136 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000137 return true;
Richard Smithb23c5e82019-05-09 03:31:27 +0000138 if (AllowNonTemplateFunctions &&
139 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
140 return true;
141 }
Simon Pilgrim6905d222016-12-30 22:55:33 +0000142
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000143 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000144}
145
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000146TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000147 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000148 bool hasTemplateKeyword,
Richard Smithc08b6932018-04-27 02:00:13 +0000149 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000150 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000151 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000152 TemplateTy &TemplateResult,
153 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000154 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000155
Douglas Gregor3cf81312009-11-03 23:16:33 +0000156 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000157 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000158
Douglas Gregor3cf81312009-11-03 23:16:33 +0000159 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000160 case UnqualifiedIdKind::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000161 TName = DeclarationName(Name.Identifier);
162 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000163
Faisal Vali2ab8c152017-12-30 04:15:27 +0000164 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000165 TName = Context.DeclarationNames.getCXXOperatorName(
166 Name.OperatorFunctionId.Operator);
167 break;
168
Faisal Vali2ab8c152017-12-30 04:15:27 +0000169 case UnqualifiedIdKind::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000170 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
171 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000172
Douglas Gregor3cf81312009-11-03 23:16:33 +0000173 default:
174 return TNK_Non_template;
175 }
Mike Stump11289f42009-09-09 15:08:12 +0000176
John McCallba7bf592010-08-24 05:47:05 +0000177 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000178
Richard Smithb23c5e82019-05-09 03:31:27 +0000179 AssumedTemplateKind AssumedTemplate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000180 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000181 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
Richard Smithb23c5e82019-05-09 03:31:27 +0000182 MemberOfUnknownSpecialization, SourceLocation(),
183 &AssumedTemplate))
Richard Smith79810042018-05-11 02:43:08 +0000184 return TNK_Non_template;
Richard Smithb23c5e82019-05-09 03:31:27 +0000185
186 if (AssumedTemplate != AssumedTemplateKind::None) {
187 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
188 // Let the parser know whether we found nothing or found functions; if we
189 // found nothing, we want to more carefully check whether this is actually
190 // a function template name versus some other kind of undeclared identifier.
191 return AssumedTemplate == AssumedTemplateKind::FoundNothing
192 ? TNK_Undeclared_template
193 : TNK_Function_template;
194 }
195
196 if (R.empty())
197 return TNK_Non_template;
Richard Smith40bd10b2019-02-15 00:29:04 +0000198
Richard Smithafcfb6b2019-02-15 21:53:07 +0000199 NamedDecl *D = nullptr;
200 if (R.isAmbiguous()) {
201 // If we got an ambiguity involving a non-function template, treat this
202 // as a template name, and pick an arbitrary template for error recovery.
203 bool AnyFunctionTemplates = false;
204 for (NamedDecl *FoundD : R) {
205 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
206 if (isa<FunctionTemplateDecl>(FoundTemplate))
207 AnyFunctionTemplates = true;
208 else {
209 D = FoundTemplate;
210 break;
211 }
212 }
213 }
214
215 // If we didn't find any templates at all, this isn't a template name.
216 // Leave the ambiguity for a later lookup to diagnose.
217 if (!D && !AnyFunctionTemplates) {
218 R.suppressDiagnostics();
219 return TNK_Non_template;
220 }
221
222 // If the only templates were function templates, filter out the rest.
223 // We'll diagnose the ambiguity later.
224 if (!D)
225 FilterAcceptableTemplateNames(R);
John McCalldcc71402010-08-13 02:23:42 +0000226 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000227
Richard Smithafcfb6b2019-02-15 21:53:07 +0000228 // At this point, we have either picked a single template name declaration D
229 // or we have a non-empty set of results R containing either one template name
230 // declaration or a set of function templates.
231
John McCalld28ae272009-12-02 08:04:21 +0000232 TemplateName Template;
233 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000234
John McCalld28ae272009-12-02 08:04:21 +0000235 unsigned ResultCount = R.end() - R.begin();
Richard Smithafcfb6b2019-02-15 21:53:07 +0000236 if (!D && ResultCount > 1) {
John McCalld28ae272009-12-02 08:04:21 +0000237 // We assume that we'll preserve the qualifier from a function
238 // template name in other ways.
239 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
240 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000241
242 // We'll do this lookup again later.
243 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000244 } else {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000245 if (!D) {
246 D = getAsTemplateNameDecl(*R.begin());
247 assert(D && "unambiguous result is not a template name");
248 }
249
250 if (isa<UnresolvedUsingValueDecl>(D)) {
251 // We don't yet know whether this is a template-name or not.
252 MemberOfUnknownSpecialization = true;
253 return TNK_Non_template;
254 }
255
256 TemplateDecl *TD = cast<TemplateDecl>(D);
John McCalld28ae272009-12-02 08:04:21 +0000257
258 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000259 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000260 Template = Context.getQualifiedTemplateName(Qualifier,
261 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000262 } else {
263 Template = TemplateName(TD);
264 }
265
John McCalldcc71402010-08-13 02:23:42 +0000266 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000267 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000268
269 // We'll do this lookup again later.
270 R.suppressDiagnostics();
271 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000272 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000273 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
Faisal Valia534f072018-04-26 00:42:40 +0000274 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000275 TemplateKind =
Faisal Valia534f072018-04-26 00:42:40 +0000276 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000277 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000278 }
Mike Stump11289f42009-09-09 15:08:12 +0000279
John McCalld28ae272009-12-02 08:04:21 +0000280 TemplateResult = TemplateTy::make(Template);
281 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000282}
283
Richard Smith278890f2017-02-10 20:39:58 +0000284bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
285 SourceLocation NameLoc,
286 ParsedTemplateTy *Template) {
287 CXXScopeSpec SS;
288 bool MemberOfUnknownSpecialization = false;
289
290 // We could use redeclaration lookup here, but we don't need to: the
291 // syntactic form of a deduction guide is enough to identify it even
292 // if we can't look up the template name at all.
293 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000294 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
295 /*EnteringContext*/ false,
296 MemberOfUnknownSpecialization))
297 return false;
Richard Smith278890f2017-02-10 20:39:58 +0000298
299 if (R.empty()) return false;
300 if (R.isAmbiguous()) {
301 // FIXME: Diagnose an ambiguity if we find at least one template.
302 R.suppressDiagnostics();
303 return false;
304 }
305
306 // We only treat template-names that name type templates as valid deduction
307 // guide names.
308 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
309 if (!TD || !getAsTypeTemplateDecl(TD))
310 return false;
311
312 if (Template)
313 *Template = TemplateTy::make(TemplateName(TD));
314 return true;
315}
316
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000317bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000318 SourceLocation IILoc,
319 Scope *S,
320 const CXXScopeSpec *SS,
321 TemplateTy &SuggestedTemplate,
322 TemplateNameKind &SuggestedKind) {
323 // We can't recover unless there's a dependent scope specifier preceding the
324 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000325 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000326 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
327 computeDeclContext(*SS))
328 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000329
Douglas Gregor18473f32010-01-12 21:28:44 +0000330 // The code is missing a 'template' keyword prior to the dependent template
331 // name.
332 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
333 Diag(IILoc, diag::err_template_kw_missing)
334 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000335 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000336 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000337 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
338 SuggestedKind = TNK_Dependent_template_name;
339 return true;
340}
341
Richard Smith79810042018-05-11 02:43:08 +0000342bool Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000343 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000344 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000345 bool EnteringContext,
Richard Smith79810042018-05-11 02:43:08 +0000346 bool &MemberOfUnknownSpecialization,
Richard Smithb23c5e82019-05-09 03:31:27 +0000347 SourceLocation TemplateKWLoc,
348 AssumedTemplateKind *ATK) {
349 if (ATK)
350 *ATK = AssumedTemplateKind::None;
351
Richard Smithafcfb6b2019-02-15 21:53:07 +0000352 Found.setTemplateNameLookup(true);
353
John McCalle66edc12009-11-24 19:00:30 +0000354 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000355 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000356 DeclContext *LookupCtx = nullptr;
Richard Smith79810042018-05-11 02:43:08 +0000357 bool IsDependent = false;
John McCalle66edc12009-11-24 19:00:30 +0000358 if (!ObjectType.isNull()) {
359 // This nested-name-specifier occurs in a member access expression, e.g.,
360 // x->B::f, and we are looking into the type of the object.
361 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
362 LookupCtx = computeDeclContext(ObjectType);
Richard Smith79810042018-05-11 02:43:08 +0000363 IsDependent = !LookupCtx;
364 assert((IsDependent || !ObjectType->isIncompleteType() ||
Richard Smith5ed79562013-06-07 20:03:01 +0000365 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000366 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000367
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000368 // Template names cannot appear inside an Objective-C class or object type.
369 if (ObjectType->isObjCObjectOrInterfaceType()) {
370 Found.clear();
Richard Smith79810042018-05-11 02:43:08 +0000371 return false;
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000372 }
John McCalle66edc12009-11-24 19:00:30 +0000373 } else if (SS.isSet()) {
374 // This nested-name-specifier occurs after another nested-name-specifier,
375 // so long into the context associated with the prior nested-name-specifier.
376 LookupCtx = computeDeclContext(SS, EnteringContext);
Richard Smith79810042018-05-11 02:43:08 +0000377 IsDependent = !LookupCtx;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000378
John McCalle66edc12009-11-24 19:00:30 +0000379 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000380 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
Richard Smith79810042018-05-11 02:43:08 +0000381 return true;
John McCalle66edc12009-11-24 19:00:30 +0000382 }
383
384 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000385 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000386 if (LookupCtx) {
387 // Perform "qualified" name lookup into the declaration context we
388 // computed, which is either the type of the base of a member access
389 // expression or the declaration context associated with a prior
390 // nested-name-specifier.
391 LookupQualifiedName(Found, LookupCtx);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000392
Richard Smith79810042018-05-11 02:43:08 +0000393 // FIXME: The C++ standard does not clearly specify what happens in the
394 // case where the object type is dependent, and implementations vary. In
395 // Clang, we treat a name after a . or -> as a template-name if lookup
396 // finds a non-dependent member or member of the current instantiation that
397 // is a type template, or finds no such members and lookup in the context
398 // of the postfix-expression finds a type template. In the latter case, the
399 // name is nonetheless dependent, and we may resolve it to a member of an
400 // unknown specialization when we come to instantiate the template.
401 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
John McCalle66edc12009-11-24 19:00:30 +0000402 }
403
Richard Smith79810042018-05-11 02:43:08 +0000404 if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
405 // C++ [basic.lookup.classref]p1:
406 // In a class member access expression (5.2.5), if the . or -> token is
407 // immediately followed by an identifier followed by a <, the
408 // identifier must be looked up to determine whether the < is the
409 // beginning of a template argument list (14.2) or a less-than operator.
410 // The identifier is first looked up in the class of the object
411 // expression. If the identifier is not found, it is then looked up in
412 // the context of the entire postfix-expression and shall name a class
413 // template.
414 if (S)
415 LookupName(Found, S);
416
417 if (!ObjectType.isNull()) {
418 // FIXME: We should filter out all non-type templates here, particularly
419 // variable templates and concepts. But the exclusion of alias templates
420 // and template template parameters is a wording defect.
421 AllowFunctionTemplatesInLookup = false;
422 ObjectTypeSearchedInScope = true;
423 }
424
425 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
426 }
427
Richard Smithafcfb6b2019-02-15 21:53:07 +0000428 if (Found.isAmbiguous())
429 return false;
430
Richard Smithb23c5e82019-05-09 03:31:27 +0000431 if (ATK && !SS.isSet() && ObjectType.isNull() && TemplateKWLoc.isInvalid()) {
432 // C++2a [temp.names]p2:
433 // A name is also considered to refer to a template if it is an
434 // unqualified-id followed by a < and name lookup finds either one or more
435 // functions or finds nothing.
436 //
437 // To keep our behavior consistent, we apply the "finds nothing" part in
438 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
439 // successfully form a call to an undeclared template-id.
440 bool AllFunctions =
441 getLangOpts().CPlusPlus2a &&
442 std::all_of(Found.begin(), Found.end(), [](NamedDecl *ND) {
443 return isa<FunctionDecl>(ND->getUnderlyingDecl());
444 });
445 if (AllFunctions || (Found.empty() && !IsDependent)) {
446 // If lookup found any functions, or if this is a name that can only be
447 // used for a function, then strongly assume this is a function
448 // template-id.
449 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
450 ? AssumedTemplateKind::FoundNothing
451 : AssumedTemplateKind::FoundFunctions;
452 Found.clear();
453 return false;
454 }
455 }
456
Richard Smith79810042018-05-11 02:43:08 +0000457 if (Found.empty() && !IsDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000458 // If we did not find any names, attempt to correct any typos.
459 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000460 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000461 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Bruno Ricci70ad3962019-03-25 17:08:51 +0000462 DefaultFilterCCC FilterCCC{};
463 FilterCCC.WantTypeSpecifiers = false;
464 FilterCCC.WantExpressionKeywords = false;
465 FilterCCC.WantRemainingKeywords = false;
466 FilterCCC.WantCXXNamedCasts = true;
467 if (TypoCorrection Corrected =
468 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
469 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
Richard Smithde6d6c42015-12-29 19:43:10 +0000470 if (auto *ND = Corrected.getFoundDecl())
471 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000472 FilterAcceptableTemplateNames(Found);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000473 if (Found.isAmbiguous()) {
474 Found.clear();
475 } else if (!Found.empty()) {
Richard Smithb23c5e82019-05-09 03:31:27 +0000476 Found.setLookupName(Corrected.getCorrection());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000477 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000478 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
479 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000480 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000481 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
482 << Name << LookupCtx << DroppedSpecifier
483 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000484 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000485 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000486 }
John McCalle9cccd82010-06-16 08:42:20 +0000487 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000488 }
489 }
490
Richard Smith79810042018-05-11 02:43:08 +0000491 NamedDecl *ExampleLookupResult =
492 Found.empty() ? nullptr : Found.getRepresentativeDecl();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000493 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000494 if (Found.empty()) {
Richard Smith79810042018-05-11 02:43:08 +0000495 if (IsDependent) {
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000496 MemberOfUnknownSpecialization = true;
Richard Smith79810042018-05-11 02:43:08 +0000497 return false;
498 }
499
500 // If a 'template' keyword was used, a lookup that finds only non-template
501 // names is an error.
502 if (ExampleLookupResult && TemplateKWLoc.isValid()) {
503 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
504 << Found.getLookupName() << SS.getRange();
Richard Smithcbebd622018-05-14 20:52:48 +0000505 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
Richard Smith79810042018-05-11 02:43:08 +0000506 diag::note_template_kw_refers_to_non_template)
507 << Found.getLookupName();
508 return true;
509 }
510
511 return false;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000512 }
John McCalle66edc12009-11-24 19:00:30 +0000513
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000514 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000515 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000516 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000517 // [...] If the lookup in the class of the object expression finds a
518 // template, the name is also looked up in the context of the entire
519 // postfix-expression and [...]
520 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000521 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000522 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
523 LookupOrdinaryName);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000524 FoundOuter.setTemplateNameLookup(true);
John McCalle66edc12009-11-24 19:00:30 +0000525 LookupName(FoundOuter, S);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000526 // FIXME: We silently accept an ambiguous lookup here, in violation of
527 // [basic.lookup]/1.
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000528 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000529
Richard Smithafcfb6b2019-02-15 21:53:07 +0000530 NamedDecl *OuterTemplate;
John McCalle66edc12009-11-24 19:00:30 +0000531 if (FoundOuter.empty()) {
532 // - if the name is not found, the name found in the class of the
533 // object expression is used, otherwise
Richard Smithafcfb6b2019-02-15 21:53:07 +0000534 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
535 !(OuterTemplate =
536 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
John McCalle66edc12009-11-24 19:00:30 +0000537 // - if the name is found in the context of the entire
538 // postfix-expression and does not name a class template, the name
539 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000540 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000541 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000542 // - if the name found is a class template, it must refer to the same
543 // entity as the one found in the class of the object expression,
544 // otherwise the program is ill-formed.
545 if (!Found.isSingleResult() ||
Richard Smithafcfb6b2019-02-15 21:53:07 +0000546 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
547 OuterTemplate->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000548 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000549 diag::ext_nested_name_member_ref_lookup_ambiguous)
550 << Found.getLookupName()
551 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000552 Diag(Found.getRepresentativeDecl()->getLocation(),
553 diag::note_ambig_member_ref_object_type)
554 << ObjectType;
555 Diag(FoundOuter.getFoundDecl()->getLocation(),
556 diag::note_ambig_member_ref_scope);
557
558 // Recover by taking the template that we found in the object
559 // expression's type.
560 }
561 }
562 }
Richard Smith79810042018-05-11 02:43:08 +0000563
564 return false;
John McCalle66edc12009-11-24 19:00:30 +0000565}
566
Richard Smith42bc73a2017-05-10 02:30:28 +0000567void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
568 SourceLocation Less,
569 SourceLocation Greater) {
570 if (TemplateName.isInvalid())
571 return;
572
573 DeclarationNameInfo NameInfo;
574 CXXScopeSpec SS;
575 LookupNameKind LookupKind;
576
577 DeclContext *LookupCtx = nullptr;
578 NamedDecl *Found = nullptr;
Richard Smithbf5bcf22018-06-26 23:20:26 +0000579 bool MissingTemplateKeyword = false;
Richard Smith42bc73a2017-05-10 02:30:28 +0000580
581 // Figure out what name we looked up.
Richard Smithbf5bcf22018-06-26 23:20:26 +0000582 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
583 NameInfo = DRE->getNameInfo();
584 SS.Adopt(DRE->getQualifierLoc());
585 LookupKind = LookupOrdinaryName;
586 Found = DRE->getFoundDecl();
587 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000588 NameInfo = ME->getMemberNameInfo();
589 SS.Adopt(ME->getQualifierLoc());
590 LookupKind = LookupMemberName;
591 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
592 Found = ME->getMemberDecl();
Richard Smithbf5bcf22018-06-26 23:20:26 +0000593 } else if (auto *DSDRE =
594 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
595 NameInfo = DSDRE->getNameInfo();
596 SS.Adopt(DSDRE->getQualifierLoc());
597 MissingTemplateKeyword = true;
598 } else if (auto *DSME =
599 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
600 NameInfo = DSME->getMemberNameInfo();
601 SS.Adopt(DSME->getQualifierLoc());
602 MissingTemplateKeyword = true;
Richard Smith42bc73a2017-05-10 02:30:28 +0000603 } else {
Richard Smithbf5bcf22018-06-26 23:20:26 +0000604 llvm_unreachable("unexpected kind of potential template name");
605 }
606
607 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
608 // was missing.
609 if (MissingTemplateKeyword) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000610 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
611 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
Richard Smithbf5bcf22018-06-26 23:20:26 +0000612 return;
Richard Smith42bc73a2017-05-10 02:30:28 +0000613 }
614
615 // Try to correct the name by looking for templates and C++ named casts.
616 struct TemplateCandidateFilter : CorrectionCandidateCallback {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000617 Sema &S;
618 TemplateCandidateFilter(Sema &S) : S(S) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000619 WantTypeSpecifiers = false;
620 WantExpressionKeywords = false;
621 WantRemainingKeywords = false;
622 WantCXXNamedCasts = true;
623 };
624 bool ValidateCandidate(const TypoCorrection &Candidate) override {
625 if (auto *ND = Candidate.getCorrectionDecl())
Richard Smithafcfb6b2019-02-15 21:53:07 +0000626 return S.getAsTemplateNameDecl(ND);
Richard Smith42bc73a2017-05-10 02:30:28 +0000627 return Candidate.isKeyword();
628 }
Bruno Ricci70ad3962019-03-25 17:08:51 +0000629
630 std::unique_ptr<CorrectionCandidateCallback> clone() override {
631 return llvm::make_unique<TemplateCandidateFilter>(*this);
632 }
Richard Smith42bc73a2017-05-10 02:30:28 +0000633 };
634
635 DeclarationName Name = NameInfo.getName();
Bruno Ricci70ad3962019-03-25 17:08:51 +0000636 TemplateCandidateFilter CCC(*this);
637 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
638 CTK_ErrorRecovery, LookupCtx)) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000639 auto *ND = Corrected.getFoundDecl();
640 if (ND)
Richard Smithafcfb6b2019-02-15 21:53:07 +0000641 ND = getAsTemplateNameDecl(ND);
Richard Smith42bc73a2017-05-10 02:30:28 +0000642 if (ND || Corrected.isKeyword()) {
643 if (LookupCtx) {
644 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
645 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
646 Name.getAsString() == CorrectedStr;
647 diagnoseTypo(Corrected,
648 PDiag(diag::err_non_template_in_member_template_id_suggest)
649 << Name << LookupCtx << DroppedSpecifier
Richard Smith52f8d192017-05-10 21:32:16 +0000650 << SS.getRange(), false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000651 } else {
652 diagnoseTypo(Corrected,
653 PDiag(diag::err_non_template_in_template_id_suggest)
Richard Smith52f8d192017-05-10 21:32:16 +0000654 << Name, false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000655 }
656 if (Found)
657 Diag(Found->getLocation(),
658 diag::note_non_template_in_template_id_found);
659 return;
660 }
661 }
662
663 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
664 << Name << SourceRange(Less, Greater);
665 if (Found)
666 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
667}
668
John McCallcd4b4772009-12-02 03:53:29 +0000669/// ActOnDependentIdExpression - Handle a dependent id-expression that
670/// was just parsed. This is only possible with an explicit scope
671/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000672ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000673Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000674 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000675 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000676 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000677 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000678 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000679
Reid Kleckner1af391df2016-03-11 18:59:12 +0000680 // C++11 [expr.prim.general]p12:
681 // An id-expression that denotes a non-static data member or non-static
682 // member function of a class can only be used:
683 // (...)
684 // - if that id-expression denotes a non-static data member and it
685 // appears in an unevaluated operand.
686 //
687 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
688 // CXXDependentScopeMemberExpr. The former can instantiate to either
689 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
690 // always a MemberExpr.
691 bool MightBeCxx11UnevalField =
692 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
693
Akira Hatanakad644e022016-12-16 03:19:41 +0000694 // Check if the nested name specifier is an enum type.
695 bool IsEnum = false;
696 if (NestedNameSpecifier *NNS = SS.getScopeRep())
697 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
698
699 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000700 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
Brian Gesiak5488ab42019-01-11 01:54:53 +0000701 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000702
John McCalle66edc12009-11-24 19:00:30 +0000703 // Since the 'this' expression is synthesized, we don't need to
704 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000705 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000706
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000707 return CXXDependentScopeMemberExpr::Create(
708 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
709 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
710 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000711 }
712
Abramo Bagnara7945c982012-01-27 09:46:47 +0000713 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000714}
715
John McCalldadc5752010-08-24 06:29:42 +0000716ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000717Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000718 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000719 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000720 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000721 return DependentScopeDeclRefExpr::Create(
722 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
723 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000724}
725
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000726
727/// Determine whether we would be unable to instantiate this template (because
728/// it either has no definition, or is in the process of being instantiated).
729bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
730 NamedDecl *Instantiation,
731 bool InstantiatedFromMember,
732 const NamedDecl *Pattern,
733 const NamedDecl *PatternDef,
734 TemplateSpecializationKind TSK,
735 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000736 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
737 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000738
Richard Smithedbc6e92016-10-14 21:41:24 +0000739 bool IsEntityBeingDefined = false;
740 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
741 IsEntityBeingDefined = TD->isBeingDefined();
742
743 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000744 NamedDecl *SuggestedDef = nullptr;
745 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
746 /*OnlyNeedComplete*/false)) {
747 // If we're allowed to diagnose this and recover, do so.
748 bool Recover = Complain && !isSFINAEContext();
749 if (Complain)
750 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
751 Sema::MissingImportKind::Definition, Recover);
752 return !Recover;
753 }
754 return false;
755 }
756
Richard Smith6f4e2e02016-08-23 19:41:39 +0000757 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
758 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000759
Richard Smithedbc6e92016-10-14 21:41:24 +0000760 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000761 QualType InstantiationTy;
762 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
763 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000764 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000765 Diag(PointOfInstantiation,
766 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000767 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000768 << InstantiationTy;
769 // Not much point in noting the template declaration here, since
770 // we're lexically inside it.
771 Instantiation->setInvalidDecl();
772 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000773 if (isa<FunctionDecl>(Instantiation)) {
774 Diag(PointOfInstantiation,
775 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000776 << /*member function*/ 1 << Instantiation->getDeclName()
777 << Instantiation->getDeclContext();
778 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000779 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000780 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000781 Diag(PointOfInstantiation,
782 diag::err_implicit_instantiate_member_undefined)
783 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000784 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000785 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000786 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000787 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000788 Diag(PointOfInstantiation,
789 diag::err_explicit_instantiation_undefined_func_template)
790 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000791 Note = diag::note_explicit_instantiation_here;
792 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000793 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
794 << (TSK != TSK_ImplicitInstantiation)
795 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000796 Note = diag::note_template_decl_here;
797 } else {
798 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
799 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
800 Diag(PointOfInstantiation,
801 diag::err_explicit_instantiation_undefined_var_template)
802 << Instantiation;
803 Instantiation->setInvalidDecl();
804 } else
805 Diag(PointOfInstantiation,
806 diag::err_explicit_instantiation_undefined_member)
807 << /*static data member*/ 2 << Instantiation->getDeclName()
808 << Instantiation->getDeclContext();
809 Note = diag::note_explicit_instantiation_here;
810 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000811 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000812 if (Note) // Diagnostics were emitted.
813 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000814
815 // In general, Instantiation isn't marked invalid to get more than one
816 // error for multiple undefined instantiations. But the code that does
817 // explicit declaration -> explicit definition conversion can't handle
818 // invalid declarations, so mark as invalid in that case.
819 if (TSK == TSK_ExplicitInstantiationDeclaration)
820 Instantiation->setInvalidDecl();
821 return true;
822}
823
Douglas Gregor5101c242008-12-05 18:15:24 +0000824/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
825/// that the template parameter 'PrevDecl' is being shadowed by a new
826/// declaration at location Loc. Returns true to indicate that this is
827/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000828void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000829 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000830
831 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000832 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000833 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000834
835 // C++ [temp.local]p4:
836 // A template-parameter shall not be redeclared within its
837 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000838 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000839 << cast<NamedDecl>(PrevDecl)->getDeclName();
840 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000841}
842
Douglas Gregor463421d2009-03-03 04:44:36 +0000843/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000844/// the parameter D to reference the templated declaration and return a pointer
845/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000846TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
847 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
848 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000849 return Temp;
850 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000851 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000852}
853
Douglas Gregoreb29d182011-01-05 17:40:24 +0000854ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
855 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000856 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000857 "Only template template arguments can be pack expansions here");
858 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
859 "Template template argument pack expansion without packs");
860 ParsedTemplateArgument Result(*this);
861 Result.EllipsisLoc = EllipsisLoc;
862 return Result;
863}
864
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000865static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
866 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000867
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000868 switch (Arg.getKind()) {
869 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000870 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000871 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000872 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000873 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000874 return TemplateArgumentLoc(TemplateArgument(T), DI);
875 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000876
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000877 case ParsedTemplateArgument::NonType: {
878 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
879 return TemplateArgumentLoc(TemplateArgument(E), E);
880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000881
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000882 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000883 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000884 TemplateArgument TArg;
885 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000886 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000887 else
888 TArg = Template;
889 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000890 Arg.getScopeSpec().getWithLocInContext(
891 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000892 Arg.getLocation(),
893 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000894 }
895 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000896
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000897 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000898}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000899
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000900/// Translates template arguments as provided by the parser
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000901/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000902void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
903 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000904 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000905 TemplateArgs.addArgument(translateTemplateArgument(*this,
906 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000907}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000908
Richard Smithb80d5402013-06-25 22:21:36 +0000909static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
910 SourceLocation Loc,
911 IdentifierInfo *Name) {
912 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
Richard Smithbecb92d2017-10-10 22:33:17 +0000913 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
Richard Smithb80d5402013-06-25 22:21:36 +0000914 if (PrevDecl && PrevDecl->isTemplateParameter())
915 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
916}
917
Richard Smith77a9c602018-02-28 03:02:23 +0000918/// Convert a parsed type into a parsed template argument. This is mostly
919/// trivial, except that we may have parsed a C++17 deduced class template
920/// specialization type, in which case we should form a template template
921/// argument instead of a type template argument.
922ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
923 TypeSourceInfo *TInfo;
924 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
925 if (T.isNull())
926 return ParsedTemplateArgument();
927 assert(TInfo && "template argument with no location");
928
929 // If we might have formed a deduced template specialization type, convert
930 // it to a template template argument.
931 if (getLangOpts().CPlusPlus17) {
932 TypeLoc TL = TInfo->getTypeLoc();
933 SourceLocation EllipsisLoc;
934 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
935 EllipsisLoc = PET.getEllipsisLoc();
936 TL = PET.getPatternLoc();
937 }
938
939 CXXScopeSpec SS;
940 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
941 SS.Adopt(ET.getQualifierLoc());
942 TL = ET.getNamedTypeLoc();
943 }
944
945 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
946 TemplateName Name = DTST.getTypePtr()->getTemplateName();
947 if (SS.isSet())
948 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
949 /*HasTemplateKeyword*/ false,
950 Name.getAsTemplateDecl());
951 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
952 DTST.getTemplateNameLoc());
953 if (EllipsisLoc.isValid())
954 Result = Result.getTemplatePackExpansion(EllipsisLoc);
955 return Result;
956 }
957 }
958
959 // This is a normal type template argument. Note, if the type template
960 // argument is an injected-class-name for a template, it has a dual nature
Fangrui Song6907ce22018-07-30 19:24:48 +0000961 // and can be used as either a type or a template. We handle that in
Richard Smith77a9c602018-02-28 03:02:23 +0000962 // convertTypeTemplateArgumentToTemplate.
963 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
964 ParsedType.get().getAsOpaquePtr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000965 TInfo->getTypeLoc().getBeginLoc());
Richard Smith77a9c602018-02-28 03:02:23 +0000966}
967
Douglas Gregor5101c242008-12-05 18:15:24 +0000968/// ActOnTypeParameter - Called when a C++ template type parameter
969/// (e.g., "typename T") has been parsed. Typename specifies whether
970/// the keyword "typename" was used to declare the type parameter
971/// (otherwise, "class" was used), and KeyLoc is the location of the
972/// "class" or "typename" keyword. ParamName is the name of the
973/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000974/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000975/// If the type parameter has a default argument, it will be added
976/// later via ActOnTypeParameterDefault.
Faisal Valibe294032017-12-23 18:56:34 +0000977NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000978 SourceLocation EllipsisLoc,
979 SourceLocation KeyLoc,
980 IdentifierInfo *ParamName,
981 SourceLocation ParamNameLoc,
982 unsigned Depth, unsigned Position,
983 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000984 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000985 assert(S->isTemplateParamScope() &&
986 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000987
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000988 SourceLocation Loc = ParamNameLoc;
989 if (!ParamName)
990 Loc = KeyLoc;
991
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000992 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000993 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000994 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000995 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000996 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000997 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000998
999 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +00001000 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1001
Douglas Gregor5101c242008-12-05 18:15:24 +00001002 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +00001003 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +00001004 IdResolver.AddDecl(Param);
1005 }
1006
Douglas Gregorf5500772011-01-05 15:48:55 +00001007 // C++0x [temp.param]p9:
1008 // A default template-argument may be specified for any kind of
1009 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00001010 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +00001011 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +00001012 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +00001013 }
1014
Douglas Gregordc13ded2010-07-01 00:00:45 +00001015 // Handle the default argument, if provided.
1016 if (DefaultArg) {
1017 TypeSourceInfo *DefaultTInfo;
1018 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001019
Douglas Gregordc13ded2010-07-01 00:00:45 +00001020 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001021
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001022 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001023 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001024 UPPC_DefaultArgument))
1025 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001026
Douglas Gregordc13ded2010-07-01 00:00:45 +00001027 // Check the template argument itself.
1028 if (CheckTemplateArgument(Param, DefaultTInfo)) {
1029 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00001030 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001032
Richard Smith1469b912015-06-10 00:29:03 +00001033 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +00001034 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001035
John McCall48871652010-08-21 09:40:31 +00001036 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +00001037}
1038
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001039/// Check that the type of a non-type template parameter is
Douglas Gregor463421d2009-03-03 04:44:36 +00001040/// well-formed.
1041///
1042/// \returns the (possibly-promoted) parameter type if valid;
1043/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +00001044QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1045 SourceLocation Loc) {
1046 if (TSI->getType()->isUndeducedType()) {
Erik Pilkington9f9462a2018-08-07 22:59:02 +00001047 // C++17 [temp.dep.expr]p3:
Richard Smith15361a22016-12-28 06:27:18 +00001048 // An id-expression is type-dependent if it contains
1049 // - an identifier associated by name lookup with a non-type
1050 // template-parameter declared with a type that contains a
1051 // placeholder type (7.1.7.4),
1052 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
1053 }
1054
1055 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1056}
1057
1058QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1059 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +00001060 // We don't allow variably-modified types as the type of non-type template
1061 // parameters.
1062 if (T->isVariablyModifiedType()) {
1063 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1064 << T;
1065 return QualType();
1066 }
1067
Douglas Gregor463421d2009-03-03 04:44:36 +00001068 // C++ [temp.param]p4:
1069 //
1070 // A non-type template-parameter shall have one of the following
1071 // (optionally cv-qualified) types:
1072 //
1073 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +00001074 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001075 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +00001076 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001077 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +00001078 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001079 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +00001080 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001081 // -- std::nullptr_t.
1082 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +00001083 // If T is a dependent type, we can't do the check now, so we
1084 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +00001085 T->isDependentType() ||
1086 // Allow use of auto in template parameter declarations.
1087 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +00001088 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1089 // are ignored when determining its type.
1090 return T.getUnqualifiedType();
1091 }
1092
Douglas Gregor463421d2009-03-03 04:44:36 +00001093 // C++ [temp.param]p8:
1094 //
1095 // A non-type template-parameter of type "array of T" or
1096 // "function returning T" is adjusted to be of type "pointer to
1097 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +00001098 else if (T->isArrayType() || T->isFunctionType())
1099 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001100
Douglas Gregor463421d2009-03-03 04:44:36 +00001101 Diag(Loc, diag::err_template_nontype_parm_bad_type)
1102 << T;
1103
1104 return QualType();
1105}
1106
Faisal Valibe294032017-12-23 18:56:34 +00001107NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
John McCall48871652010-08-21 09:40:31 +00001108 unsigned Depth,
1109 unsigned Position,
1110 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +00001111 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +00001112 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +00001113
Faisal Valia223d1c2017-12-22 03:50:55 +00001114 // Check that we have valid decl-specifiers specified.
1115 auto CheckValidDeclSpecifiers = [this, &D] {
1116 // C++ [temp.param]
Fangrui Song6907ce22018-07-30 19:24:48 +00001117 // p1
Malcolm Parsonsfab36802018-04-16 08:31:08 +00001118 // template-parameter:
1119 // ...
1120 // parameter-declaration
Fangrui Song6907ce22018-07-30 19:24:48 +00001121 // p2
Faisal Valia223d1c2017-12-22 03:50:55 +00001122 // ... A storage class shall not be specified in a template-parameter
1123 // declaration.
Fangrui Song6907ce22018-07-30 19:24:48 +00001124 // [dcl.typedef]p1:
Faisal Valia223d1c2017-12-22 03:50:55 +00001125 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1126 // of a parameter-declaration
1127 const DeclSpec &DS = D.getDeclSpec();
1128 auto EmitDiag = [this](SourceLocation Loc) {
1129 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1130 << FixItHint::CreateRemoval(Loc);
1131 };
1132 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1133 EmitDiag(DS.getStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001134
Sam McCall1371cba2017-12-22 07:09:51 +00001135 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
Faisal Valia223d1c2017-12-22 03:50:55 +00001136 EmitDiag(DS.getThreadStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001137
1138 // [dcl.inline]p1:
1139 // The inline specifier can be applied only to the declaration or
Faisal Valia223d1c2017-12-22 03:50:55 +00001140 // definition of a variable or function.
Fangrui Song6907ce22018-07-30 19:24:48 +00001141
Faisal Valia223d1c2017-12-22 03:50:55 +00001142 if (DS.isInlineSpecified())
1143 EmitDiag(DS.getInlineSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001144
Faisal Valia223d1c2017-12-22 03:50:55 +00001145 // [dcl.constexpr]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00001146 // The constexpr specifier shall be applied only to the definition of a
1147 // variable or variable template or the declaration of a function or
Faisal Valia223d1c2017-12-22 03:50:55 +00001148 // function template.
Fangrui Song6907ce22018-07-30 19:24:48 +00001149
Faisal Valia223d1c2017-12-22 03:50:55 +00001150 if (DS.isConstexprSpecified())
1151 EmitDiag(DS.getConstexprSpecLoc());
1152
1153 // [dcl.fct.spec]p1:
1154 // Function-specifiers can be used only in function declarations.
1155
1156 if (DS.isVirtualSpecified())
1157 EmitDiag(DS.getVirtualSpecLoc());
1158
Richard Smith76b90272019-05-09 03:59:21 +00001159 if (DS.hasExplicitSpecifier())
Faisal Valia223d1c2017-12-22 03:50:55 +00001160 EmitDiag(DS.getExplicitSpecLoc());
1161
1162 if (DS.isNoreturnSpecified())
1163 EmitDiag(DS.getNoreturnSpecLoc());
1164 };
1165
1166 CheckValidDeclSpecifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00001167
Richard Smith15361a22016-12-28 06:27:18 +00001168 if (TInfo->getType()->isUndeducedType()) {
1169 Diag(D.getIdentifierLoc(),
1170 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1171 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1172 }
Douglas Gregor5101c242008-12-05 18:15:24 +00001173
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001174 assert(S->isTemplateParamScope() &&
1175 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +00001176 bool Invalid = false;
1177
Richard Smith15361a22016-12-28 06:27:18 +00001178 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001179 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001180 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +00001181 Invalid = true;
1182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001183
Richard Smithb80d5402013-06-25 22:21:36 +00001184 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001185 bool IsParameterPack = D.hasEllipsis();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001186 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1187 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1188 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1189 TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001190 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +00001191
Douglas Gregor5101c242008-12-05 18:15:24 +00001192 if (Invalid)
1193 Param->setInvalidDecl();
1194
Richard Smithb80d5402013-06-25 22:21:36 +00001195 if (ParamName) {
1196 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1197 ParamName);
1198
Douglas Gregor5101c242008-12-05 18:15:24 +00001199 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +00001200 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +00001201 IdResolver.AddDecl(Param);
1202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001203
Douglas Gregorf5500772011-01-05 15:48:55 +00001204 // C++0x [temp.param]p9:
1205 // A default template-argument may be specified for any kind of
1206 // template-parameter that is not a template parameter pack.
1207 if (Default && IsParameterPack) {
1208 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +00001209 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +00001210 }
1211
Douglas Gregordc13ded2010-07-01 00:00:45 +00001212 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001213 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001214 // Check for unexpanded parameter packs.
1215 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1216 return Param;
1217
Douglas Gregordc13ded2010-07-01 00:00:45 +00001218 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +00001219 ExprResult DefaultRes =
1220 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +00001221 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +00001222 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00001223 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001224 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001225 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001226
Richard Smith1469b912015-06-10 00:29:03 +00001227 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +00001228 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001229
John McCall48871652010-08-21 09:40:31 +00001230 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +00001231}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001232
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001233/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +00001234/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001235/// has been parsed. S is the current scope.
Faisal Valibe294032017-12-23 18:56:34 +00001236NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
John McCall48871652010-08-21 09:40:31 +00001237 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00001238 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +00001239 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +00001240 IdentifierInfo *Name,
1241 SourceLocation NameLoc,
1242 unsigned Depth,
1243 unsigned Position,
1244 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +00001245 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001246 assert(S->isTemplateParamScope() &&
1247 "Template template parameter not in template parameter scope!");
1248
1249 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +00001250 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001251 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +00001252 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001253 NameLoc.isInvalid()? TmpLoc : NameLoc,
1254 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +00001255 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001256 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001257
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001258 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +00001259 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001260 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +00001261 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1262
John McCall48871652010-08-21 09:40:31 +00001263 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001264 IdResolver.AddDecl(Param);
1265 }
1266
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001267 if (Params->size() == 0) {
1268 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1269 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1270 Param->setInvalidDecl();
1271 }
1272
Douglas Gregorf5500772011-01-05 15:48:55 +00001273 // C++0x [temp.param]p9:
1274 // A default template-argument may be specified for any kind of
1275 // template-parameter that is not a template parameter pack.
1276 if (IsParameterPack && !Default.isInvalid()) {
1277 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1278 Default = ParsedTemplateArgument();
1279 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001280
Douglas Gregordc13ded2010-07-01 00:00:45 +00001281 if (!Default.isInvalid()) {
1282 // Check only that we have a template template argument. We don't want to
1283 // try to check well-formedness now, because our template template parameter
1284 // might have dependent types in its template parameters, which we wouldn't
1285 // be able to match now.
1286 //
1287 // If none of the template template parameter's template arguments mention
1288 // other template parameters, we could actually perform more checking here.
1289 // However, it isn't worth doing.
1290 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1291 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +00001292 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +00001293 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00001294 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001295 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001296
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001297 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001298 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001299 DefaultArg.getArgument().getAsTemplate(),
1300 UPPC_DefaultArgument))
1301 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001302
Richard Smith1469b912015-06-10 00:29:03 +00001303 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +00001304 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001305
John McCall48871652010-08-21 09:40:31 +00001306 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +00001307}
1308
Hubert Tongf608c052016-04-29 18:05:37 +00001309/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1310/// constrained by RequiresClause, that contains the template parameters in
1311/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +00001312TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001313Sema::ActOnTemplateParameterList(unsigned Depth,
1314 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001315 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001316 SourceLocation LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001317 ArrayRef<NamedDecl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001318 SourceLocation RAngleLoc,
1319 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001320 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001321 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001322
David Majnemer902f8c62015-12-27 07:16:27 +00001323 return TemplateParameterList::Create(
1324 Context, TemplateLoc, LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001325 llvm::makeArrayRef(Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001326 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001327}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001328
Bruno Ricci4224c872018-12-21 14:35:24 +00001329static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1330 const CXXScopeSpec &SS) {
John McCall3e11ebe2010-03-15 10:12:16 +00001331 if (SS.isSet())
Bruno Ricci4224c872018-12-21 14:35:24 +00001332 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
John McCall3e11ebe2010-03-15 10:12:16 +00001333}
1334
Erich Keanec480f302018-07-12 21:09:05 +00001335DeclResult Sema::CheckClassTemplate(
1336 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1337 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1338 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1339 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1340 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1341 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001342 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001343 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001344 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001345 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001346
1347 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001348 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001349 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001350
Abramo Bagnara6150c882010-05-11 21:36:43 +00001351 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1352 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001353
1354 // There is no such thing as an unnamed class template.
1355 if (!Name) {
1356 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001357 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001358 }
1359
Richard Smith6483d222012-04-21 01:27:54 +00001360 // Find any previous declaration with this name. For a friend with no
1361 // scope explicitly specified, we only look for tag declarations (per
1362 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001363 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001364 LookupResult Previous(*this, Name, NameLoc,
1365 (SS.isEmpty() && TUK == TUK_Friend)
1366 ? LookupTagName : LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001367 forRedeclarationInCurContext());
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001368 if (SS.isNotEmpty() && !SS.isInvalid()) {
1369 SemanticContext = computeDeclContext(SS, true);
1370 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001371 // FIXME: Horrible, horrible hack! We can't currently represent this
1372 // in the AST, and historically we have just ignored such friend
1373 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001374 Diag(NameLoc, TUK == TUK_Friend
1375 ? diag::warn_template_qualified_friend_ignored
1376 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001377 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001378 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001379 }
Mike Stump11289f42009-09-09 15:08:12 +00001380
John McCall0b66eb32010-05-01 00:40:08 +00001381 if (RequireCompleteDeclContext(SS, SemanticContext))
1382 return true;
1383
Simon Pilgrim6905d222016-12-30 22:55:33 +00001384 // If we're adding a template to a dependent context, we may need to
1385 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001386 // now that we know what the current instantiation is.
1387 if (SemanticContext->isDependentContext()) {
1388 ContextRAII SavedContext(*this, SemanticContext);
1389 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1390 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001391 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
Richard Smithc660c8f2018-03-16 13:36:56 +00001392 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
Richard Smith6483d222012-04-21 01:27:54 +00001393
John McCall27b18f82009-11-17 02:14:36 +00001394 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001395 } else {
1396 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001397
1398 // C++14 [class.mem]p14:
1399 // If T is the name of a class, then each of the following shall have a
1400 // name different from T:
1401 // -- every member template of class T
1402 if (TUK != TUK_Friend &&
1403 DiagnoseClassNameShadow(SemanticContext,
1404 DeclarationNameInfo(Name, NameLoc)))
1405 return true;
1406
John McCall27b18f82009-11-17 02:14:36 +00001407 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001408 }
Mike Stump11289f42009-09-09 15:08:12 +00001409
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001410 if (Previous.isAmbiguous())
1411 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001412
Craig Topperc3ec1492014-05-26 06:22:03 +00001413 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001414 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001415 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001416
Serge Pavlove50bf752016-06-10 04:39:07 +00001417 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1418 // Maybe we will complain about the shadowed template parameter.
1419 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1420 // Just pretend that we didn't see the previous declaration.
1421 PrevDecl = nullptr;
1422 }
1423
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001424 // If there is a previous declaration with the same name, check
1425 // whether this is a valid redeclaration.
Richard Smithbecb92d2017-10-10 22:33:17 +00001426 ClassTemplateDecl *PrevClassTemplate =
1427 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001428
1429 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001430 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001431 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001432 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001433 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1434 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001435 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001436 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1437 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1438 PrevClassTemplate
1439 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1440 ->getSpecializedTemplate();
1441 }
1442 }
1443
John McCalld43784f2009-12-18 11:25:59 +00001444 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001445 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001446 // [...] When looking for a prior declaration of a class or a function
1447 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001448 // function is neither a qualified name nor a template-id, scopes outside
1449 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001450 if (!SS.isSet()) {
1451 DeclContext *OutermostContext = CurContext;
1452 while (!OutermostContext->isFileContext())
1453 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001454
Richard Smith61e582f2012-04-20 07:12:26 +00001455 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001456 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1457 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1458 SemanticContext = PrevDecl->getDeclContext();
1459 } else {
1460 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001461 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001462 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001463 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001464 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001465
1466 // Check that the chosen semantic context doesn't already contain a
1467 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001468 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001469 DeclContext *LookupContext = SemanticContext;
1470 while (LookupContext->isTransparentContext())
1471 LookupContext = LookupContext->getLookupParent();
1472 LookupQualifiedName(Previous, LookupContext);
1473
1474 if (Previous.isAmbiguous())
1475 return true;
1476
1477 if (Previous.begin() != Previous.end())
1478 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001479 }
John McCall90d3bb92009-12-17 23:21:11 +00001480 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001481 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001482 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1483 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001484 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485
Richard Smithfc805ca2015-07-06 04:43:58 +00001486 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1487 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1488 if (SS.isEmpty() &&
1489 !(PrevClassTemplate &&
1490 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1491 SemanticContext->getRedeclContext()))) {
1492 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1493 Diag(Shadow->getTargetDecl()->getLocation(),
1494 diag::note_using_decl_target);
1495 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1496 // Recover by ignoring the old declaration.
1497 PrevDecl = PrevClassTemplate = nullptr;
1498 }
1499 }
1500
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001501 // TODO Memory management; associated constraints are not always stored.
1502 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1503
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001504 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001505 // Ensure that the template parameter lists are compatible. Skip this check
1506 // for a friend in a dependent context: the template parameter list itself
1507 // could be dependent.
1508 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1509 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001510 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001511 /*Complain=*/true,
1512 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001513 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001514
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001515 // Check for matching associated constraints on redeclarations.
1516 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1517 const bool RedeclACMismatch = [&] {
1518 if (!(CurAC || PrevAC))
1519 return false; // Nothing to check; no mismatch.
1520 if (CurAC && PrevAC) {
1521 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1522 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1523 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1524 if (CurACInfo == PrevACInfo)
1525 return false; // All good; no mismatch.
1526 }
1527 return true;
1528 }();
1529
1530 if (RedeclACMismatch) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001531 Diag(CurAC ? CurAC->getBeginLoc() : NameLoc,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001532 diag::err_template_different_associated_constraints);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001533 Diag(PrevAC ? PrevAC->getBeginLoc() : PrevClassTemplate->getLocation(),
1534 diag::note_template_prev_declaration)
1535 << /*declaration*/ 0;
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001536 return true;
1537 }
1538
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001539 // C++ [temp.class]p4:
1540 // In a redeclaration, partial specialization, explicit
1541 // specialization or explicit instantiation of a class template,
1542 // the class-key shall agree in kind with the original class
1543 // template declaration (7.1.5.3).
1544 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001545 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001546 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001547 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001548 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001549 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001550 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001551 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001552 }
1553
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001554 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001555 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001556 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001557 // If we have a prior definition that is not visible, treat this as
1558 // simply making that previous definition visible.
1559 NamedDecl *Hidden = nullptr;
1560 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001561 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00001562 SkipBody->Previous = Def;
Richard Smithbe3980b2015-03-27 00:41:57 +00001563 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1564 assert(Tmpl && "original definition of a class template is not a "
1565 "class template?");
Richard Smith858e0e02017-05-11 23:11:16 +00001566 makeMergedDefinitionVisible(Hidden);
1567 makeMergedDefinitionVisible(Tmpl);
Richard Smithc4577662018-09-12 02:13:47 +00001568 } else {
1569 Diag(NameLoc, diag::err_redefinition) << Name;
1570 Diag(Def->getLocation(), diag::note_previous_definition);
1571 // FIXME: Would it make sense to try to "forget" the previous
1572 // definition, as part of error recovery?
1573 return true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001574 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001575 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001576 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001577 } else if (PrevDecl) {
1578 // C++ [temp]p5:
1579 // A class template shall not have the same name as any other
1580 // template, class, function, object, enumeration, enumerator,
1581 // namespace, or type in the same scope (3.3), except as specified
1582 // in (14.5.4).
1583 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1584 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001585 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001586 }
1587
Douglas Gregordba32632009-02-10 19:49:53 +00001588 // Check the template parameter list of this declaration, possibly
1589 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001590 // template declaration. Skip this check for a friend in a dependent
1591 // context, because the template parameter list might be dependent.
1592 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001593 CheckTemplateParameterList(
1594 TemplateParams,
Richard Smithc4577662018-09-12 02:13:47 +00001595 PrevClassTemplate
1596 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1597 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001598 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1599 SemanticContext->isDependentContext())
1600 ? TPC_ClassTemplateMember
Richard Smithc4577662018-09-12 02:13:47 +00001601 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1602 SkipBody))
Douglas Gregordba32632009-02-10 19:49:53 +00001603 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001604
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001605 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001606 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001607 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001608 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1609 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001610 : diag::err_member_decl_does_not_match)
1611 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001612 Invalid = true;
1613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001614 }
1615
Vassil Vassilev352e4412017-01-12 09:16:26 +00001616 // If this is a templated friend in a dependent context we should not put it
1617 // on the redecl chain. In some cases, the templated friend can be the most
1618 // recent declaration tricking the template instantiator to make substitutions
1619 // there.
1620 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1621 bool ShouldAddRedecl
1622 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1623
Mike Stump11289f42009-09-09 15:08:12 +00001624 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001625 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001626 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001627 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001628 /*DelayTypeCreation=*/true);
Bruno Ricci4224c872018-12-21 14:35:24 +00001629 SetNestedNameSpecifier(*this, NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001630 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001631 NewClass->setTemplateParameterListsInfo(
1632 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1633 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001634
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001635 // Add alignment attributes if necessary; these attributes are checked when
1636 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00001637 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Eli Friedman0415f3e12012-08-08 21:08:34 +00001638 AddAlignmentAttributesForRecord(NewClass);
1639 AddMsStructLayoutForRecord(NewClass);
1640 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001641
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001642 // Attach the associated constraints when the declaration will not be part of
1643 // a decl chain.
1644 Expr *const ACtoAttach =
1645 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1646
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001647 ClassTemplateDecl *NewTemplate
1648 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1649 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001650 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001651
1652 if (ShouldAddRedecl)
1653 NewTemplate->setPreviousDecl(PrevClassTemplate);
1654
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001655 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001656
Douglas Gregor21823bf2011-12-20 18:11:52 +00001657 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001658 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001659
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001660 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001661 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001662 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001663 assert(T->isDependentType() && "Class template type is not dependent?");
1664 (void)T;
1665
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001666 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001667 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001668 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001669 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1670 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001671
Anders Carlsson137108d2009-03-26 01:24:28 +00001672 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001673 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001674 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001675
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001676 // Set the lexical context of these templates
1677 NewClass->setLexicalDeclContext(CurContext);
1678 NewTemplate->setLexicalDeclContext(CurContext);
1679
Richard Smithc4577662018-09-12 02:13:47 +00001680 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001681 NewClass->startDefinition();
1682
Erich Keanec480f302018-07-12 21:09:05 +00001683 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001684
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001685 if (PrevClassTemplate)
1686 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1687
Rafael Espindola385c0422012-07-13 18:04:45 +00001688 AddPushedVisibilityAttribute(NewClass);
1689
Richard Smith234ff472014-08-23 00:49:01 +00001690 if (TUK != TUK_Friend) {
1691 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1692 Scope *Outer = S;
1693 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1694 Outer = Outer->getParent();
1695 PushOnScopeChains(NewTemplate, Outer);
1696 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001697 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001698 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001699 NewClass->setAccess(PrevClassTemplate->getAccess());
1700 }
John McCall27b5c252009-09-14 21:59:20 +00001701
Richard Smith64017682013-07-17 23:53:16 +00001702 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001703
John McCall27b5c252009-09-14 21:59:20 +00001704 // Friend templates are visible in fairly strange ways.
1705 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001706 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001707 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001708 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1709 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001710 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001712
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001713 FriendDecl *Friend = FriendDecl::Create(
1714 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001715 Friend->setAccess(AS_public);
1716 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001717 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001718
Richard Smithbecb92d2017-10-10 22:33:17 +00001719 if (PrevClassTemplate)
1720 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1721
Douglas Gregordba32632009-02-10 19:49:53 +00001722 if (Invalid) {
1723 NewTemplate->setInvalidDecl();
1724 NewClass->setInvalidDecl();
1725 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001726
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001727 ActOnDocumentableDecl(NewTemplate);
1728
Richard Smithc4577662018-09-12 02:13:47 +00001729 if (SkipBody && SkipBody->ShouldSkip)
1730 return SkipBody->Previous;
1731
John McCall48871652010-08-21 09:40:31 +00001732 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001733}
1734
Richard Smith32918772017-02-14 00:25:28 +00001735namespace {
Erik Pilkington69770d32018-07-27 21:23:48 +00001736/// Tree transform to "extract" a transformed type from a class template's
1737/// constructor to a deduction guide.
1738class ExtractTypeForDeductionGuide
1739 : public TreeTransform<ExtractTypeForDeductionGuide> {
1740public:
1741 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
1742 ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1743
1744 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1745
1746 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1747 return TransformType(
1748 TLB,
1749 TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1750 }
1751};
1752
Richard Smith32918772017-02-14 00:25:28 +00001753/// Transform to convert portions of a constructor declaration into the
1754/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1755struct ConvertConstructorToDeductionGuideTransform {
1756 ConvertConstructorToDeductionGuideTransform(Sema &S,
1757 ClassTemplateDecl *Template)
1758 : SemaRef(S), Template(Template) {}
1759
1760 Sema &SemaRef;
1761 ClassTemplateDecl *Template;
1762
1763 DeclContext *DC = Template->getDeclContext();
1764 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1765 DeclarationName DeductionGuideName =
1766 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1767
1768 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1769
1770 // Index adjustment to apply to convert depth-1 template parameters into
1771 // depth-0 template parameters.
1772 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1773
1774 /// Transform a constructor declaration into a deduction guide.
Richard Smithbc491202017-02-17 20:05:37 +00001775 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1776 CXXConstructorDecl *CD) {
Richard Smith32918772017-02-14 00:25:28 +00001777 SmallVector<TemplateArgument, 16> SubstArgs;
1778
Richard Smithb4f96252017-02-21 06:30:38 +00001779 LocalInstantiationScope Scope(SemaRef);
1780
Richard Smith32918772017-02-14 00:25:28 +00001781 // C++ [over.match.class.deduct]p1:
1782 // -- For each constructor of the class template designated by the
1783 // template-name, a function template with the following properties:
1784
1785 // -- The template parameters are the template parameters of the class
1786 // template followed by the template parameters (including default
1787 // template arguments) of the constructor, if any.
1788 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1789 if (FTD) {
1790 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1791 SmallVector<NamedDecl *, 16> AllParams;
1792 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1793 AllParams.insert(AllParams.begin(),
1794 TemplateParams->begin(), TemplateParams->end());
1795 SubstArgs.reserve(InnerParams->size());
1796
1797 // Later template parameters could refer to earlier ones, so build up
1798 // a list of substituted template arguments as we go.
1799 for (NamedDecl *Param : *InnerParams) {
1800 MultiLevelTemplateArgumentList Args;
1801 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001802 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001803 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1804 if (!NewParam)
1805 return nullptr;
1806 AllParams.push_back(NewParam);
1807 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1808 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1809 }
1810 TemplateParams = TemplateParameterList::Create(
1811 SemaRef.Context, InnerParams->getTemplateLoc(),
1812 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1813 /*FIXME: RequiresClause*/ nullptr);
1814 }
1815
1816 // If we built a new template-parameter-list, track that we need to
1817 // substitute references to the old parameters into references to the
1818 // new ones.
1819 MultiLevelTemplateArgumentList Args;
1820 if (FTD) {
1821 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001822 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001823 }
1824
Richard Smithbc491202017-02-17 20:05:37 +00001825 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
Richard Smith32918772017-02-14 00:25:28 +00001826 .getAsAdjusted<FunctionProtoTypeLoc>();
1827 assert(FPTL && "no prototype for constructor declaration");
1828
1829 // Transform the type of the function, adjusting the return type and
1830 // replacing references to the old parameters with references to the
1831 // new ones.
1832 TypeLocBuilder TLB;
1833 SmallVector<ParmVarDecl*, 8> Params;
1834 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1835 if (NewType.isNull())
1836 return nullptr;
1837 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1838
Richard Smith76b90272019-05-09 03:59:21 +00001839 return buildDeductionGuide(TemplateParams, CD->getExplicitSpecifier(),
1840 NewTInfo, CD->getBeginLoc(), CD->getLocation(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001841 CD->getEndLoc());
Richard Smith32918772017-02-14 00:25:28 +00001842 }
1843
1844 /// Build a deduction guide with the specified parameter types.
1845 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1846 SourceLocation Loc = Template->getLocation();
1847
1848 // Build the requested type.
1849 FunctionProtoType::ExtProtoInfo EPI;
1850 EPI.HasTrailingReturn = true;
1851 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1852 DeductionGuideName, EPI);
1853 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1854
1855 FunctionProtoTypeLoc FPTL =
1856 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1857
1858 // Build the parameters, needed during deduction / substitution.
1859 SmallVector<ParmVarDecl*, 4> Params;
1860 for (auto T : ParamTypes) {
1861 ParmVarDecl *NewParam = ParmVarDecl::Create(
1862 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1863 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1864 NewParam->setScopeInfo(0, Params.size());
1865 FPTL.setParam(Params.size(), NewParam);
1866 Params.push_back(NewParam);
1867 }
1868
Richard Smith76b90272019-05-09 03:59:21 +00001869 return buildDeductionGuide(Template->getTemplateParameters(),
1870 ExplicitSpecifier(), TSI, Loc, Loc, Loc);
Richard Smith32918772017-02-14 00:25:28 +00001871 }
1872
1873private:
1874 /// Transform a constructor template parameter into a deduction guide template
1875 /// parameter, rebuilding any internal references to earlier parameters and
1876 /// renumbering as we go.
1877 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1878 MultiLevelTemplateArgumentList &Args) {
1879 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1880 // TemplateTypeParmDecl's index cannot be changed after creation, so
1881 // substitute it directly.
1882 auto *NewTTP = TemplateTypeParmDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001883 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
1884 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
Richard Smith32918772017-02-14 00:25:28 +00001885 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1886 TTP->isParameterPack());
1887 if (TTP->hasDefaultArgument()) {
1888 TypeSourceInfo *InstantiatedDefaultArg =
1889 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1890 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1891 if (InstantiatedDefaultArg)
1892 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1893 }
Richard Smithb4f96252017-02-21 06:30:38 +00001894 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1895 NewTTP);
Richard Smith32918772017-02-14 00:25:28 +00001896 return NewTTP;
1897 }
1898
1899 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1900 return transformTemplateParameterImpl(TTP, Args);
1901
1902 return transformTemplateParameterImpl(
1903 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1904 }
1905 template<typename TemplateParmDecl>
1906 TemplateParmDecl *
1907 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1908 MultiLevelTemplateArgumentList &Args) {
1909 // Ask the template instantiator to do the heavy lifting for us, then adjust
1910 // the index of the parameter once it's done.
1911 auto *NewParam =
1912 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1913 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1914 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1915 return NewParam;
1916 }
1917
1918 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1919 FunctionProtoTypeLoc TL,
1920 SmallVectorImpl<ParmVarDecl*> &Params,
1921 MultiLevelTemplateArgumentList &Args) {
1922 SmallVector<QualType, 4> ParamTypes;
1923 const FunctionProtoType *T = TL.getTypePtr();
1924
1925 // -- The types of the function parameters are those of the constructor.
1926 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001927 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001928 if (!NewParam)
1929 return QualType();
1930 ParamTypes.push_back(NewParam->getType());
1931 Params.push_back(NewParam);
1932 }
1933
1934 // -- The return type is the class template specialization designated by
1935 // the template-name and template arguments corresponding to the
1936 // template parameters obtained from the class template.
1937 //
1938 // We use the injected-class-name type of the primary template instead.
1939 // This has the convenient property that it is different from any type that
1940 // the user can write in a deduction-guide (because they cannot enter the
1941 // context of the template), so implicit deduction guides can never collide
1942 // with explicit ones.
1943 QualType ReturnType = DeducedType;
1944 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1945
1946 // Resolving a wording defect, we also inherit the variadicness of the
1947 // constructor.
1948 FunctionProtoType::ExtProtoInfo EPI;
1949 EPI.Variadic = T->isVariadic();
1950 EPI.HasTrailingReturn = true;
1951
1952 QualType Result = SemaRef.BuildFunctionType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001953 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
Richard Smith32918772017-02-14 00:25:28 +00001954 if (Result.isNull())
1955 return QualType();
1956
1957 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1958 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1959 NewTL.setLParenLoc(TL.getLParenLoc());
1960 NewTL.setRParenLoc(TL.getRParenLoc());
1961 NewTL.setExceptionSpecRange(SourceRange());
1962 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1963 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1964 NewTL.setParam(I, Params[I]);
1965
1966 return Result;
1967 }
1968
1969 ParmVarDecl *
1970 transformFunctionTypeParam(ParmVarDecl *OldParam,
1971 MultiLevelTemplateArgumentList &Args) {
1972 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smith479ba8e2017-04-20 01:15:31 +00001973 TypeSourceInfo *NewDI;
Erik Pilkington69770d32018-07-27 21:23:48 +00001974 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
Richard Smith479ba8e2017-04-20 01:15:31 +00001975 // Expand out the one and only element in each inner pack.
1976 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1977 NewDI =
1978 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1979 OldParam->getLocation(), OldParam->getDeclName());
1980 if (!NewDI) return nullptr;
1981 NewDI =
1982 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1983 PackTL.getTypePtr()->getNumExpansions());
1984 } else
1985 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1986 OldParam->getDeclName());
Richard Smith32918772017-02-14 00:25:28 +00001987 if (!NewDI)
1988 return nullptr;
1989
Erik Pilkington69770d32018-07-27 21:23:48 +00001990 // Extract the type. This (for instance) replaces references to typedef
1991 // members of the current instantiations with the definitions of those
1992 // typedefs, avoiding triggering instantiation of the deduced type during
1993 // deduction.
1994 NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
Richard Smithc27b3d72017-02-14 01:49:59 +00001995
Richard Smith32918772017-02-14 00:25:28 +00001996 // Resolving a wording defect, we also inherit default arguments from the
1997 // constructor.
1998 ExprResult NewDefArg;
1999 if (OldParam->hasDefaultArg()) {
Erik Pilkington69770d32018-07-27 21:23:48 +00002000 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
Richard Smith32918772017-02-14 00:25:28 +00002001 if (NewDefArg.isInvalid())
2002 return nullptr;
2003 }
2004
2005 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2006 OldParam->getInnerLocStart(),
2007 OldParam->getLocation(),
2008 OldParam->getIdentifier(),
2009 NewDI->getType(),
2010 NewDI,
2011 OldParam->getStorageClass(),
2012 NewDefArg.get());
2013 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2014 OldParam->getFunctionScopeIndex());
Erik Pilkington69770d32018-07-27 21:23:48 +00002015 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
Richard Smith32918772017-02-14 00:25:28 +00002016 return NewParam;
2017 }
2018
2019 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
Richard Smith76b90272019-05-09 03:59:21 +00002020 ExplicitSpecifier ES, TypeSourceInfo *TInfo,
Richard Smith32918772017-02-14 00:25:28 +00002021 SourceLocation LocStart, SourceLocation Loc,
2022 SourceLocation LocEnd) {
Richard Smithbc491202017-02-17 20:05:37 +00002023 DeclarationNameInfo Name(DeductionGuideName, Loc);
Richard Smithefa919a2017-02-16 21:29:21 +00002024 ArrayRef<ParmVarDecl *> Params =
2025 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2026
Richard Smith32918772017-02-14 00:25:28 +00002027 // Build the implicit deduction guide template.
Richard Smithbc491202017-02-17 20:05:37 +00002028 auto *Guide =
Richard Smith76b90272019-05-09 03:59:21 +00002029 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2030 TInfo->getType(), TInfo, LocEnd);
Richard Smith32918772017-02-14 00:25:28 +00002031 Guide->setImplicit();
Richard Smithefa919a2017-02-16 21:29:21 +00002032 Guide->setParams(Params);
2033
2034 for (auto *Param : Params)
2035 Param->setDeclContext(Guide);
Richard Smith32918772017-02-14 00:25:28 +00002036
2037 auto *GuideTemplate = FunctionTemplateDecl::Create(
2038 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2039 GuideTemplate->setImplicit();
2040 Guide->setDescribedFunctionTemplate(GuideTemplate);
2041
2042 if (isa<CXXRecordDecl>(DC)) {
2043 Guide->setAccess(AS_public);
2044 GuideTemplate->setAccess(AS_public);
2045 }
2046
2047 DC->addDecl(GuideTemplate);
2048 return GuideTemplate;
2049 }
2050};
2051}
2052
2053void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2054 SourceLocation Loc) {
2055 DeclContext *DC = Template->getDeclContext();
2056 if (DC->isDependentContext())
2057 return;
2058
2059 ConvertConstructorToDeductionGuideTransform Transform(
2060 *this, cast<ClassTemplateDecl>(Template));
2061 if (!isCompleteType(Loc, Transform.DeducedType))
2062 return;
2063
2064 // Check whether we've already declared deduction guides for this template.
2065 // FIXME: Consider storing a flag on the template to indicate this.
2066 auto Existing = DC->lookup(Transform.DeductionGuideName);
2067 for (auto *D : Existing)
2068 if (D->isImplicit())
2069 return;
2070
2071 // In case we were expanding a pack when we attempted to declare deduction
2072 // guides, turn off pack expansion for everything we're about to do.
2073 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2074 // Create a template instantiation record to track the "instantiation" of
2075 // constructors into deduction guides.
2076 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2077 // this substitution process actually fail?
2078 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
Volodymyr Sapsai2f649f32018-05-14 22:49:44 +00002079 if (BuildingDeductionGuides.isInvalid())
2080 return;
Richard Smith32918772017-02-14 00:25:28 +00002081
2082 // Convert declared constructors into deduction guide templates.
2083 // FIXME: Skip constructors for which deduction must necessarily fail (those
2084 // for which some class template parameter without a default argument never
2085 // appears in a deduced context).
2086 bool AddedAny = false;
Richard Smith32918772017-02-14 00:25:28 +00002087 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2088 D = D->getUnderlyingDecl();
2089 if (D->isInvalidDecl() || D->isImplicit())
2090 continue;
2091 D = cast<NamedDecl>(D->getCanonicalDecl());
2092
2093 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00002094 auto *CD =
2095 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00002096 // Class-scope explicit specializations (MS extension) do not result in
2097 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00002098 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00002099 continue;
2100
Richard Smithbc491202017-02-17 20:05:37 +00002101 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00002102 AddedAny = true;
Richard Smith32918772017-02-14 00:25:28 +00002103 }
2104
Faisal Vali81b756e2017-10-22 14:45:08 +00002105 // C++17 [over.match.class.deduct]
2106 // -- If C is not defined or does not declare any constructors, an
2107 // additional function template derived as above from a hypothetical
2108 // constructor C().
Richard Smith32918772017-02-14 00:25:28 +00002109 if (!AddedAny)
2110 Transform.buildSimpleDeductionGuide(None);
2111
Faisal Vali81b756e2017-10-22 14:45:08 +00002112 // -- An additional function template derived as above from a hypothetical
2113 // constructor C(C), called the copy deduction candidate.
2114 cast<CXXDeductionGuideDecl>(
2115 cast<FunctionTemplateDecl>(
2116 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2117 ->getTemplatedDecl())
2118 ->setIsCopyDeductionCandidate();
Richard Smith32918772017-02-14 00:25:28 +00002119}
2120
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002121/// Diagnose the presence of a default template argument on a
Douglas Gregored5731f2009-11-25 17:50:39 +00002122/// template parameter, which is ill-formed in certain contexts.
2123///
2124/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002125static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00002126 Sema::TemplateParamListContext TPC,
2127 SourceLocation ParamLoc,
2128 SourceRange DefArgRange) {
2129 switch (TPC) {
2130 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002131 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00002132 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002133 return false;
2134
2135 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002136 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00002138 // A default template-argument shall not be specified in a
2139 // function template declaration or a function template
2140 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00002141 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002142 // template-argument, that declaration shall be a definition and shall be
2143 // the only declaration of the function template in the translation unit.
2144 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002145 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002146 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2147 : diag::ext_template_parameter_default_in_function_template)
2148 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00002149 return false;
2150
2151 case Sema::TPC_ClassTemplateMember:
2152 // C++0x [temp.param]p9:
2153 // A default template-argument shall not be specified in the
2154 // template-parameter-lists of the definition of a member of a
2155 // class template that appears outside of the member's class.
2156 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2157 << DefArgRange;
2158 return true;
2159
David Majnemerba8f17a2013-06-25 22:08:55 +00002160 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002161 case Sema::TPC_FriendFunctionTemplate:
2162 // C++ [temp.param]p9:
2163 // A default template-argument shall not be specified in a
2164 // friend template declaration.
2165 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2166 << DefArgRange;
2167 return true;
2168
2169 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2170 // for friend function templates if there is only a single
2171 // declaration (and it is a definition). Strange!
2172 }
2173
David Blaikie8a40f702012-01-17 06:56:22 +00002174 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00002175}
2176
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002177/// Check for unexpanded parameter packs within the template parameters
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002178/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00002179static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2180 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002181 // A template template parameter which is a parameter pack is also a pack
2182 // expansion.
2183 if (TTP->isParameterPack())
2184 return false;
2185
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002186 TemplateParameterList *Params = TTP->getTemplateParameters();
2187 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2188 NamedDecl *P = Params->getParam(I);
2189 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002190 if (!NTTP->isParameterPack() &&
2191 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002192 NTTP->getTypeSourceInfo(),
2193 Sema::UPPC_NonTypeTemplateParameterType))
2194 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002195
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002196 continue;
2197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002198
2199 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002200 = dyn_cast<TemplateTemplateParmDecl>(P))
2201 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2202 return true;
2203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002204
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002205 return false;
2206}
2207
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002208/// Checks the validity of a template parameter list, possibly
Douglas Gregordba32632009-02-10 19:49:53 +00002209/// considering the template parameter list from a previous
2210/// declaration.
2211///
2212/// If an "old" template parameter list is provided, it must be
2213/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2214/// template parameter list.
2215///
2216/// \param NewParams Template parameter list for a new template
2217/// declaration. This template parameter list will be updated with any
2218/// default arguments that are carried through from the previous
2219/// template parameter list.
2220///
2221/// \param OldParams If provided, template parameter list from a
2222/// previous declaration of the same template. Default template
2223/// arguments will be merged from the old template parameter list to
2224/// the new template parameter list.
2225///
Douglas Gregored5731f2009-11-25 17:50:39 +00002226/// \param TPC Describes the context in which we are checking the given
2227/// template parameter list.
2228///
Richard Smithc4577662018-09-12 02:13:47 +00002229/// \param SkipBody If we might have already made a prior merged definition
2230/// of this template visible, the corresponding body-skipping information.
2231/// Default argument redefinition is not an error when skipping such a body,
2232/// because (under the ODR) we can assume the default arguments are the same
2233/// as the prior merged definition.
2234///
Douglas Gregordba32632009-02-10 19:49:53 +00002235/// \returns true if an error occurred, false otherwise.
2236bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00002237 TemplateParameterList *OldParams,
Richard Smithc4577662018-09-12 02:13:47 +00002238 TemplateParamListContext TPC,
2239 SkipBodyInfo *SkipBody) {
Douglas Gregordba32632009-02-10 19:49:53 +00002240 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00002241
Douglas Gregordba32632009-02-10 19:49:53 +00002242 // C++ [temp.param]p10:
2243 // The set of default template-arguments available for use with a
2244 // template declaration or definition is obtained by merging the
2245 // default arguments from the definition (if in scope) and all
2246 // declarations in scope in the same way default function
2247 // arguments are (8.3.6).
2248 bool SawDefaultArgument = false;
2249 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00002250
Mike Stumpc89c8e32009-02-11 23:03:27 +00002251 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00002252 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00002253 if (OldParams)
2254 OldParam = OldParams->begin();
2255
Douglas Gregor0693def2011-01-27 01:40:17 +00002256 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00002257 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2258 NewParamEnd = NewParams->end();
2259 NewParam != NewParamEnd; ++NewParam) {
2260 // Variables used to diagnose redundant default arguments
2261 bool RedundantDefaultArg = false;
2262 SourceLocation OldDefaultLoc;
2263 SourceLocation NewDefaultLoc;
2264
David Blaikie651c73c2011-10-19 05:19:50 +00002265 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00002266 bool MissingDefaultArg = false;
2267
David Blaikie651c73c2011-10-19 05:19:50 +00002268 // Variable used to diagnose non-final parameter packs
2269 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00002270
Douglas Gregordba32632009-02-10 19:49:53 +00002271 if (TemplateTypeParmDecl *NewTypeParm
2272 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00002273 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002274 if (NewTypeParm->hasDefaultArgument() &&
2275 DiagnoseDefaultTemplateArgument(*this, TPC,
2276 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002277 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002278 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00002279 NewTypeParm->removeDefaultArgument();
2280
2281 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002282 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002283 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00002284 if (NewTypeParm->isParameterPack()) {
2285 assert(!NewTypeParm->hasDefaultArgument() &&
2286 "Parameter packs can't have a default argument!");
2287 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002288 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002289 NewTypeParm->hasDefaultArgument() &&
2290 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002291 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2292 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2293 SawDefaultArgument = true;
2294 RedundantDefaultArg = true;
2295 PreviousDefaultArgLoc = NewDefaultLoc;
2296 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2297 // Merge the default argument from the old declaration to the
2298 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002299 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002300 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2301 } else if (NewTypeParm->hasDefaultArgument()) {
2302 SawDefaultArgument = true;
2303 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2304 } else if (SawDefaultArgument)
2305 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002306 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00002307 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002308 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002309 if (!NewNonTypeParm->isParameterPack() &&
2310 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002311 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002312 UPPC_NonTypeTemplateParameterType)) {
2313 Invalid = true;
2314 continue;
2315 }
2316
Douglas Gregored5731f2009-11-25 17:50:39 +00002317 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002318 if (NewNonTypeParm->hasDefaultArgument() &&
2319 DiagnoseDefaultTemplateArgument(*this, TPC,
2320 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002321 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00002322 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002323 }
2324
Mike Stump12b8ce12009-08-04 21:02:39 +00002325 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002326 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002327 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002328 if (NewNonTypeParm->isParameterPack()) {
2329 assert(!NewNonTypeParm->hasDefaultArgument() &&
2330 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002331 if (!NewNonTypeParm->isPackExpansion())
2332 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002333 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002334 NewNonTypeParm->hasDefaultArgument() &&
2335 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002336 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2337 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2338 SawDefaultArgument = true;
2339 RedundantDefaultArg = true;
2340 PreviousDefaultArgLoc = NewDefaultLoc;
2341 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2342 // Merge the default argument from the old declaration to the
2343 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002344 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002345 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2346 } else if (NewNonTypeParm->hasDefaultArgument()) {
2347 SawDefaultArgument = true;
2348 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2349 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002350 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002351 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00002352 TemplateTemplateParmDecl *NewTemplateParm
2353 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002354
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002355 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002356 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002357 Invalid = true;
2358 continue;
2359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002360
David Blaikie651c73c2011-10-19 05:19:50 +00002361 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002362 if (NewTemplateParm->hasDefaultArgument() &&
2363 DiagnoseDefaultTemplateArgument(*this, TPC,
2364 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002365 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002366 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002367
2368 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002369 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002370 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002371 if (NewTemplateParm->isParameterPack()) {
2372 assert(!NewTemplateParm->hasDefaultArgument() &&
2373 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002374 if (!NewTemplateParm->isPackExpansion())
2375 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002376 } else if (OldTemplateParm &&
2377 hasVisibleDefaultArgument(OldTemplateParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002378 NewTemplateParm->hasDefaultArgument() &&
2379 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002380 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2381 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002382 SawDefaultArgument = true;
2383 RedundantDefaultArg = true;
2384 PreviousDefaultArgLoc = NewDefaultLoc;
2385 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2386 // Merge the default argument from the old declaration to the
2387 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002388 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002389 PreviousDefaultArgLoc
2390 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002391 } else if (NewTemplateParm->hasDefaultArgument()) {
2392 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002393 PreviousDefaultArgLoc
2394 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002395 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002396 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002397 }
2398
Richard Smith1fde8ec2012-09-07 02:06:42 +00002399 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002400 // If a template parameter of a primary class template or alias template
2401 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002402 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002403 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2404 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002405 Diag((*NewParam)->getLocation(),
2406 diag::err_template_param_pack_must_be_last_template_parameter);
2407 Invalid = true;
2408 }
2409
Douglas Gregordba32632009-02-10 19:49:53 +00002410 if (RedundantDefaultArg) {
2411 // C++ [temp.param]p12:
2412 // A template-parameter shall not be given default arguments
2413 // by two different declarations in the same scope.
2414 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2415 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2416 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002417 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002418 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002419 // If a template-parameter of a class template has a default
2420 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002421 // have a default template-argument supplied or be a template parameter
2422 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002423 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002424 diag::err_template_param_default_arg_missing);
2425 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2426 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002427 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002428 }
2429
2430 // If we have an old template parameter list that we're merging
2431 // in, move on to the next parameter.
2432 if (OldParams)
2433 ++OldParam;
2434 }
2435
Douglas Gregor0693def2011-01-27 01:40:17 +00002436 // We were missing some default arguments at the end of the list, so remove
2437 // all of the default arguments.
2438 if (RemoveDefaultArguments) {
2439 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2440 NewParamEnd = NewParams->end();
2441 NewParam != NewParamEnd; ++NewParam) {
2442 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2443 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002444 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002445 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2446 NTTP->removeDefaultArgument();
2447 else
2448 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2449 }
2450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002451
Douglas Gregordba32632009-02-10 19:49:53 +00002452 return Invalid;
2453}
Douglas Gregord32e0282009-02-09 23:23:08 +00002454
John McCalla020a012010-10-20 05:44:58 +00002455namespace {
2456
2457/// A class which looks for a use of a certain level of template
2458/// parameter.
2459struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2460 typedef RecursiveASTVisitor<DependencyChecker> super;
2461
2462 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00002463
2464 // Whether we're looking for a use of a template parameter that makes the
2465 // overall construct type-dependent / a dependent type. This is strictly
2466 // best-effort for now; we may fail to match at all for a dependent type
2467 // in some cases if this is set.
2468 bool IgnoreNonTypeDependent;
2469
John McCalla020a012010-10-20 05:44:58 +00002470 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002471 SourceLocation MatchLoc;
2472
Richard Smith13894182017-04-13 21:37:24 +00002473 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2474 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2475 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002476
Richard Smith57aae072016-12-28 02:37:25 +00002477 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith13894182017-04-13 21:37:24 +00002478 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2479 NamedDecl *ND = Params->getParam(0);
2480 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2481 Depth = PD->getDepth();
2482 } else if (NonTypeTemplateParmDecl *PD =
2483 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2484 Depth = PD->getDepth();
2485 } else {
2486 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2487 }
2488 }
John McCalla020a012010-10-20 05:44:58 +00002489
Richard Smith6056d5e2014-02-09 00:54:43 +00002490 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith13894182017-04-13 21:37:24 +00002491 if (ParmDepth >= Depth) {
John McCalla020a012010-10-20 05:44:58 +00002492 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002493 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002494 return true;
2495 }
2496 return false;
2497 }
2498
Richard Smith57aae072016-12-28 02:37:25 +00002499 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2500 // Prune out non-type-dependent expressions if requested. This can
2501 // sometimes result in us failing to find a template parameter reference
2502 // (if a value-dependent expression creates a dependent type), but this
2503 // mode is best-effort only.
2504 if (auto *E = dyn_cast_or_null<Expr>(S))
2505 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2506 return true;
2507 return super::TraverseStmt(S, Q);
2508 }
2509
2510 bool TraverseTypeLoc(TypeLoc TL) {
2511 if (IgnoreNonTypeDependent && !TL.isNull() &&
2512 !TL.getType()->isDependentType())
2513 return true;
2514 return super::TraverseTypeLoc(TL);
2515 }
2516
Richard Smith6056d5e2014-02-09 00:54:43 +00002517 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2518 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2519 }
2520
John McCalla020a012010-10-20 05:44:58 +00002521 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002522 // For a best-effort search, keep looking until we find a location.
2523 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002524 }
2525
2526 bool TraverseTemplateName(TemplateName N) {
2527 if (TemplateTemplateParmDecl *PD =
2528 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002529 if (Matches(PD->getDepth()))
2530 return false;
John McCalla020a012010-10-20 05:44:58 +00002531 return super::TraverseTemplateName(N);
2532 }
2533
2534 bool VisitDeclRefExpr(DeclRefExpr *E) {
2535 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002536 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2537 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002538 return false;
John McCalla020a012010-10-20 05:44:58 +00002539 return super::VisitDeclRefExpr(E);
2540 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002541
2542 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2543 return TraverseType(T->getReplacementType());
2544 }
2545
2546 bool
2547 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2548 return TraverseTemplateArgument(T->getArgumentPack());
2549 }
2550
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002551 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2552 return TraverseType(T->getInjectedSpecializationType());
2553 }
John McCalla020a012010-10-20 05:44:58 +00002554};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002555} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002556
Douglas Gregor972fe532011-05-10 18:27:06 +00002557/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002558/// list.
2559static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002560DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002561 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002562 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002563 return Checker.Match;
2564}
2565
Douglas Gregor972fe532011-05-10 18:27:06 +00002566// Find the source range corresponding to the named type in the given
2567// nested-name-specifier, if any.
2568static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2569 QualType T,
2570 const CXXScopeSpec &SS) {
2571 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2572 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2573 if (const Type *CurType = NNS->getAsType()) {
2574 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2575 return NNSLoc.getTypeLoc().getSourceRange();
2576 } else
2577 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002578
Douglas Gregor972fe532011-05-10 18:27:06 +00002579 NNSLoc = NNSLoc.getPrefix();
2580 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002581
Douglas Gregor972fe532011-05-10 18:27:06 +00002582 return SourceRange();
2583}
2584
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002585/// Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002586/// specifier, returning the template parameter list that applies to the
2587/// name.
2588///
2589/// \param DeclStartLoc the start of the declaration that has a scope
2590/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002591///
Douglas Gregor972fe532011-05-10 18:27:06 +00002592/// \param DeclLoc The location of the declaration itself.
2593///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002594/// \param SS the scope specifier that will be matched to the given template
2595/// parameter lists. This scope specifier precedes a qualified name that is
2596/// being declared.
2597///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002598/// \param TemplateId The template-id following the scope specifier, if there
2599/// is one. Used to check for a missing 'template<>'.
2600///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002601/// \param ParamLists the template parameter lists, from the outermost to the
2602/// innermost template parameter lists.
2603///
John McCalle820e5e2010-04-13 20:37:33 +00002604/// \param IsFriend Whether to apply the slightly different rules for
2605/// matching template parameters to scope specifiers in friend
2606/// declarations.
2607///
Richard Smithf445f192017-02-09 21:04:43 +00002608/// \param IsMemberSpecialization will be set true if the scope specifier
2609/// denotes a fully-specialized type, and therefore this is a declaration of
2610/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002611///
Mike Stump11289f42009-09-09 15:08:12 +00002612/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002613/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002614/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002615/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002616/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002617/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002618TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2619 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002620 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002621 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002622 bool &IsMemberSpecialization, bool &Invalid) {
2623 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002624 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002625
Douglas Gregor972fe532011-05-10 18:27:06 +00002626 // The sequence of nested types to which we will match up the template
2627 // parameter lists. We first build this list by starting with the type named
2628 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002629 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002630 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002631 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002632 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002633 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2634 T = Context.getTypeDeclType(Record);
2635 else
2636 T = QualType(SS.getScopeRep()->getAsType(), 0);
2637 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002638
Douglas Gregor972fe532011-05-10 18:27:06 +00002639 // If we found an explicit specialization that prevents us from needing
2640 // 'template<>' headers, this will be set to the location of that
2641 // explicit specialization.
2642 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002643
Douglas Gregor972fe532011-05-10 18:27:06 +00002644 while (!T.isNull()) {
2645 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002646
Douglas Gregor972fe532011-05-10 18:27:06 +00002647 // Retrieve the parent of a record type.
2648 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2649 // If this type is an explicit specialization, we're done.
2650 if (ClassTemplateSpecializationDecl *Spec
2651 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002652 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002653 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2654 ExplicitSpecLoc = Spec->getLocation();
2655 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002656 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002657 } else if (Record->getTemplateSpecializationKind()
2658 == TSK_ExplicitSpecialization) {
2659 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002660 break;
2661 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002662
Douglas Gregor972fe532011-05-10 18:27:06 +00002663 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2664 T = Context.getTypeDeclType(Parent);
2665 else
2666 T = QualType();
2667 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002668 }
2669
Douglas Gregor972fe532011-05-10 18:27:06 +00002670 if (const TemplateSpecializationType *TST
2671 = T->getAs<TemplateSpecializationType>()) {
2672 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2673 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2674 T = Context.getTypeDeclType(Parent);
2675 else
2676 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002677 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002678 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002679 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002680
Douglas Gregor972fe532011-05-10 18:27:06 +00002681 // Look one step prior in a dependent template specialization type.
2682 if (const DependentTemplateSpecializationType *DependentTST
2683 = T->getAs<DependentTemplateSpecializationType>()) {
2684 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2685 T = QualType(NNS->getAsType(), 0);
2686 else
2687 T = QualType();
2688 continue;
2689 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002690
Douglas Gregor972fe532011-05-10 18:27:06 +00002691 // Look one step prior in a dependent name type.
2692 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2693 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2694 T = QualType(NNS->getAsType(), 0);
2695 else
2696 T = QualType();
2697 continue;
2698 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002699
Douglas Gregor972fe532011-05-10 18:27:06 +00002700 // Retrieve the parent of an enumeration type.
2701 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2702 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2703 // check here.
2704 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002705
Douglas Gregor972fe532011-05-10 18:27:06 +00002706 // Get to the parent type.
2707 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2708 T = Context.getTypeDeclType(Parent);
2709 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002710 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002711 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002712 }
Mike Stump11289f42009-09-09 15:08:12 +00002713
Douglas Gregor972fe532011-05-10 18:27:06 +00002714 T = QualType();
2715 }
2716 // Reverse the nested types list, since we want to traverse from the outermost
2717 // to the innermost while checking template-parameter-lists.
2718 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002719
Douglas Gregor972fe532011-05-10 18:27:06 +00002720 // C++0x [temp.expl.spec]p17:
2721 // A member or a member template may be nested within many
2722 // enclosing class templates. In an explicit specialization for
2723 // such a member, the member declaration shall be preceded by a
2724 // template<> for each enclosing class template that is
2725 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002726 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002727
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002728 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002729 if (SawNonEmptyTemplateParameterList) {
2730 Diag(DeclLoc, diag::err_specialize_member_of_template)
2731 << !Recovery << Range;
2732 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002733 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002734 return true;
2735 }
2736
2737 return false;
2738 };
2739
2740 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2741 // Check that we can have an explicit specialization here.
2742 if (CheckExplicitSpecialization(Range, true))
2743 return true;
2744
2745 // We don't have a template header, but we should.
2746 SourceLocation ExpectedTemplateLoc;
2747 if (!ParamLists.empty())
2748 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2749 else
2750 ExpectedTemplateLoc = DeclStartLoc;
2751
2752 Diag(DeclLoc, diag::err_template_spec_needs_header)
2753 << Range
2754 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2755 return false;
2756 };
2757
Douglas Gregor972fe532011-05-10 18:27:06 +00002758 unsigned ParamIdx = 0;
2759 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2760 ++TypeIdx) {
2761 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002762
Douglas Gregor972fe532011-05-10 18:27:06 +00002763 // Whether we expect a 'template<>' header.
2764 bool NeedEmptyTemplateHeader = false;
2765
2766 // Whether we expect a template header with parameters.
2767 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002768
Douglas Gregor972fe532011-05-10 18:27:06 +00002769 // For a dependent type, the set of template parameters that we
2770 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002771 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002772
Douglas Gregor373af9b2011-05-11 23:26:17 +00002773 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002774 // A member or a member template may be nested within many enclosing
2775 // class templates. In an explicit specialization for such a member, the
2776 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002777 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002778 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2779 if (ClassTemplatePartialSpecializationDecl *Partial
2780 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2781 ExpectedTemplateParams = Partial->getTemplateParameters();
2782 NeedNonemptyTemplateHeader = true;
2783 } else if (Record->isDependentType()) {
2784 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002785 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002786 ->getTemplateParameters();
2787 NeedNonemptyTemplateHeader = true;
2788 }
2789 } else if (ClassTemplateSpecializationDecl *Spec
2790 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2791 // C++0x [temp.expl.spec]p4:
2792 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002793 // in the same manner as members of normal classes, and not using
2794 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002795 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2796 NeedEmptyTemplateHeader = true;
2797 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002798 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002799 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002800 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002801 != TSK_ExplicitSpecialization &&
2802 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002803 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002804
Douglas Gregor373af9b2011-05-11 23:26:17 +00002805 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002806 }
2807 } else if (const TemplateSpecializationType *TST
2808 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002809 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002810 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002811 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002812 }
2813 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2814 // FIXME: We actually could/should check the template arguments here
2815 // against the corresponding template parameter list.
2816 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002817 }
2818
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002819 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002820 // In an explicit specialization declaration for a member of a class
2821 // template or a member template that ap- pears in namespace scope, the
2822 // member template and some of its enclosing class templates may remain
2823 // unspecialized, except that the declaration shall not explicitly
2824 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002825 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002826 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002827 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002828 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2829 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002830 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002831 } else
2832 SawNonEmptyTemplateParameterList = true;
2833 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002834
Douglas Gregor972fe532011-05-10 18:27:06 +00002835 if (NeedEmptyTemplateHeader) {
2836 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002837 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002838 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002839 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002840
2841 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002842 if (ParamLists[ParamIdx]->size() > 0) {
2843 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002844 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002845 diag::err_template_param_list_matches_nontemplate)
2846 << T
2847 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2848 ParamLists[ParamIdx]->getRAngleLoc())
2849 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2850 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002851 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002852 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002853
Douglas Gregor972fe532011-05-10 18:27:06 +00002854 // Consume this template header.
2855 ++ParamIdx;
2856 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002857 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002858
2859 if (!IsFriend)
2860 if (DiagnoseMissingExplicitSpecialization(
2861 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002862 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002863
Douglas Gregor972fe532011-05-10 18:27:06 +00002864 continue;
2865 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002866
Douglas Gregor972fe532011-05-10 18:27:06 +00002867 if (NeedNonemptyTemplateHeader) {
2868 // In friend declarations we can have template-ids which don't
2869 // depend on the corresponding template parameter lists. But
2870 // assume that empty parameter lists are supposed to match this
2871 // template-id.
2872 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002873 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002874 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002875 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002876 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002877 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002878 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002879
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002880 if (ParamIdx < ParamLists.size()) {
2881 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002882 if (ExpectedTemplateParams &&
2883 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2884 ExpectedTemplateParams,
2885 true, TPL_TemplateMatch))
2886 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002887
Douglas Gregor972fe532011-05-10 18:27:06 +00002888 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002889 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002890 TPC_ClassTemplateMember))
2891 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002892
Douglas Gregor972fe532011-05-10 18:27:06 +00002893 ++ParamIdx;
2894 continue;
2895 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002896
Douglas Gregor972fe532011-05-10 18:27:06 +00002897 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2898 << T
2899 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2900 Invalid = true;
2901 continue;
2902 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002903 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002904
Douglas Gregord8d297c2009-07-21 23:53:31 +00002905 // If there were at least as many template-ids as there were template
2906 // parameter lists, then there are no template parameter lists remaining for
2907 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002908 if (ParamIdx >= ParamLists.size()) {
2909 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002910 // We don't have a template header for the declaration itself, but we
2911 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002912 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2913 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002914
2915 // Fabricate an empty template parameter list for the invented header.
2916 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002917 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002918 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002919 }
2920
Craig Topperc3ec1492014-05-26 06:22:03 +00002921 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002922 }
Mike Stump11289f42009-09-09 15:08:12 +00002923
Douglas Gregord8d297c2009-07-21 23:53:31 +00002924 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002925 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002926 bool HasAnyExplicitSpecHeader = false;
2927 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002928 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002929 if (ParamLists[I]->size() == 0)
2930 HasAnyExplicitSpecHeader = true;
2931 else
2932 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002933 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002934
Douglas Gregor972fe532011-05-10 18:27:06 +00002935 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002936 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2937 : diag::err_template_spec_extra_headers)
2938 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2939 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002940
2941 // If there was a specialization somewhere, such that 'template<>' is
2942 // not required, and there were any 'template<>' headers, note where the
2943 // specialization occurred.
2944 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002945 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002946 diag::note_explicit_template_spec_does_not_need_header)
2947 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002948
Douglas Gregor972fe532011-05-10 18:27:06 +00002949 // We have a template parameter list with no corresponding scope, which
2950 // means that the resulting template declaration can't be instantiated
2951 // properly (we'll end up with dependent nodes when we shouldn't).
2952 if (!AllExplicitSpecHeaders)
2953 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002954 }
Mike Stump11289f42009-09-09 15:08:12 +00002955
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002956 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002957 // In an explicit specialization declaration for a member of a class
2958 // template or a member template that ap- pears in namespace scope, the
2959 // member template and some of its enclosing class templates may remain
2960 // unspecialized, except that the declaration shall not explicitly
2961 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002962 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002963 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002964 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2965 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002966 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002967
Douglas Gregord8d297c2009-07-21 23:53:31 +00002968 // Return the last template parameter list, which corresponds to the
2969 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002970 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002971}
2972
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002973void Sema::NoteAllFoundTemplates(TemplateName Name) {
2974 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2975 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002976 << (isa<FunctionTemplateDecl>(Template)
2977 ? 0
2978 : isa<ClassTemplateDecl>(Template)
2979 ? 1
2980 : isa<VarTemplateDecl>(Template)
2981 ? 2
2982 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2983 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002984 return;
2985 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002986
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002987 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002988 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002989 IEnd = OST->end();
2990 I != IEnd; ++I)
2991 Diag((*I)->getLocation(), diag::note_template_declared_here)
2992 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002993
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002994 return;
2995 }
2996}
2997
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002998static QualType
2999checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3000 const SmallVectorImpl<TemplateArgument> &Converted,
3001 SourceLocation TemplateLoc,
3002 TemplateArgumentListInfo &TemplateArgs) {
3003 ASTContext &Context = SemaRef.getASTContext();
3004 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00003005 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003006 // Specializations of __make_integer_seq<S, T, N> are treated like
3007 // S<T, 0, ..., N-1>.
3008
3009 // C++14 [inteseq.intseq]p1:
3010 // T shall be an integer type.
3011 if (!Converted[1].getAsType()->isIntegralType(Context)) {
3012 SemaRef.Diag(TemplateArgs[1].getLocation(),
3013 diag::err_integer_sequence_integral_element_type);
3014 return QualType();
3015 }
3016
3017 // C++14 [inteseq.make]p1:
3018 // If N is negative the program is ill-formed.
3019 TemplateArgument NumArgsArg = Converted[2];
3020 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3021 if (NumArgs < 0) {
3022 SemaRef.Diag(TemplateArgs[2].getLocation(),
3023 diag::err_integer_sequence_negative_length);
3024 return QualType();
3025 }
3026
3027 QualType ArgTy = NumArgsArg.getIntegralType();
3028 TemplateArgumentListInfo SyntheticTemplateArgs;
3029 // The type argument gets reused as the first template argument in the
3030 // synthetic template argument list.
3031 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3032 // Expand N into 0 ... N-1.
3033 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3034 I < NumArgs; ++I) {
3035 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00003036 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3037 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003038 }
3039 // The first template argument will be reused as the template decl that
3040 // our synthetic template arguments will be applied to.
3041 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3042 TemplateLoc, SyntheticTemplateArgs);
3043 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00003044
3045 case BTK__type_pack_element:
3046 // Specializations of
3047 // __type_pack_element<Index, T_1, ..., T_N>
3048 // are treated like T_Index.
3049 assert(Converted.size() == 2 &&
3050 "__type_pack_element should be given an index and a parameter pack");
3051
3052 // If the Index is out of bounds, the program is ill-formed.
3053 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3054 llvm::APSInt Index = IndexArg.getAsIntegral();
3055 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3056 "type std::size_t, and hence be non-negative");
3057 if (Index >= Ts.pack_size()) {
3058 SemaRef.Diag(TemplateArgs[0].getLocation(),
3059 diag::err_type_pack_element_out_of_bounds);
3060 return QualType();
3061 }
3062
3063 // We simply return the type at index `Index`.
3064 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3065 return Nth->getAsType();
3066 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003067 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3068}
3069
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003070/// Determine whether this alias template is "enable_if_t".
3071static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3072 return AliasTemplate->getName().equals("enable_if_t");
3073}
3074
3075/// Collect all of the separable terms in the given condition, which
3076/// might be a conjunction.
3077///
3078/// FIXME: The right answer is to convert the logical expression into
3079/// disjunctive normal form, so we can find the first failed term
3080/// within each possible clause.
3081static void collectConjunctionTerms(Expr *Clause,
3082 SmallVectorImpl<Expr *> &Terms) {
3083 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3084 if (BinOp->getOpcode() == BO_LAnd) {
3085 collectConjunctionTerms(BinOp->getLHS(), Terms);
3086 collectConjunctionTerms(BinOp->getRHS(), Terms);
3087 }
3088
3089 return;
3090 }
3091
3092 Terms.push_back(Clause);
3093}
3094
Douglas Gregorbb33f572017-07-05 20:20:15 +00003095// The ranges-v3 library uses an odd pattern of a top-level "||" with
3096// a left-hand side that is value-dependent but never true. Identify
3097// the idiom and ignore that term.
3098static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3099 // Top-level '||'.
3100 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3101 if (!BinOp) return Cond;
3102
3103 if (BinOp->getOpcode() != BO_LOr) return Cond;
3104
3105 // With an inner '==' that has a literal on the right-hand side.
3106 Expr *LHS = BinOp->getLHS();
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003107 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
Douglas Gregorbb33f572017-07-05 20:20:15 +00003108 if (!InnerBinOp) return Cond;
3109
3110 if (InnerBinOp->getOpcode() != BO_EQ ||
3111 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3112 return Cond;
3113
3114 // If the inner binary operation came from a macro expansion named
3115 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3116 // of the '||', which is the real, user-provided condition.
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003117 SourceLocation Loc = InnerBinOp->getExprLoc();
Douglas Gregorbb33f572017-07-05 20:20:15 +00003118 if (!Loc.isMacroID()) return Cond;
3119
3120 StringRef MacroName = PP.getImmediateMacroName(Loc);
3121 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3122 return BinOp->getRHS();
3123
3124 return Cond;
3125}
3126
Clement Courbetf44c6f42018-12-11 08:39:11 +00003127namespace {
3128
3129// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3130// within failing boolean expression, such as substituting template parameters
3131// for actual types.
3132class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3133public:
3134 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3135 : Policy(P) {}
3136
3137 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3138 const auto *DR = dyn_cast<DeclRefExpr>(E);
3139 if (DR && DR->getQualifier()) {
3140 // If this is a qualified name, expand the template arguments in nested
3141 // qualifiers.
3142 DR->getQualifier()->print(OS, Policy, true);
3143 // Then print the decl itself.
3144 const ValueDecl *VD = DR->getDecl();
3145 OS << VD->getName();
3146 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3147 // This is a template variable, print the expanded template arguments.
3148 printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3149 }
3150 return true;
Clement Courbet9d432e02018-12-04 07:59:57 +00003151 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003152 return false;
Clement Courbet9d432e02018-12-04 07:59:57 +00003153 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003154
3155private:
3156 const PrintingPolicy Policy;
3157};
3158
3159} // end anonymous namespace
Clement Courbet9d432e02018-12-04 07:59:57 +00003160
Douglas Gregor672281a2017-09-14 23:38:42 +00003161std::pair<Expr *, std::string>
Clement Courbetf44c6f42018-12-11 08:39:11 +00003162Sema::findFailedBooleanCondition(Expr *Cond) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003163 Cond = lookThroughRangesV3Condition(PP, Cond);
Douglas Gregorbb33f572017-07-05 20:20:15 +00003164
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003165 // Separate out all of the terms in a conjunction.
3166 SmallVector<Expr *, 4> Terms;
3167 collectConjunctionTerms(Cond, Terms);
3168
3169 // Determine which term failed.
3170 Expr *FailedCond = nullptr;
3171 for (Expr *Term : Terms) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003172 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3173
Clement Courbetd8720412018-12-10 08:53:17 +00003174 // Literals are uninteresting.
3175 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3176 isa<IntegerLiteral>(TermAsWritten))
3177 continue;
3178
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003179 // The initialization of the parameter from the argument is
3180 // a constant-evaluated context.
3181 EnterExpressionEvaluationContext ConstantEvaluated(
Douglas Gregor672281a2017-09-14 23:38:42 +00003182 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003183
3184 bool Succeeded;
Douglas Gregor672281a2017-09-14 23:38:42 +00003185 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003186 !Succeeded) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003187 FailedCond = TermAsWritten;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003188 break;
3189 }
3190 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003191 if (!FailedCond)
Clement Courbetd8720412018-12-10 08:53:17 +00003192 FailedCond = Cond->IgnoreParenImpCasts();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003193
3194 std::string Description;
3195 {
3196 llvm::raw_string_ostream Out(Description);
Clement Courbetfb2c74d2018-12-20 09:05:15 +00003197 PrintingPolicy Policy = getPrintingPolicy();
3198 Policy.PrintCanonicalTypes = true;
3199 FailedBooleanConditionPrinterHelper Helper(Policy);
3200 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003201 }
3202 return { FailedCond, Description };
3203}
3204
Douglas Gregordc572a32009-03-30 22:58:21 +00003205QualType Sema::CheckTemplateIdType(TemplateName Name,
3206 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003207 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00003208 DependentTemplateName *DTN
3209 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00003210 if (DTN && DTN->isIdentifier())
3211 // When building a template-id where the template-name is dependent,
3212 // assume the template is a type template. Either our assumption is
3213 // correct, or the code is ill-formed and will be diagnosed when the
3214 // dependent name is substituted.
3215 return Context.getDependentTemplateSpecializationType(ETK_None,
3216 DTN->getQualifier(),
3217 DTN->getIdentifier(),
3218 TemplateArgs);
3219
Douglas Gregordc572a32009-03-30 22:58:21 +00003220 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00003221 if (!Template || isa<FunctionTemplateDecl>(Template) ||
Faisal Valia534f072018-04-26 00:42:40 +00003222 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003223 // We might have a substituted template template parameter pack. If so,
3224 // build a template specialization type for it.
3225 if (Name.getAsSubstTemplateTemplateParmPack())
3226 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003227
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003228 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3229 << Name;
3230 NoteAllFoundTemplates(Name);
3231 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00003232 }
Douglas Gregordc572a32009-03-30 22:58:21 +00003233
Douglas Gregorc40290e2009-03-09 23:48:35 +00003234 // Check that the template argument list is well-formed for this
3235 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003236 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00003237 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003238 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00003239 return QualType();
3240
Douglas Gregorc40290e2009-03-09 23:48:35 +00003241 QualType CanonType;
3242
Douglas Gregor678d76c2011-07-01 01:22:09 +00003243 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00003244 if (TypeAliasTemplateDecl *AliasTemplate =
3245 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00003246 // Find the canonical type for this type alias template specialization.
3247 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3248 if (Pattern->isInvalidDecl())
3249 return QualType();
3250
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003251 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3252 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003253
3254 // Only substitute for the innermost template argument list.
3255 MultiLevelTemplateArgumentList TemplateArgLists;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003256 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00003257 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3258 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00003259 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003260
Richard Smith802c4b72012-08-23 06:16:52 +00003261 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003262 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003263 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003264 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00003265
Richard Smith3f1b5d02011-05-05 21:57:07 +00003266 CanonType = SubstType(Pattern->getUnderlyingType(),
3267 TemplateArgLists, AliasTemplate->getLocation(),
3268 AliasTemplate->getDeclName());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003269 if (CanonType.isNull()) {
3270 // If this was enable_if and we failed to find the nested type
3271 // within enable_if in a SFINAE context, dig out the specific
3272 // enable_if condition that failed and present that instead.
3273 if (isEnableIfAliasTemplate(AliasTemplate)) {
3274 if (auto DeductionInfo = isSFINAEContext()) {
3275 if (*DeductionInfo &&
3276 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3277 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3278 diag::err_typename_nested_not_found_enable_if &&
3279 TemplateArgs[0].getArgument().getKind()
3280 == TemplateArgument::Expression) {
3281 Expr *FailedCond;
3282 std::string FailedDescription;
3283 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00003284 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003285
3286 // Remove the old SFINAE diagnostic.
3287 PartialDiagnosticAt OldDiag =
3288 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3289 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3290
3291 // Add a new SFINAE diagnostic specifying which condition
3292 // failed.
3293 (*DeductionInfo)->addSFINAEDiagnostic(
3294 OldDiag.first,
3295 PDiag(diag::err_typename_nested_not_found_requirement)
3296 << FailedDescription
3297 << FailedCond->getSourceRange());
3298 }
3299 }
3300 }
3301
Richard Smith3f1b5d02011-05-05 21:57:07 +00003302 return QualType();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003303 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003304 } else if (Name.isDependent() ||
3305 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00003306 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003307 // This class template specialization is a dependent
3308 // type. Therefore, its canonical type is another class template
3309 // specialization type that contains all of the converted
3310 // arguments in canonical form. This ensures that, e.g., A<T> and
3311 // A<T, T> have identical types when A is declared as:
3312 //
3313 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003314 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00003315
3316 // This might work out to be a current instantiation, in which
3317 // case the canonical type needs to be the InjectedClassNameType.
3318 //
3319 // TODO: in theory this could be a simple hashtable lookup; most
3320 // changes to CurContext don't change the set of current
3321 // instantiations.
3322 if (isa<ClassTemplateDecl>(Template)) {
3323 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3324 // If we get out to a namespace, we're done.
3325 if (Ctx->isFileContext()) break;
3326
3327 // If this isn't a record, keep looking.
3328 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3329 if (!Record) continue;
3330
3331 // Look for one of the two cases with InjectedClassNameTypes
3332 // and check whether it's the same template.
3333 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3334 !Record->getDescribedClassTemplate())
3335 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336
John McCall2408e322010-04-27 00:57:59 +00003337 // Fetch the injected class name type and check whether its
3338 // injected type is equal to the type we just built.
3339 QualType ICNT = Context.getTypeDeclType(Record);
3340 QualType Injected = cast<InjectedClassNameType>(ICNT)
3341 ->getInjectedSpecializationType();
3342
3343 if (CanonType != Injected->getCanonicalTypeInternal())
3344 continue;
3345
3346 // If so, the canonical type of this TST is the injected
3347 // class name type of the record we just found.
3348 assert(ICNT.isCanonical());
3349 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00003350 break;
3351 }
3352 }
Mike Stump11289f42009-09-09 15:08:12 +00003353 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00003354 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003355 // Find the class template specialization declaration that
3356 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003357 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003358 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00003359 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003360 if (!Decl) {
3361 // This is the first time we have referenced this class template
3362 // specialization. Create the canonical declaration and add it to
3363 // the set of specializations.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003364 Decl = ClassTemplateSpecializationDecl::Create(
3365 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3366 ClassTemplate->getDeclContext(),
3367 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3368 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003369 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00003370 if (ClassTemplate->isOutOfLine())
3371 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00003372 }
3373
Erich Keanea32910d2017-03-23 18:51:54 +00003374 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3375 MultiLevelTemplateArgumentList TemplateArgLists;
3376 TemplateArgLists.addOuterTemplateArguments(Converted);
3377 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3378 Decl);
3379 }
3380
Chandler Carruth2acfb222013-09-27 22:14:40 +00003381 // Diagnose uses of this specialization.
3382 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3383
Douglas Gregorc40290e2009-03-09 23:48:35 +00003384 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00003385 assert(isa<RecordType>(CanonType) &&
3386 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003387 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3388 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3389 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003390 }
Mike Stump11289f42009-09-09 15:08:12 +00003391
Douglas Gregorc40290e2009-03-09 23:48:35 +00003392 // Build the fully-sugared type for this class template
3393 // specialization, which refers back to the class template
3394 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00003395 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003396}
3397
Richard Smithb23c5e82019-05-09 03:31:27 +00003398void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3399 TemplateNameKind &TNK,
3400 SourceLocation NameLoc,
3401 IdentifierInfo *&II) {
3402 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3403
3404 TemplateName Name = ParsedName.get();
3405 auto *ATN = Name.getAsAssumedTemplateName();
3406 assert(ATN && "not an assumed template name");
3407 II = ATN->getDeclName().getAsIdentifierInfo();
3408
3409 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3410 // Resolved to a type template name.
3411 ParsedName = TemplateTy::make(Name);
3412 TNK = TNK_Type_template;
3413 }
3414}
3415
3416bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3417 SourceLocation NameLoc,
3418 bool Diagnose) {
3419 // We assumed this undeclared identifier to be an (ADL-only) function
3420 // template name, but it was used in a context where a type was required.
3421 // Try to typo-correct it now.
3422 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3423 assert(ATN && "not an assumed template name");
3424
3425 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3426 struct CandidateCallback : CorrectionCandidateCallback {
3427 bool ValidateCandidate(const TypoCorrection &TC) override {
3428 return TC.getCorrectionDecl() &&
3429 getAsTypeTemplateDecl(TC.getCorrectionDecl());
3430 }
3431 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3432 return llvm::make_unique<CandidateCallback>(*this);
3433 }
3434 } FilterCCC;
3435
3436 TypoCorrection Corrected =
3437 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3438 FilterCCC, CTK_ErrorRecovery);
3439 if (Corrected && Corrected.getFoundDecl()) {
3440 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3441 << ATN->getDeclName());
3442 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3443 return false;
3444 }
3445
3446 if (Diagnose)
3447 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3448 return true;
3449}
3450
3451TypeResult Sema::ActOnTemplateIdType(
3452 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3453 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3454 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3455 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3456 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003457 if (SS.isInvalid())
3458 return true;
3459
Richard Smith62559bd2017-02-01 21:36:38 +00003460 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3461 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3462
3463 // C++ [temp.res]p3:
3464 // A qualified-id that refers to a type and in which the
3465 // nested-name-specifier depends on a template-parameter (14.6.2)
3466 // shall be prefixed by the keyword typename to indicate that the
3467 // qualified-id denotes a type, forming an
3468 // elaborated-type-specifier (7.1.5.3).
3469 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00003470 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00003471 << SS.getScopeRep() << TemplateII->getName();
3472 // Recover as if 'typename' were specified.
3473 // FIXME: This is not quite correct recovery as we don't transform SS
3474 // into the corresponding dependent form (and we don't diagnose missing
3475 // 'template' keywords within SS as a result).
3476 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3477 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3478 TemplateArgsIn, RAngleLoc);
3479 }
3480
3481 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3482 // it's not actually allowed to be used as a type in most cases. Because
3483 // we annotate it before we know whether it's valid, we have to check for
3484 // this case here.
3485 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00003486 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3487 Diag(TemplateIILoc,
3488 TemplateKWLoc.isInvalid()
3489 ? diag::err_out_of_line_qualified_id_type_names_constructor
3490 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3491 << TemplateII << 0 /*injected-class-name used as template name*/
3492 << 1 /*if any keyword was present, it was 'template'*/;
3493 }
3494 }
3495
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003496 TemplateName Template = TemplateD.get();
Richard Smithb23c5e82019-05-09 03:31:27 +00003497 if (Template.getAsAssumedTemplateName() &&
3498 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3499 return true;
Douglas Gregor8bf42052009-02-09 18:46:07 +00003500
Douglas Gregorc40290e2009-03-09 23:48:35 +00003501 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003502 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003503 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00003504
Douglas Gregor5a064722011-02-28 17:23:35 +00003505 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00003506 QualType T
3507 = Context.getDependentTemplateSpecializationType(ETK_None,
3508 DTN->getQualifier(),
3509 DTN->getIdentifier(),
3510 TemplateArgs);
3511 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00003512 TypeLocBuilder TLB;
3513 DependentTemplateSpecializationTypeLoc SpecTL
3514 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003515 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3516 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003517 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003518 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003519 SpecTL.setLAngleLoc(LAngleLoc);
3520 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003521 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3522 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3523 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3524 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003525
Richard Smith74f02342017-01-19 21:00:13 +00003526 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003527 if (Result.isNull())
3528 return true;
3529
Douglas Gregore7c20652011-03-02 00:47:37 +00003530 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003531 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00003532 TemplateSpecializationTypeLoc SpecTL
3533 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003534 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003535 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003536 SpecTL.setLAngleLoc(LAngleLoc);
3537 SpecTL.setRAngleLoc(RAngleLoc);
3538 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3539 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00003540
Abramo Bagnara4244b432012-01-27 08:46:19 +00003541 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3542 // constructor or destructor name (in such a case, the scope specifier
3543 // will be attached to the enclosing Decl or Expr node).
3544 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003545 // Create an elaborated-type-specifier containing the nested-name-specifier.
3546 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3547 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003548 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00003549 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3550 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003551
Douglas Gregore7c20652011-03-02 00:47:37 +00003552 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00003553}
John McCall06f6fe8d2009-09-04 01:14:41 +00003554
Douglas Gregore7c20652011-03-02 00:47:37 +00003555TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00003556 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00003557 SourceLocation TagLoc,
3558 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003559 SourceLocation TemplateKWLoc,
3560 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00003561 SourceLocation TemplateLoc,
3562 SourceLocation LAngleLoc,
3563 ASTTemplateArgsPtr TemplateArgsIn,
3564 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003565 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003566
Douglas Gregore7c20652011-03-02 00:47:37 +00003567 // Translate the parser's template argument list in our AST format.
3568 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3569 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003570
Douglas Gregore7c20652011-03-02 00:47:37 +00003571 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00003572 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00003573 ElaboratedTypeKeyword Keyword
3574 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00003575
Douglas Gregore7c20652011-03-02 00:47:37 +00003576 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3577 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00003578 DTN->getQualifier(),
3579 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00003580 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003581
3582 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00003583 TypeLocBuilder TLB;
3584 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003585 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3586 SpecTL.setElaboratedKeywordLoc(TagLoc);
3587 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003588 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003589 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003590 SpecTL.setLAngleLoc(LAngleLoc);
3591 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003592 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3593 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3594 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3595 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003596
3597 if (TypeAliasTemplateDecl *TAT =
3598 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3599 // C++0x [dcl.type.elab]p2:
3600 // If the identifier resolves to a typedef-name or the simple-template-id
3601 // resolves to an alias template specialization, the
3602 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003603 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3604 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003605 Diag(TAT->getLocation(), diag::note_declared_at);
3606 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003607
Douglas Gregore7c20652011-03-02 00:47:37 +00003608 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3609 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003610 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003611
Douglas Gregore7c20652011-03-02 00:47:37 +00003612 // Check the tag kind
3613 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003614 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003615
John McCalld8fe9af2009-09-08 17:47:29 +00003616 IdentifierInfo *Id = D->getIdentifier();
3617 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003618
Richard Trieucaa33d32011-06-10 03:11:26 +00003619 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003620 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003621 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003622 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003623 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003624 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003625 }
3626 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003627
Douglas Gregore7c20652011-03-02 00:47:37 +00003628 // Provide source-location information for the template specialization.
3629 TypeLocBuilder TLB;
3630 TemplateSpecializationTypeLoc SpecTL
3631 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003632 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003633 SpecTL.setTemplateNameLoc(TemplateLoc);
3634 SpecTL.setLAngleLoc(LAngleLoc);
3635 SpecTL.setRAngleLoc(RAngleLoc);
3636 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3637 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003638
Douglas Gregore7c20652011-03-02 00:47:37 +00003639 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003640 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003641 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3642 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003643 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003644 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3645 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003646}
3647
Larisse Voufo39a1e502013-08-06 01:03:05 +00003648static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3649 NamedDecl *PrevDecl,
3650 SourceLocation Loc,
3651 bool IsPartialSpecialization);
3652
3653static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003654
Richard Smith300e0c32013-09-24 04:49:23 +00003655static bool isTemplateArgumentTemplateParameter(
3656 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3657 switch (Arg.getKind()) {
3658 case TemplateArgument::Null:
3659 case TemplateArgument::NullPtr:
3660 case TemplateArgument::Integral:
3661 case TemplateArgument::Declaration:
3662 case TemplateArgument::Pack:
3663 case TemplateArgument::TemplateExpansion:
3664 return false;
3665
3666 case TemplateArgument::Type: {
3667 QualType Type = Arg.getAsType();
3668 const TemplateTypeParmType *TPT =
3669 Arg.getAsType()->getAs<TemplateTypeParmType>();
3670 return TPT && !Type.hasQualifiers() &&
3671 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3672 }
3673
3674 case TemplateArgument::Expression: {
3675 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3676 if (!DRE || !DRE->getDecl())
3677 return false;
3678 const NonTypeTemplateParmDecl *NTTP =
3679 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3680 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3681 }
3682
3683 case TemplateArgument::Template:
3684 const TemplateTemplateParmDecl *TTP =
3685 dyn_cast_or_null<TemplateTemplateParmDecl>(
3686 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3687 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3688 }
3689 llvm_unreachable("unexpected kind of template argument");
3690}
3691
3692static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3693 ArrayRef<TemplateArgument> Args) {
3694 if (Params->size() != Args.size())
3695 return false;
3696
3697 unsigned Depth = Params->getDepth();
3698
3699 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3700 TemplateArgument Arg = Args[I];
3701
3702 // If the parameter is a pack expansion, the argument must be a pack
3703 // whose only element is a pack expansion.
3704 if (Params->getParam(I)->isParameterPack()) {
3705 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3706 !Arg.pack_begin()->isPackExpansion())
3707 return false;
3708 Arg = Arg.pack_begin()->getPackExpansionPattern();
3709 }
3710
3711 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3712 return false;
3713 }
3714
3715 return true;
3716}
3717
Richard Smith4b55a9c2014-04-17 03:29:33 +00003718/// Convert the parser's template argument list representation into our form.
3719static TemplateArgumentListInfo
3720makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3721 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3722 TemplateId.RAngleLoc);
3723 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3724 TemplateId.NumArgs);
3725 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3726 return TemplateArgs;
3727}
3728
Richard Smith0e617ec2016-12-27 07:56:27 +00003729template<typename PartialSpecDecl>
3730static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3731 if (Partial->getDeclContext()->isDependentContext())
3732 return;
3733
3734 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3735 // for non-substitution-failure issues?
3736 TemplateDeductionInfo Info(Partial->getLocation());
3737 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3738 return;
3739
3740 auto *Template = Partial->getSpecializedTemplate();
3741 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003742 diag::ext_partial_spec_not_more_specialized_than_primary)
3743 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003744
3745 if (Info.hasSFINAEDiagnostic()) {
3746 PartialDiagnosticAt Diag = {SourceLocation(),
3747 PartialDiagnostic::NullDiagnostic()};
3748 Info.takeSFINAEDiagnostic(Diag);
3749 SmallString<128> SFINAEArgString;
3750 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3751 S.Diag(Diag.first,
3752 diag::note_partial_spec_not_more_specialized_than_primary)
3753 << SFINAEArgString;
3754 }
3755
3756 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3757}
3758
Richard Smith4e05eaa2017-02-16 00:36:47 +00003759static void
3760noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3761 const llvm::SmallBitVector &DeducibleParams) {
3762 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3763 if (!DeducibleParams[I]) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00003764 NamedDecl *Param = TemplateParams->getParam(I);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003765 if (Param->getDeclName())
3766 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3767 << Param->getDeclName();
3768 else
3769 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3770 << "(anonymous)";
3771 }
3772 }
3773}
3774
3775
Richard Smith57aae072016-12-28 02:37:25 +00003776template<typename PartialSpecDecl>
3777static void checkTemplatePartialSpecialization(Sema &S,
3778 PartialSpecDecl *Partial) {
3779 // C++1z [temp.class.spec]p8: (DR1495)
3780 // - The specialization shall be more specialized than the primary
3781 // template (14.5.5.2).
3782 checkMoreSpecializedThanPrimary(S, Partial);
3783
3784 // C++ [temp.class.spec]p8: (DR1315)
3785 // - Each template-parameter shall appear at least once in the
3786 // template-id outside a non-deduced context.
3787 // C++1z [temp.class.spec.match]p3 (P0127R2)
3788 // If the template arguments of a partial specialization cannot be
3789 // deduced because of the structure of its template-parameter-list
3790 // and the template-id, the program is ill-formed.
3791 auto *TemplateParams = Partial->getTemplateParameters();
3792 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3793 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3794 TemplateParams->getDepth(), DeducibleParams);
3795
3796 if (!DeducibleParams.all()) {
3797 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3798 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3799 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3800 << (NumNonDeducible > 1)
3801 << SourceRange(Partial->getLocation(),
3802 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003803 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003804 }
3805}
3806
3807void Sema::CheckTemplatePartialSpecialization(
3808 ClassTemplatePartialSpecializationDecl *Partial) {
3809 checkTemplatePartialSpecialization(*this, Partial);
3810}
3811
3812void Sema::CheckTemplatePartialSpecialization(
3813 VarTemplatePartialSpecializationDecl *Partial) {
3814 checkTemplatePartialSpecialization(*this, Partial);
3815}
3816
Richard Smith4e05eaa2017-02-16 00:36:47 +00003817void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3818 // C++1z [temp.param]p11:
3819 // A template parameter of a deduction guide template that does not have a
3820 // default-argument shall be deducible from the parameter-type-list of the
3821 // deduction guide template.
3822 auto *TemplateParams = TD->getTemplateParameters();
3823 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3824 MarkDeducedTemplateParameters(TD, DeducibleParams);
3825 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3826 // A parameter pack is deducible (to an empty pack).
3827 auto *Param = TemplateParams->getParam(I);
3828 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3829 DeducibleParams[I] = true;
3830 }
3831
3832 if (!DeducibleParams.all()) {
3833 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3834 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3835 << (NumNonDeducible > 1);
3836 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3837 }
3838}
3839
Larisse Voufo39a1e502013-08-06 01:03:05 +00003840DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003841 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003842 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003843 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003844 // D must be variable template id.
Faisal Vali2ab8c152017-12-30 04:15:27 +00003845 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003846 "Variable template specialization is declared with a template it.");
3847
3848 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003849 TemplateArgumentListInfo TemplateArgs =
3850 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003851 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3852 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3853 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003854
Richard Smithbeef3452014-01-16 23:39:20 +00003855 TemplateName Name = TemplateId->Template.get();
3856
3857 // The template-id must name a variable template.
3858 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003859 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3860 if (!VarTemplate) {
3861 NamedDecl *FnTemplate;
3862 if (auto *OTS = Name.getAsOverloadedTemplate())
3863 FnTemplate = *OTS->begin();
3864 else
3865 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3866 if (FnTemplate)
3867 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3868 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003869 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3870 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003871 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003872
3873 // Check for unexpanded parameter packs in any of the template arguments.
3874 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3875 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3876 UPPC_PartialSpecialization))
3877 return true;
3878
3879 // Check that the template argument list is well-formed for this
3880 // template.
3881 SmallVector<TemplateArgument, 4> Converted;
3882 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3883 false, Converted))
3884 return true;
3885
Larisse Voufo39a1e502013-08-06 01:03:05 +00003886 // Find the variable template (partial) specialization declaration that
3887 // corresponds to these arguments.
3888 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003889 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3890 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003891 return true;
3892
Richard Smith57aae072016-12-28 02:37:25 +00003893 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3894 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003895 bool InstantiationDependent;
3896 if (!Name.isDependent() &&
3897 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003898 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003899 InstantiationDependent)) {
3900 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3901 << VarTemplate->getDeclName();
3902 IsPartialSpecialization = false;
3903 }
Richard Smith300e0c32013-09-24 04:49:23 +00003904
3905 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3906 Converted)) {
3907 // C++ [temp.class.spec]p9b3:
3908 //
3909 // -- The argument list of the specialization shall not be identical
3910 // to the implicit argument list of the primary template.
3911 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3912 << /*variable template*/ 1
3913 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3914 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3915 // FIXME: Recover from this by treating the declaration as a redeclaration
3916 // of the primary template.
3917 return true;
3918 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003919 }
3920
Craig Topperc3ec1492014-05-26 06:22:03 +00003921 void *InsertPos = nullptr;
3922 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003923
3924 if (IsPartialSpecialization)
3925 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003926 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003927 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003928 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003929
Craig Topperc3ec1492014-05-26 06:22:03 +00003930 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003931
3932 // Check whether we can declare a variable template specialization in
3933 // the current scope.
3934 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3935 TemplateNameLoc,
3936 IsPartialSpecialization))
3937 return true;
3938
3939 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3940 // Since the only prior variable template specialization with these
3941 // arguments was referenced but not declared, reuse that
3942 // declaration node as our own, updating its source location and
3943 // the list of outer template parameters to reflect our new declaration.
3944 Specialization = PrevDecl;
3945 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003946 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003947 } else if (IsPartialSpecialization) {
3948 // Create a new class template partial specialization declaration node.
3949 VarTemplatePartialSpecializationDecl *PrevPartial =
3950 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003951 VarTemplatePartialSpecializationDecl *Partial =
3952 VarTemplatePartialSpecializationDecl::Create(
3953 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3954 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003955 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003956
3957 if (!PrevPartial)
3958 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3959 Specialization = Partial;
3960
3961 // If we are providing an explicit specialization of a member variable
3962 // template specialization, make a note of that.
3963 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003964 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003965
Richard Smith57aae072016-12-28 02:37:25 +00003966 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003967 } else {
3968 // Create a new class template specialization declaration node for
3969 // this explicit specialization or friend declaration.
3970 Specialization = VarTemplateSpecializationDecl::Create(
3971 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003972 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003973 Specialization->setTemplateArgsInfo(TemplateArgs);
3974
3975 if (!PrevDecl)
3976 VarTemplate->AddSpecialization(Specialization, InsertPos);
3977 }
3978
3979 // C++ [temp.expl.spec]p6:
3980 // If a template, a member template or the member of a class template is
3981 // explicitly specialized then that specialization shall be declared
3982 // before the first use of that specialization that would cause an implicit
3983 // instantiation to take place, in every translation unit in which such a
3984 // use occurs; no diagnostic is required.
3985 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3986 bool Okay = false;
3987 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3988 // Is there any previous explicit specialization declaration?
3989 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3990 Okay = true;
3991 break;
3992 }
3993 }
3994
3995 if (!Okay) {
3996 SourceRange Range(TemplateNameLoc, RAngleLoc);
3997 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3998 << Name << Range;
3999
4000 Diag(PrevDecl->getPointOfInstantiation(),
4001 diag::note_instantiation_required_here)
4002 << (PrevDecl->getTemplateSpecializationKind() !=
4003 TSK_ImplicitInstantiation);
4004 return true;
4005 }
4006 }
4007
4008 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4009 Specialization->setLexicalDeclContext(CurContext);
4010
4011 // Add the specialization into its lexical context, so that it can
4012 // be seen when iterating through the list of declarations in that
4013 // context. However, specializations are not found by name lookup.
4014 CurContext->addDecl(Specialization);
4015
4016 // Note that this is an explicit specialization.
4017 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4018
4019 if (PrevDecl) {
4020 // Check that this isn't a redefinition of this specialization,
4021 // merging with previous declarations.
4022 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00004023 forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004024 PrevSpec.addDecl(PrevDecl);
4025 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00004026 } else if (Specialization->isStaticDataMember() &&
4027 Specialization->isOutOfLine()) {
4028 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004029 }
4030
Larisse Voufo39a1e502013-08-06 01:03:05 +00004031 return Specialization;
4032}
4033
4034namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004035/// A partial specialization whose template arguments have matched
Larisse Voufo39a1e502013-08-06 01:03:05 +00004036/// a given template-id.
4037struct PartialSpecMatchResult {
4038 VarTemplatePartialSpecializationDecl *Partial;
4039 TemplateArgumentList *Args;
4040};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004041} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00004042
4043DeclResult
4044Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4045 SourceLocation TemplateNameLoc,
4046 const TemplateArgumentListInfo &TemplateArgs) {
4047 assert(Template && "A variable template id without template?");
4048
4049 // Check that the template argument list is well-formed for this template.
4050 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004051 if (CheckTemplateArgumentList(
4052 Template, TemplateNameLoc,
4053 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00004054 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00004055 return true;
4056
4057 // Find the variable template specialization declaration that
4058 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00004059 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004060 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00004061 Converted, InsertPos)) {
4062 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004063 // If we already have a variable template specialization, return it.
4064 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00004065 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004066
4067 // This is the first time we have referenced this variable template
4068 // specialization. Create the canonical declaration and add it to
4069 // the set of specializations, based on the closest partial specialization
4070 // that it represents. That is,
4071 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4072 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004073 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004074 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4075 bool AmbiguousPartialSpec = false;
4076 typedef PartialSpecMatchResult MatchResult;
4077 SmallVector<MatchResult, 4> Matched;
4078 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00004079 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4080 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004081
4082 // 1. Attempt to find the closest partial specialization that this
4083 // specializes, if any.
4084 // If any of the template arguments is dependent, then this is probably
4085 // a placeholder for an incomplete declarative context; which must be
4086 // complete by instantiation time. Thus, do not search through the partial
4087 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00004088 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4089 // Perhaps better after unification of DeduceTemplateArguments() and
4090 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00004091 bool InstantiationDependent = false;
4092 if (!TemplateSpecializationType::anyDependentTemplateArguments(
4093 TemplateArgs, InstantiationDependent)) {
4094
4095 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4096 Template->getPartialSpecializations(PartialSpecs);
4097
4098 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4099 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4100 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4101
4102 if (TemplateDeductionResult Result =
4103 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4104 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00004105 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00004106 FailedCandidates.addCandidate().set(
4107 DeclAccessPair::make(Template, AS_public), Partial,
4108 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00004109 (void)Result;
4110 } else {
4111 Matched.push_back(PartialSpecMatchResult());
4112 Matched.back().Partial = Partial;
4113 Matched.back().Args = Info.take();
4114 }
4115 }
4116
Larisse Voufo39a1e502013-08-06 01:03:05 +00004117 if (Matched.size() >= 1) {
4118 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4119 if (Matched.size() == 1) {
4120 // -- If exactly one matching specialization is found, the
4121 // instantiation is generated from that specialization.
4122 // We don't need to do anything for this.
4123 } else {
4124 // -- If more than one matching specialization is found, the
4125 // partial order rules (14.5.4.2) are used to determine
4126 // whether one of the specializations is more specialized
4127 // than the others. If none of the specializations is more
4128 // specialized than all of the other matching
4129 // specializations, then the use of the variable template is
4130 // ambiguous and the program is ill-formed.
4131 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4132 PEnd = Matched.end();
4133 P != PEnd; ++P) {
4134 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4135 PointOfInstantiation) ==
4136 P->Partial)
4137 Best = P;
4138 }
4139
4140 // Determine if the best partial specialization is more specialized than
4141 // the others.
4142 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4143 PEnd = Matched.end();
4144 P != PEnd; ++P) {
4145 if (P != Best && getMoreSpecializedPartialSpecialization(
4146 P->Partial, Best->Partial,
4147 PointOfInstantiation) != Best->Partial) {
4148 AmbiguousPartialSpec = true;
4149 break;
4150 }
4151 }
4152 }
4153
4154 // Instantiate using the best variable template partial specialization.
4155 InstantiationPattern = Best->Partial;
4156 InstantiationArgs = Best->Args;
4157 } else {
4158 // -- If no match is found, the instantiation is generated
4159 // from the primary template.
4160 // InstantiationPattern = Template->getTemplatedDecl();
4161 }
4162 }
4163
Larisse Voufo39a1e502013-08-06 01:03:05 +00004164 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00004165 // Note that we do not instantiate a definition until we see an odr-use
4166 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00004167 // FIXME: LateAttrs et al.?
4168 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4169 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4170 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4171 if (!Decl)
4172 return true;
4173
4174 if (AmbiguousPartialSpec) {
4175 // Partial ordering did not produce a clear winner. Complain.
4176 Decl->setInvalidDecl();
4177 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4178 << Decl;
4179
4180 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00004181 for (MatchResult P : Matched)
4182 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4183 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4184 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004185 return true;
4186 }
4187
4188 if (VarTemplatePartialSpecializationDecl *D =
4189 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4190 Decl->setInstantiationOf(D, InstantiationArgs);
4191
Richard Smith6739a102016-05-05 00:56:12 +00004192 checkSpecializationVisibility(TemplateNameLoc, Decl);
4193
Larisse Voufo39a1e502013-08-06 01:03:05 +00004194 assert(Decl && "No variable template specialization?");
4195 return Decl;
4196}
4197
4198ExprResult
4199Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4200 const DeclarationNameInfo &NameInfo,
4201 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4202 const TemplateArgumentListInfo *TemplateArgs) {
4203
4204 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4205 *TemplateArgs);
4206 if (Decl.isInvalid())
4207 return ExprError();
4208
4209 VarDecl *Var = cast<VarDecl>(Decl.get());
4210 if (!Var->getTemplateSpecializationKind())
4211 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4212 NameInfo.getLoc());
4213
4214 // Build an ordinary singleton decl ref.
4215 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00004216 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004217}
4218
Richard Smithecad88d2018-04-26 01:08:00 +00004219void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4220 SourceLocation Loc) {
4221 Diag(Loc, diag::err_template_missing_args)
4222 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4223 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4224 Diag(TD->getLocation(), diag::note_template_decl_here)
4225 << TD->getTemplateParameters()->getSourceRange();
4226 }
4227}
4228
John McCalldadc5752010-08-24 06:29:42 +00004229ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004230 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00004231 LookupResult &R,
4232 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004233 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00004234 // FIXME: Can we do any checking at this point? I guess we could check the
4235 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00004236 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00004237 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00004238 // foo<int> could identify a single function unambiguously
4239 // This approach does NOT work, since f<int>(1);
4240 // gets resolved prior to resorting to overload resolution
4241 // i.e., template<class T> void f(double);
4242 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00004243
4244 // These should be filtered out by our callers.
John McCalle66edc12009-11-24 19:00:30 +00004245 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4246
Richard Smith04100942018-04-26 02:10:22 +00004247 // Non-function templates require a template argument list.
4248 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4249 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4250 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4251 return ExprError();
4252 }
4253 }
4254
Richard Smith0bf96f92018-04-25 22:58:55 +00004255 auto AnyDependentArguments = [&]() -> bool {
4256 bool InstantiationDependent;
4257 return TemplateArgs &&
4258 TemplateSpecializationType::anyDependentTemplateArguments(
4259 *TemplateArgs, InstantiationDependent);
4260 };
4261
Larisse Voufo39a1e502013-08-06 01:03:05 +00004262 // In C++1y, check variable template ids.
Richard Smith0bf96f92018-04-25 22:58:55 +00004263 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
Richard Smithd7d11ef2014-02-03 20:09:56 +00004264 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4265 R.getAsSingle<VarTemplateDecl>(),
4266 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004267 }
4268
John McCall58cc69d2010-01-27 01:50:18 +00004269 // We don't want lookup warnings at this point.
4270 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004271
John McCalle66edc12009-11-24 19:00:30 +00004272 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00004273 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00004274 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004275 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004276 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004277 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00004278 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00004279
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004280 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00004281}
4282
John McCalle66edc12009-11-24 19:00:30 +00004283// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00004284ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004285Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004286 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004287 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004288 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004289
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004290 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00004291 DeclContext *DC;
4292 if (!(DC = computeDeclContext(SS, false)) ||
4293 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00004294 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00004295 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004296
Douglas Gregor786123d2010-05-21 23:18:07 +00004297 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004298 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +00004299 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4300 /*Entering*/false, MemberOfUnknownSpecialization,
4301 TemplateKWLoc))
4302 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004303
John McCalle66edc12009-11-24 19:00:30 +00004304 if (R.isAmbiguous())
4305 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306
John McCalle66edc12009-11-24 19:00:30 +00004307 if (R.empty()) {
Richard Smith79810042018-05-11 02:43:08 +00004308 Diag(NameInfo.getLoc(), diag::err_no_member)
4309 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004310 return ExprError();
4311 }
4312
4313 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004314 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00004315 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00004316 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004317 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4318 return ExprError();
4319 }
4320
Abramo Bagnara7945c982012-01-27 09:46:47 +00004321 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00004322}
4323
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004324/// Form a dependent template name.
Douglas Gregorb67535d2009-03-31 00:43:58 +00004325///
4326/// This action forms a dependent template name given the template
4327/// name and its (presumably dependent) scope specifier. For
4328/// example, given "MetaFun::template apply", the scope specifier \p
4329/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4330/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004331TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00004332 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004333 SourceLocation TemplateKWLoc,
Richard Smithc08b6932018-04-27 02:00:13 +00004334 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00004335 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00004336 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00004337 TemplateTy &Result,
4338 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004339 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4340 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004341 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004342 diag::warn_cxx98_compat_template_outside_of_template :
4343 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344 << FixItHint::CreateRemoval(TemplateKWLoc);
4345
Craig Topperc3ec1492014-05-26 06:22:03 +00004346 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00004347 if (SS.isSet())
4348 LookupCtx = computeDeclContext(SS, EnteringContext);
4349 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00004350 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00004351 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00004352 // C++0x [temp.names]p5:
4353 // If a name prefixed by the keyword template is not the name of
4354 // a template, the program is ill-formed. [Note: the keyword
4355 // template may not be applied to non-template members of class
4356 // templates. -end note ] [ Note: as is the case with the
4357 // typename prefix, the template prefix is allowed in cases
4358 // where it is not strictly necessary; i.e., when the
4359 // nested-name-specifier or the expression on the left of the ->
4360 // or . is not dependent on a template-parameter, or the use
4361 // does not appear in the scope of a template. -end note]
4362 //
4363 // Note: C++03 was more strict here, because it banned the use of
4364 // the "template" keyword prior to a template-name that was not a
4365 // dependent name. C++ DR468 relaxed this requirement (the
4366 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00004367 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00004368 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00004369 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00004370 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00004371 MemberOfUnknownSpecialization);
Richard Smith79810042018-05-11 02:43:08 +00004372 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
Douglas Gregorbb119652010-06-16 23:00:59 +00004373 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00004374 } else if (TNK == TNK_Non_template) {
Richard Smith79810042018-05-11 02:43:08 +00004375 // Do the lookup again to determine if this is a "nothing found" case or
4376 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4377 // need to do this.
4378 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004379 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
Richard Smith79810042018-05-11 02:43:08 +00004380 LookupOrdinaryName);
4381 bool MOUS;
4382 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
Richard Smithafcfb6b2019-02-15 21:53:07 +00004383 MOUS, TemplateKWLoc) && !R.isAmbiguous())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004384 Diag(Name.getBeginLoc(), diag::err_no_member)
Richard Smith79810042018-05-11 02:43:08 +00004385 << DNI.getName() << LookupCtx << SS.getRange();
Douglas Gregorbb119652010-06-16 23:00:59 +00004386 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00004387 } else {
4388 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00004389 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4390 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
Faisal Vali2ab8c152017-12-30 04:15:27 +00004391 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4392 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
Richard Smithfd3dae02017-01-20 00:20:39 +00004393 // C++14 [class.qual]p2:
4394 // In a lookup in which function names are not ignored and the
4395 // nested-name-specifier nominates a class C, if the name specified
4396 // [...] is the injected-class-name of C, [...] the name is instead
4397 // considered to name the constructor
4398 //
4399 // We don't get here if naming the constructor would be valid, so we
4400 // just reject immediately and recover by treating the
4401 // injected-class-name as naming the template.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004402 Diag(Name.getBeginLoc(),
Richard Smithfd3dae02017-01-20 00:20:39 +00004403 diag::ext_out_of_line_qualified_id_type_names_constructor)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004404 << Name.Identifier
4405 << 0 /*injected-class-name used as template name*/
4406 << 1 /*'template' keyword was used*/;
Richard Smithfd3dae02017-01-20 00:20:39 +00004407 }
Douglas Gregorbb119652010-06-16 23:00:59 +00004408 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004409 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00004410 }
4411
Aaron Ballman4a979672014-01-03 13:56:08 +00004412 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004413
Douglas Gregor3cf81312009-11-03 23:16:33 +00004414 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00004415 case UnqualifiedIdKind::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004416 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00004417 Name.Identifier));
4418 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419
Faisal Vali2ab8c152017-12-30 04:15:27 +00004420 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00004421 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00004422 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00004423 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00004424
Faisal Vali2ab8c152017-12-30 04:15:27 +00004425 case UnqualifiedIdKind::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00004426 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00004427
Douglas Gregor3cf81312009-11-03 23:16:33 +00004428 default:
4429 break;
4430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004432 Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4433 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4434 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004435 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004436}
4437
Mike Stump11289f42009-09-09 15:08:12 +00004438bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004439 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004440 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00004441 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00004442 QualType ArgType;
4443 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00004444
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004445 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004446 switch(Arg.getKind()) {
4447 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004448 // C++ [temp.arg.type]p1:
4449 // A template-argument for a template-parameter which is a
4450 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00004451 ArgType = Arg.getAsType();
4452 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004453 break;
Richard Smith77a9c602018-02-28 03:02:23 +00004454 case TemplateArgument::Template:
4455 case TemplateArgument::TemplateExpansion: {
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004456 // We have a template type parameter but the template argument
4457 // is a template without any arguments.
4458 SourceRange SR = AL.getSourceRange();
Richard Smith77a9c602018-02-28 03:02:23 +00004459 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
Richard Smithecad88d2018-04-26 01:08:00 +00004460 diagnoseMissingTemplateArguments(Name, SR.getEnd());
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004461 return true;
4462 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004463 case TemplateArgument::Expression: {
4464 // We have a template type parameter but the template argument is an
4465 // expression; see if maybe it is missing the "typename" keyword.
4466 CXXScopeSpec SS;
4467 DeclarationNameInfo NameInfo;
4468
4469 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4470 SS.Adopt(ArgExpr->getQualifierLoc());
4471 NameInfo = ArgExpr->getNameInfo();
4472 } else if (DependentScopeDeclRefExpr *ArgExpr =
4473 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4474 SS.Adopt(ArgExpr->getQualifierLoc());
4475 NameInfo = ArgExpr->getNameInfo();
4476 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4477 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004478 if (ArgExpr->isImplicitAccess()) {
4479 SS.Adopt(ArgExpr->getQualifierLoc());
4480 NameInfo = ArgExpr->getMemberNameInfo();
4481 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004482 }
4483
Reid Kleckner377c1592014-06-10 23:29:48 +00004484 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004485 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4486 LookupParsedName(Result, CurScope, &SS);
4487
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004488 if (Result.getAsSingle<TypeDecl>() ||
4489 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00004490 LookupResult::NotFoundInCurrentInstantiation) {
4491 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004492 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00004493 Diag(Loc, getLangOpts().MSVCCompat
4494 ? diag::ext_ms_template_type_arg_missing_typename
4495 : diag::err_template_arg_must_be_type_suggest)
4496 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004497 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00004498
4499 // Recover by synthesizing a type using the location information that we
4500 // already have.
4501 ArgType =
4502 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4503 TypeLocBuilder TLB;
4504 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4505 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4506 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4507 TL.setNameLoc(NameInfo.getLoc());
4508 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4509
4510 // Overwrite our input TemplateArgumentLoc so that we can recover
4511 // properly.
4512 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4513 TemplateArgumentLocInfo(TSI));
4514
4515 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004516 }
4517 }
4518 // fallthrough
Galina Kistanova3779cb32017-06-07 06:25:05 +00004519 LLVM_FALLTHROUGH;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004520 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004521 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004522 // We have a template type parameter but the template argument
4523 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00004524 SourceRange SR = AL.getSourceRange();
4525 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004526 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00004527
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004528 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004529 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004530 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004531
Reid Kleckner377c1592014-06-10 23:29:48 +00004532 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004533 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004534
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004535 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00004536 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004537
Douglas Gregore46db902011-06-17 22:11:49 +00004538 // Objective-C ARC:
4539 // If an explicitly-specified template argument type is a lifetime type
4540 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004541 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00004542 ArgType->isObjCLifetimeType() &&
4543 !ArgType.getObjCLifetime()) {
4544 Qualifiers Qs;
4545 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4546 ArgType = Context.getQualifiedType(ArgType, Qs);
4547 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004548
Douglas Gregore46db902011-06-17 22:11:49 +00004549 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004550 return false;
4551}
4552
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004553/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004554/// the given template type parameter.
4555///
4556/// \param SemaRef the semantic analysis object for which we are performing
4557/// the substitution.
4558///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004559/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004560/// for.
4561///
4562/// \param TemplateLoc the location of the template name that started the
4563/// template-id we are checking.
4564///
4565/// \param RAngleLoc the location of the right angle bracket ('>') that
4566/// terminates the template-id.
4567///
4568/// \param Param the template template parameter whose default we are
4569/// substituting into.
4570///
4571/// \param Converted the list of template arguments provided for template
4572/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004573/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00004574static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004575SubstDefaultTemplateArgument(Sema &SemaRef,
4576 TemplateDecl *Template,
4577 SourceLocation TemplateLoc,
4578 SourceLocation RAngleLoc,
4579 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00004580 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00004581 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004582
4583 // If the argument type is dependent, instantiate it now based
4584 // on the previously-computed template arguments.
Erik Pilkingtonba88e212018-11-12 21:31:06 +00004585 if (ArgType->getType()->isInstantiationDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004586 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004587 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004588 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004589 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004590 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004591
David Majnemer8b622692016-07-03 21:17:51 +00004592 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004593
4594 // Only substitute for the innermost template argument list.
4595 MultiLevelTemplateArgumentList TemplateArgLists;
4596 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4597 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4598 TemplateArgLists.addOuterTemplateArguments(None);
4599
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004600 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004601 ArgType =
4602 SemaRef.SubstType(ArgType, TemplateArgLists,
4603 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004604 }
4605
4606 return ArgType;
4607}
4608
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004609/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004610/// the given non-type template parameter.
4611///
4612/// \param SemaRef the semantic analysis object for which we are performing
4613/// the substitution.
4614///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004615/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004616/// for.
4617///
4618/// \param TemplateLoc the location of the template name that started the
4619/// template-id we are checking.
4620///
4621/// \param RAngleLoc the location of the right angle bracket ('>') that
4622/// terminates the template-id.
4623///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004624/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004625/// substituting into.
4626///
4627/// \param Converted the list of template arguments provided for template
4628/// parameters that precede \p Param in the template parameter list.
4629///
4630/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004631static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004632SubstDefaultTemplateArgument(Sema &SemaRef,
4633 TemplateDecl *Template,
4634 SourceLocation TemplateLoc,
4635 SourceLocation RAngleLoc,
4636 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004637 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004638 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004639 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004640 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004641 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004642 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004643
David Majnemer8b622692016-07-03 21:17:51 +00004644 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004645
4646 // Only substitute for the innermost template argument list.
4647 MultiLevelTemplateArgumentList TemplateArgLists;
4648 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4649 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4650 TemplateArgLists.addOuterTemplateArguments(None);
4651
Faisal Valid143a0c2017-04-01 21:30:49 +00004652 EnterExpressionEvaluationContext ConstantEvaluated(
4653 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004654 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004655}
4656
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004657/// Substitute template arguments into the default template argument for
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004658/// the given template template parameter.
4659///
4660/// \param SemaRef the semantic analysis object for which we are performing
4661/// the substitution.
4662///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004663/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004664/// for.
4665///
4666/// \param TemplateLoc the location of the template name that started the
4667/// template-id we are checking.
4668///
4669/// \param RAngleLoc the location of the right angle bracket ('>') that
4670/// terminates the template-id.
4671///
4672/// \param Param the template template parameter whose default we are
4673/// substituting into.
4674///
4675/// \param Converted the list of template arguments provided for template
4676/// parameters that precede \p Param in the template parameter list.
4677///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004678/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004679/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004680///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004681/// \returns the substituted template argument, or NULL if an error occurred.
4682static TemplateName
4683SubstDefaultTemplateArgument(Sema &SemaRef,
4684 TemplateDecl *Template,
4685 SourceLocation TemplateLoc,
4686 SourceLocation RAngleLoc,
4687 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004688 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004689 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004690 Sema::InstantiatingTemplate Inst(
4691 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4692 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004693 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004694 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004695
David Majnemer8b622692016-07-03 21:17:51 +00004696 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004697
4698 // Only substitute for the innermost template argument list.
4699 MultiLevelTemplateArgumentList TemplateArgLists;
4700 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4701 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4702 TemplateArgLists.addOuterTemplateArguments(None);
4703
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004704 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004705 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004706 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004707 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004708 QualifierLoc =
4709 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004710 if (!QualifierLoc)
4711 return TemplateName();
4712 }
David Majnemer89189202013-08-28 23:48:32 +00004713
4714 return SemaRef.SubstTemplateName(
4715 QualifierLoc,
4716 Param->getDefaultArgument().getArgument().getAsTemplate(),
4717 Param->getDefaultArgument().getTemplateNameLoc(),
4718 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004719}
4720
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004721/// If the given template parameter has a default template
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004722/// argument, substitute into that default template argument and
4723/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004724TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004725Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4726 SourceLocation TemplateLoc,
4727 SourceLocation RAngleLoc,
4728 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004729 SmallVectorImpl<TemplateArgument>
4730 &Converted,
4731 bool &HasDefaultArg) {
4732 HasDefaultArg = false;
4733
4734 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004735 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004736 return TemplateArgumentLoc();
4737
Richard Smithc87b9382013-07-04 01:01:24 +00004738 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004739 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004740 TemplateLoc,
4741 RAngleLoc,
4742 TypeParm,
4743 Converted);
4744 if (DI)
4745 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4746
4747 return TemplateArgumentLoc();
4748 }
4749
4750 if (NonTypeTemplateParmDecl *NonTypeParm
4751 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004752 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004753 return TemplateArgumentLoc();
4754
Richard Smithc87b9382013-07-04 01:01:24 +00004755 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004756 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004757 TemplateLoc,
4758 RAngleLoc,
4759 NonTypeParm,
4760 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004761 if (Arg.isInvalid())
4762 return TemplateArgumentLoc();
4763
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004764 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004765 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4766 }
4767
4768 TemplateTemplateParmDecl *TempTempParm
4769 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004770 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004771 return TemplateArgumentLoc();
4772
Richard Smithc87b9382013-07-04 01:01:24 +00004773 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004774 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004775 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004776 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004777 RAngleLoc,
4778 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004779 Converted,
4780 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004781 if (TName.isNull())
4782 return TemplateArgumentLoc();
4783
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004784 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004785 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004786 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4787}
4788
Richard Smith11255ec2017-01-18 19:19:22 +00004789/// Convert a template-argument that we parsed as a type into a template, if
4790/// possible. C++ permits injected-class-names to perform dual service as
4791/// template template arguments and as template type arguments.
4792static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4793 // Extract and step over any surrounding nested-name-specifier.
4794 NestedNameSpecifierLoc QualLoc;
4795 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4796 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4797 return TemplateArgumentLoc();
4798
4799 QualLoc = ETLoc.getQualifierLoc();
4800 TLoc = ETLoc.getNamedTypeLoc();
4801 }
4802
4803 // If this type was written as an injected-class-name, it can be used as a
4804 // template template argument.
4805 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4806 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4807 QualLoc, InjLoc.getNameLoc());
4808
4809 // If this type was written as an injected-class-name, it may have been
4810 // converted to a RecordType during instantiation. If the RecordType is
4811 // *not* wrapped in a TemplateSpecializationType and denotes a class
4812 // template specialization, it must have come from an injected-class-name.
4813 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4814 if (auto *CTSD =
4815 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4816 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4817 QualLoc, RecLoc.getNameLoc());
4818
4819 return TemplateArgumentLoc();
4820}
4821
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004822/// Check that the given template argument corresponds to the given
Douglas Gregorda0fb532009-11-11 19:31:23 +00004823/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004824///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004825/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004826/// checked.
4827///
Richard Trieu15b66532015-01-24 02:48:32 +00004828/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004829///
4830/// \param Template The template in which the template argument resides.
4831///
4832/// \param TemplateLoc The location of the template name for the template
4833/// whose argument list we're matching.
4834///
4835/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4836/// the template argument list.
4837///
4838/// \param ArgumentPackIndex The index into the argument pack where this
4839/// argument will be placed. Only valid if the parameter is a parameter pack.
4840///
4841/// \param Converted The checked, converted argument will be added to the
4842/// end of this small vector.
4843///
4844/// \param CTAK Describes how we arrived at this particular template argument:
4845/// explicitly written, deduced, etc.
4846///
4847/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004848bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004849 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004850 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004851 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004852 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004853 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004854 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004855 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004856 // Check template type parameters.
4857 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004858 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004859
Douglas Gregoreebed722009-11-11 19:41:09 +00004860 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004861 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004862 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004863 // with the template arguments we've seen thus far. But if the
4864 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004865 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004866 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4867 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004868
Richard Smith5d331022018-03-08 01:07:33 +00004869 // FIXME: Do we need to substitute into parameters here if they're
4870 // instantiation-dependent but not dependent?
Peter Collingbourne01687632010-12-10 17:08:53 +00004871 if (NTTPType->isDependentType() &&
4872 !isa<TemplateTemplateParmDecl>(Template) &&
4873 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004874 // Do substitution on the type of the non-type template parameter.
4875 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004876 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004877 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004878 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004879 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004880
4881 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004882 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004883 NTTPType = SubstType(NTTPType,
4884 MultiLevelTemplateArgumentList(TemplateArgs),
4885 NTTP->getLocation(),
4886 NTTP->getDeclName());
4887 // If that worked, check the non-type template parameter type
4888 // for validity.
4889 if (!NTTPType.isNull())
4890 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4891 NTTP->getLocation());
4892 if (NTTPType.isNull())
4893 return true;
4894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895
Douglas Gregorda0fb532009-11-11 19:31:23 +00004896 switch (Arg.getArgument().getKind()) {
4897 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004898 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004899
Douglas Gregorda0fb532009-11-11 19:31:23 +00004900 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004901 TemplateArgument Result;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004902 unsigned CurSFINAEErrors = NumSFINAEErrors;
John Wiegley01296292011-04-08 18:41:53 +00004903 ExprResult Res =
4904 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4905 Result, CTAK);
4906 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004907 return true;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004908 // If the current template argument causes an error, give up now.
4909 if (CurSFINAEErrors < NumSFINAEErrors)
4910 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911
Richard Trieu15b66532015-01-24 02:48:32 +00004912 // If the resulting expression is new, then use it in place of the
4913 // old expression in the template argument.
4914 if (Res.get() != Arg.getArgument().getAsExpr()) {
4915 TemplateArgument TA(Res.get());
4916 Arg = TemplateArgumentLoc(TA, Res.get());
4917 }
4918
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004919 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004920 break;
4921 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004922
Douglas Gregorda0fb532009-11-11 19:31:23 +00004923 case TemplateArgument::Declaration:
4924 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004925 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004926 // We've already checked this template argument, so just copy
4927 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004928 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004929 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004930
Douglas Gregorda0fb532009-11-11 19:31:23 +00004931 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004932 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004933 // We were given a template template argument. It may not be ill-formed;
4934 // see below.
4935 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004936 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4937 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004938 // We have a template argument such as \c T::template X, which we
4939 // parsed as a template template argument. However, since we now
4940 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004941 // template name into an expression.
4942
4943 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4944 Arg.getTemplateNameLoc());
4945
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004946 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004947 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004948 // FIXME: the template-template arg was a DependentTemplateName,
4949 // so it was provided with a template keyword. However, its source
4950 // location is not stored in the template argument structure.
4951 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004952 ExprResult E = DependentScopeDeclRefExpr::Create(
4953 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4954 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004955
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004956 // If we parsed the template argument as a pack expansion, create a
4957 // pack expansion expression.
4958 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004959 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004960 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004961 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004962 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004963
Douglas Gregorda0fb532009-11-11 19:31:23 +00004964 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004965 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004966 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004967 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004968
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004969 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004970 break;
4971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004972
Douglas Gregorda0fb532009-11-11 19:31:23 +00004973 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004974 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004975 // therefore cannot be a non-type template argument.
4976 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4977 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004978
Douglas Gregorda0fb532009-11-11 19:31:23 +00004979 Diag(Param->getLocation(), diag::note_template_param_here);
4980 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004981
Douglas Gregorda0fb532009-11-11 19:31:23 +00004982 case TemplateArgument::Type: {
4983 // We have a non-type template parameter but the template
4984 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004985
Douglas Gregorda0fb532009-11-11 19:31:23 +00004986 // C++ [temp.arg]p2:
4987 // In a template-argument, an ambiguity between a type-id and
4988 // an expression is resolved to a type-id, regardless of the
4989 // form of the corresponding template-parameter.
4990 //
4991 // We warn specifically about this case, since it can be rather
4992 // confusing for users.
4993 QualType T = Arg.getArgument().getAsType();
4994 SourceRange SR = Arg.getSourceRange();
4995 if (T->isFunctionType())
4996 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4997 else
4998 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4999 Diag(Param->getLocation(), diag::note_template_param_here);
5000 return true;
5001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005002
Douglas Gregorda0fb532009-11-11 19:31:23 +00005003 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005004 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00005005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005006
Douglas Gregorda0fb532009-11-11 19:31:23 +00005007 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005008 }
5009
5010
Douglas Gregorda0fb532009-11-11 19:31:23 +00005011 // Check template template parameters.
5012 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005013
Richard Smith5d331022018-03-08 01:07:33 +00005014 TemplateParameterList *Params = TempParm->getTemplateParameters();
5015 if (TempParm->isExpandedParameterPack())
5016 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5017
Douglas Gregorda0fb532009-11-11 19:31:23 +00005018 // Substitute into the template parameter list of the template
5019 // template parameter, since previously-supplied template arguments
5020 // may appear within the template template parameter.
Richard Smith5d331022018-03-08 01:07:33 +00005021 //
5022 // FIXME: Skip this if the parameters aren't instantiation-dependent.
Douglas Gregorda0fb532009-11-11 19:31:23 +00005023 {
5024 // Set up a template instantiation context.
5025 LocalInstantiationScope Scope(*this);
5026 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00005027 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00005028 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00005029 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005030 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005031
David Majnemer8b622692016-07-03 21:17:51 +00005032 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Richard Smith5d331022018-03-08 01:07:33 +00005033 Params = SubstTemplateParams(Params, CurContext,
5034 MultiLevelTemplateArgumentList(TemplateArgs));
5035 if (!Params)
Douglas Gregorda0fb532009-11-11 19:31:23 +00005036 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00005037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005038
Richard Smith11255ec2017-01-18 19:19:22 +00005039 // C++1z [temp.local]p1: (DR1004)
5040 // When [the injected-class-name] is used [...] as a template-argument for
5041 // a template template-parameter [...] it refers to the class template
5042 // itself.
5043 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5044 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5045 Arg.getTypeSourceInfo()->getTypeLoc());
5046 if (!ConvertedArg.getArgument().isNull())
5047 Arg = ConvertedArg;
5048 }
5049
Douglas Gregorda0fb532009-11-11 19:31:23 +00005050 switch (Arg.getArgument().getKind()) {
5051 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00005052 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005053
Douglas Gregorda0fb532009-11-11 19:31:23 +00005054 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005055 case TemplateArgument::TemplateExpansion:
Richard Smith5d331022018-03-08 01:07:33 +00005056 if (CheckTemplateTemplateArgument(Params, Arg))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005057 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005058
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005059 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00005060 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005061
Douglas Gregorda0fb532009-11-11 19:31:23 +00005062 case TemplateArgument::Expression:
5063 case TemplateArgument::Type:
5064 // We have a template template parameter but the template
5065 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00005066 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005067 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00005068 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005069
Douglas Gregorda0fb532009-11-11 19:31:23 +00005070 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00005071 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00005072 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00005073 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00005074 case TemplateArgument::NullPtr:
5075 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076
Douglas Gregorda0fb532009-11-11 19:31:23 +00005077 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005078 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00005079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005080
Douglas Gregorda0fb532009-11-11 19:31:23 +00005081 return false;
5082}
5083
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005084/// Check whether the template parameter is a pack expansion, and if so,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005085/// determine the number of parameters produced by that expansion. For instance:
5086///
5087/// \code
5088/// template<typename ...Ts> struct A {
5089/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
5090/// };
5091/// \endcode
5092///
5093/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
5094/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00005095static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005096 if (NonTypeTemplateParmDecl *NTTP
5097 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5098 if (NTTP->isExpandedParameterPack())
5099 return NTTP->getNumExpansionTypes();
5100 }
5101
5102 if (TemplateTemplateParmDecl *TTP
5103 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
5104 if (TTP->isExpandedParameterPack())
5105 return TTP->getNumExpansionTemplateParameters();
5106 }
5107
David Blaikie7a30dc52013-02-21 01:47:18 +00005108 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00005109}
5110
Richard Smith35c1df52015-06-17 20:16:32 +00005111/// Diagnose a missing template argument.
5112template<typename TemplateParmDecl>
5113static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5114 TemplateDecl *TD,
5115 const TemplateParmDecl *D,
5116 TemplateArgumentListInfo &Args) {
5117 // Dig out the most recent declaration of the template parameter; there may be
5118 // declarations of the template that are more recent than TD.
5119 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5120 ->getTemplateParameters()
5121 ->getParam(D->getIndex()));
5122
5123 // If there's a default argument that's not visible, diagnose that we're
5124 // missing a module import.
5125 llvm::SmallVector<Module*, 8> Modules;
5126 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5127 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5128 D->getDefaultArgumentLoc(), Modules,
5129 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00005130 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00005131 return true;
5132 }
5133
5134 // FIXME: If there's a more recent default argument that *is* visible,
5135 // diagnose that it was declared too late.
5136
Richard Smith4a8f3512018-07-19 19:00:37 +00005137 TemplateParameterList *Params = TD->getTemplateParameters();
5138
5139 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5140 << /*not enough args*/0
5141 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5142 << TD;
5143 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5144 << Params->getSourceRange();
5145 return true;
Richard Smith35c1df52015-06-17 20:16:32 +00005146}
5147
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005148/// Check that the given template argument list is well-formed
Douglas Gregord32e0282009-02-09 23:23:08 +00005149/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00005150bool Sema::CheckTemplateArgumentList(
5151 TemplateDecl *Template, SourceLocation TemplateLoc,
5152 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5153 SmallVectorImpl<TemplateArgument> &Converted,
5154 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00005155 // Make a copy of the template arguments for processing. Only make the
5156 // changes at the end when successful in matching the arguments to the
5157 // template.
5158 TemplateArgumentListInfo NewArgs = TemplateArgs;
5159
Erich Keaneaf0795b2017-10-24 01:39:56 +00005160 // Make sure we get the template parameter list from the most
5161 // recentdeclaration, since that is the only one that has is guaranteed to
5162 // have all the default template argument information.
5163 TemplateParameterList *Params =
5164 cast<TemplateDecl>(Template->getMostRecentDecl())
5165 ->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00005166
Richard Trieu15b66532015-01-24 02:48:32 +00005167 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00005168
Mike Stump11289f42009-09-09 15:08:12 +00005169 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00005170 // [...] The type and form of each template-argument specified in
5171 // a template-id shall match the type and form specified for the
5172 // corresponding parameter declared by the template in its
5173 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00005174 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005175 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00005176 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00005177 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00005178 for (TemplateParameterList::iterator Param = Params->begin(),
5179 ParamEnd = Params->end();
5180 Param != ParamEnd; /* increment in loop */) {
5181 // If we have an expanded parameter pack, make sure we don't have too
5182 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00005183 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005184 if (*Expansions == ArgumentPack.size()) {
5185 // We're done with this parameter pack. Pack up its arguments and add
5186 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00005187 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00005188 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005189 ArgumentPack.clear();
5190
Richard Smith1fde8ec2012-09-07 02:06:42 +00005191 // This argument is assigned to the next parameter.
5192 ++Param;
5193 continue;
5194 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5195 // Not enough arguments for this parameter pack.
5196 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
Richard Smith4a8f3512018-07-19 19:00:37 +00005197 << /*not enough args*/0
Richard Smith0c062b42017-01-14 02:19:59 +00005198 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00005199 << Template;
5200 Diag(Template->getLocation(), diag::note_template_decl_here)
5201 << Params->getSourceRange();
5202 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005203 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005204 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005205
Richard Smith1fde8ec2012-09-07 02:06:42 +00005206 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00005207 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00005208 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005209 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005210 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00005211 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005212
Richard Smith96d71c32014-11-12 23:38:38 +00005213 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00005214 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00005215 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5216 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00005217 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00005218 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00005219 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00005220 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00005221 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00005222 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00005223 Diag((*Param)->getLocation(), diag::note_template_param_here);
5224 return true;
5225 }
5226
Richard Smith1fde8ec2012-09-07 02:06:42 +00005227 // We're now done with this argument.
5228 ++ArgIdx;
5229
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005230 if ((*Param)->isTemplateParameterPack()) {
5231 // The template parameter was a template parameter pack, so take the
5232 // deduced argument and place it on the argument pack. Note that we
5233 // stay on the same template parameter so that we can deduce more
5234 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00005235 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005236 } else {
5237 // Move to the next template parameter.
5238 ++Param;
5239 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005240
Richard Smith96d71c32014-11-12 23:38:38 +00005241 // If we just saw a pack expansion into a non-pack, then directly convert
5242 // the remaining arguments, because we don't know what parameters they'll
5243 // match up with.
5244 if (PackExpansionIntoNonPack) {
5245 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005246 // If we were part way through filling in an expanded parameter pack,
5247 // fall back to just producing individual arguments.
5248 Converted.insert(Converted.end(),
5249 ArgumentPack.begin(), ArgumentPack.end());
5250 ArgumentPack.clear();
5251 }
5252
5253 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00005254 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00005255 ++ArgIdx;
5256 }
5257
Richard Smith1fde8ec2012-09-07 02:06:42 +00005258 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00005259 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005260
Douglas Gregor84d49a22009-11-11 21:54:23 +00005261 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005263
Douglas Gregor2f157c92011-06-03 02:59:40 +00005264 // If we're checking a partial template argument list, we're done.
5265 if (PartialTemplateArgs) {
5266 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00005267 Converted.push_back(
5268 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5269
Richard Smith1fde8ec2012-09-07 02:06:42 +00005270 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00005271 }
5272
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005273 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005274 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00005275 if ((*Param)->isTemplateParameterPack()) {
5276 assert(!getExpandedPackSize(*Param) &&
5277 "Should have dealt with this already");
5278
5279 // A non-expanded parameter pack before the end of the parameter list
5280 // only occurs for an ill-formed template parameter list, unless we've
5281 // got a partial argument list for a function template, so just bail out.
5282 if (Param + 1 != ParamEnd)
5283 return true;
5284
Benjamin Kramercce63472015-08-05 09:40:22 +00005285 Converted.push_back(
5286 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005287 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00005288
5289 ++Param;
5290 continue;
5291 }
5292
Douglas Gregor8e072612012-02-03 07:34:46 +00005293 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00005294 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005295
Douglas Gregor84d49a22009-11-11 21:54:23 +00005296 // Retrieve the default template argument from the template
5297 // parameter. For each kind of template parameter, we substitute the
5298 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005299 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00005300 // the default argument.
5301 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005302 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005303 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5304 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005305
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005306 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005307 Template,
5308 TemplateLoc,
5309 RAngleLoc,
5310 TTP,
5311 Converted);
5312 if (!ArgType)
5313 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005314
Douglas Gregor84d49a22009-11-11 21:54:23 +00005315 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5316 ArgType);
5317 } else if (NonTypeTemplateParmDecl *NTTP
5318 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005319 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005320 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5321 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005322
John McCalldadc5752010-08-24 06:29:42 +00005323 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005324 TemplateLoc,
5325 RAngleLoc,
5326 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005327 Converted);
5328 if (E.isInvalid())
5329 return true;
5330
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005331 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00005332 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5333 } else {
5334 TemplateTemplateParmDecl *TempParm
5335 = cast<TemplateTemplateParmDecl>(*Param);
5336
Richard Smith95d83952015-06-10 20:36:34 +00005337 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00005338 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5339 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005340
Douglas Gregordf846d12011-03-02 18:46:51 +00005341 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00005342 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005343 TemplateLoc,
5344 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005345 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00005346 Converted,
5347 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005348 if (Name.isNull())
5349 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005350
Douglas Gregor9d802122011-03-02 17:09:35 +00005351 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5352 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00005353 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005354
Douglas Gregor84d49a22009-11-11 21:54:23 +00005355 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00005356 // the default template argument. We're not actually instantiating a
5357 // template here, we just create this object to put a note into the
5358 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00005359 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5360 SourceRange(TemplateLoc, RAngleLoc));
5361 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005362 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005363
Douglas Gregor84d49a22009-11-11 21:54:23 +00005364 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00005365 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005366 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005367 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005368
Richard Trieu15b66532015-01-24 02:48:32 +00005369 // Core issue 150 (assumed resolution): if this is a template template
5370 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00005371 // template definition.
5372 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00005373 NewArgs.addArgument(Arg);
5374
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005375 // Move to the next template parameter and argument.
5376 ++Param;
5377 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00005378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005379
Richard Smith07f79912014-06-06 16:00:50 +00005380 // If we're performing a partial argument substitution, allow any trailing
5381 // pack expansions; they might be empty. This can happen even if
5382 // PartialTemplateArgs is false (the list of arguments is complete but
5383 // still dependent).
5384 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5385 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00005386 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5387 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00005388 }
5389
Douglas Gregor8e072612012-02-03 07:34:46 +00005390 // If we have any leftover arguments, then there were too many arguments.
5391 // Complain and fail.
Richard Smith4a8f3512018-07-19 19:00:37 +00005392 if (ArgIdx < NumArgs) {
5393 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5394 << /*too many args*/1
5395 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5396 << Template
5397 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5398 Diag(Template->getLocation(), diag::note_template_decl_here)
5399 << Params->getSourceRange();
5400 return true;
5401 }
Richard Trieu15b66532015-01-24 02:48:32 +00005402
5403 // No problems found with the new argument list, propagate changes back
5404 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00005405 if (UpdateArgsWithConversions)
5406 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005407
Richard Smith1fde8ec2012-09-07 02:06:42 +00005408 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00005409}
5410
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005411namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005412 class UnnamedLocalNoLinkageFinder
5413 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005414 {
5415 Sema &S;
5416 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005417
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005418 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005419
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005420 public:
5421 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5422
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005423 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00005424 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005426
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005427#define TYPE(Class, Parent) \
5428 bool Visit##Class##Type(const Class##Type *);
5429#define ABSTRACT_TYPE(Class, Parent) \
5430 bool Visit##Class##Type(const Class##Type *) { return false; }
5431#define NON_CANONICAL_TYPE(Class, Parent) \
5432 bool Visit##Class##Type(const Class##Type *) { return false; }
5433#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005434
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005435 bool VisitTagDecl(const TagDecl *Tag);
5436 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5437 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005438} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005439
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005440bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005441 return false;
5442}
5443
5444bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5445 return Visit(T->getElementType());
5446}
5447
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005448bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005449 return Visit(T->getPointeeType());
5450}
5451
5452bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005453 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005454 return Visit(T->getPointeeType());
5455}
5456
5457bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005458 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005459 return Visit(T->getPointeeType());
5460}
5461
5462bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005463 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005464 return Visit(T->getPointeeType());
5465}
5466
5467bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005468 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005469 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5470}
5471
5472bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005473 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005474 return Visit(T->getElementType());
5475}
5476
5477bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005478 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005479 return Visit(T->getElementType());
5480}
5481
5482bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005483 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005484 return Visit(T->getElementType());
5485}
5486
5487bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005488 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005489 return Visit(T->getElementType());
5490}
5491
5492bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005493 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005494 return Visit(T->getElementType());
5495}
5496
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005497bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5498 const DependentAddressSpaceType *T) {
5499 return Visit(T->getPointeeType());
5500}
5501
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005502bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5503 return Visit(T->getElementType());
5504}
5505
Erich Keanef702b022018-07-13 19:46:04 +00005506bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5507 const DependentVectorType *T) {
5508 return Visit(T->getElementType());
5509}
5510
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005511bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5512 return Visit(T->getElementType());
5513}
5514
5515bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5516 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005517 for (const auto &A : T->param_types()) {
5518 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005519 return true;
5520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005521
Alp Toker314cc812014-01-25 16:55:45 +00005522 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005523}
5524
5525bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5526 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00005527 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005528}
5529
5530bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5531 const UnresolvedUsingType*) {
5532 return false;
5533}
5534
5535bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5536 return false;
5537}
5538
5539bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5540 return Visit(T->getUnderlyingType());
5541}
5542
5543bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5544 return false;
5545}
5546
Alexis Hunte852b102011-05-24 22:41:36 +00005547bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5548 const UnaryTransformType*) {
5549 return false;
5550}
5551
Richard Smith30482bc2011-02-20 03:19:35 +00005552bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5553 return Visit(T->getDeducedType());
5554}
5555
Richard Smith600b5262017-01-26 20:40:47 +00005556bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5557 const DeducedTemplateSpecializationType *T) {
5558 return Visit(T->getDeducedType());
5559}
5560
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005561bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5562 return VisitTagDecl(T->getDecl());
5563}
5564
5565bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5566 return VisitTagDecl(T->getDecl());
5567}
5568
5569bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5570 const TemplateTypeParmType*) {
5571 return false;
5572}
5573
Douglas Gregorada4b792011-01-14 02:55:32 +00005574bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5575 const SubstTemplateTypeParmPackType *) {
5576 return false;
5577}
5578
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005579bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5580 const TemplateSpecializationType*) {
5581 return false;
5582}
5583
5584bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5585 const InjectedClassNameType* T) {
5586 return VisitTagDecl(T->getDecl());
5587}
5588
5589bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5590 const DependentNameType* T) {
5591 return VisitNestedNameSpecifier(T->getQualifier());
5592}
5593
5594bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5595 const DependentTemplateSpecializationType* T) {
5596 return VisitNestedNameSpecifier(T->getQualifier());
5597}
5598
Douglas Gregord2fa7662010-12-20 02:24:11 +00005599bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5600 const PackExpansionType* T) {
5601 return Visit(T->getPattern());
5602}
5603
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005604bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5605 return false;
5606}
5607
5608bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5609 const ObjCInterfaceType *) {
5610 return false;
5611}
5612
5613bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5614 const ObjCObjectPointerType *) {
5615 return false;
5616}
5617
Eli Friedman0dfb8892011-10-06 23:00:33 +00005618bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5619 return Visit(T->getValueType());
5620}
5621
Xiuli Pan9c14e282016-01-09 12:53:17 +00005622bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5623 return false;
5624}
5625
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005626bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5627 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005628 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005629 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005630 diag::warn_cxx98_compat_template_arg_local_type :
5631 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005632 << S.Context.getTypeDeclType(Tag) << SR;
5633 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005634 }
5635
John McCall5ea95772013-03-09 00:54:27 +00005636 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005637 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005638 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005639 diag::warn_cxx98_compat_template_arg_unnamed_type :
5640 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005641 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5642 return true;
5643 }
5644
5645 return false;
5646}
5647
5648bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5649 NestedNameSpecifier *NNS) {
5650 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5651 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005652
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005653 switch (NNS->getKind()) {
5654 case NestedNameSpecifier::Identifier:
5655 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005656 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005657 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005658 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005659 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005660
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005661 case NestedNameSpecifier::TypeSpec:
5662 case NestedNameSpecifier::TypeSpecWithTemplate:
5663 return Visit(QualType(NNS->getAsType(), 0));
5664 }
David Blaikie8a40f702012-01-17 06:56:22 +00005665 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005666}
5667
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005668/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00005669/// template type parameter.
5670///
5671/// This routine implements the semantics of C++ [temp.arg.type]. It
5672/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005673bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005674 TypeSourceInfo *ArgInfo) {
5675 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005676 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005677 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005678
5679 if (Arg->isVariablyModifiedType()) {
5680 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005681 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005682 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005683 }
5684
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005685 // C++03 [temp.arg.type]p2:
5686 // A local type, a type with no linkage, an unnamed type or a type
5687 // compounded from any of these types shall not be used as a
5688 // template-argument for a template type-parameter.
5689 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005690 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005691 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005692 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005693 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5694 (void)Finder.Visit(Context.getCanonicalType(Arg));
5695 }
5696
Douglas Gregord32e0282009-02-09 23:23:08 +00005697 return false;
5698}
5699
Douglas Gregor20fdef32012-04-10 17:08:25 +00005700enum NullPointerValueKind {
5701 NPV_NotNullPointer,
5702 NPV_NullPointer,
5703 NPV_Error
5704};
5705
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005706/// Determine whether the given template argument is a null pointer
Douglas Gregor20fdef32012-04-10 17:08:25 +00005707/// value of the appropriate type.
5708static NullPointerValueKind
5709isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
Reid Klecknercd016d82017-07-07 22:04:29 +00005710 QualType ParamType, Expr *Arg,
5711 Decl *Entity = nullptr) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005712 if (Arg->isValueDependent() || Arg->isTypeDependent())
5713 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005714
Reid Klecknercd016d82017-07-07 22:04:29 +00005715 // dllimport'd entities aren't constant but are available inside of template
5716 // arguments.
5717 if (Entity && Entity->hasAttr<DLLImportAttr>())
5718 return NPV_NotNullPointer;
5719
Richard Smithdb0ac552015-12-18 22:40:25 +00005720 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005721 llvm_unreachable(
5722 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005723
David Majnemer5c734ad2014-08-14 00:49:23 +00005724 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005725 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005726
Douglas Gregor20fdef32012-04-10 17:08:25 +00005727 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005728 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5729 if (ArgRV.isInvalid())
5730 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005731 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005732
Douglas Gregor20fdef32012-04-10 17:08:25 +00005733 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005734 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005735 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005736 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005737 EvalResult.HasSideEffects) {
5738 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005739
Douglas Gregor350880c2012-04-10 19:03:30 +00005740 // If our only note is the usual "invalid subexpression" note, just point
5741 // the caret at its location rather than producing an essentially
5742 // redundant note.
5743 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5744 diag::note_invalid_subexpr_in_const_expr) {
5745 DiagLoc = Notes[0].first;
5746 Notes.clear();
5747 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005748
Douglas Gregor350880c2012-04-10 19:03:30 +00005749 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5750 << Arg->getType() << Arg->getSourceRange();
5751 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5752 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005753
Douglas Gregor350880c2012-04-10 19:03:30 +00005754 S.Diag(Param->getLocation(), diag::note_template_param_here);
5755 return NPV_Error;
5756 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005757
Douglas Gregor20fdef32012-04-10 17:08:25 +00005758 // C++11 [temp.arg.nontype]p1:
5759 // - an address constant expression of type std::nullptr_t
5760 if (Arg->getType()->isNullPtrType())
5761 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005762
Douglas Gregor20fdef32012-04-10 17:08:25 +00005763 // - a constant expression that evaluates to a null pointer value (4.10); or
5764 // - a constant expression that evaluates to a null member pointer value
5765 // (4.11); or
5766 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5767 (EvalResult.Val.isMemberPointer() &&
5768 !EvalResult.Val.getMemberPointerDecl())) {
5769 // If our expression has an appropriate type, we've succeeded.
5770 bool ObjCLifetimeConversion;
5771 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5772 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5773 ObjCLifetimeConversion))
5774 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005775
Douglas Gregor20fdef32012-04-10 17:08:25 +00005776 // The types didn't match, but we know we got a null pointer; complain,
5777 // then recover as if the types were correct.
5778 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5779 << Arg->getType() << ParamType << Arg->getSourceRange();
5780 S.Diag(Param->getLocation(), diag::note_template_param_here);
5781 return NPV_NullPointer;
5782 }
5783
5784 // If we don't have a null pointer value, but we do have a NULL pointer
5785 // constant, suggest a cast to the appropriate type.
5786 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5787 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5788 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005789 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005790 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
Alp Tokerb6cc5922014-05-03 03:45:55 +00005791 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005792 S.Diag(Param->getLocation(), diag::note_template_param_here);
5793 return NPV_NullPointer;
5794 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005795
Douglas Gregor20fdef32012-04-10 17:08:25 +00005796 // FIXME: If we ever want to support general, address-constant expressions
5797 // as non-type template arguments, we should return the ExprResult here to
5798 // be interpreted by the caller.
5799 return NPV_NotNullPointer;
5800}
5801
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005802/// Checks whether the given template argument is compatible with its
David Majnemer61c39a12013-08-23 05:39:39 +00005803/// template parameter.
5804static bool CheckTemplateArgumentIsCompatibleWithParameter(
5805 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5806 Expr *Arg, QualType ArgType) {
5807 bool ObjCLifetimeConversion;
5808 if (ParamType->isPointerType() &&
5809 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5810 S.IsQualificationConversion(ArgType, ParamType, false,
5811 ObjCLifetimeConversion)) {
5812 // For pointer-to-object types, qualification conversions are
5813 // permitted.
5814 } else {
5815 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5816 if (!ParamRef->getPointeeType()->isFunctionType()) {
5817 // C++ [temp.arg.nontype]p5b3:
5818 // For a non-type template-parameter of type reference to
5819 // object, no conversions apply. The type referred to by the
5820 // reference may be more cv-qualified than the (otherwise
5821 // identical) type of the template- argument. The
5822 // template-parameter is bound directly to the
5823 // template-argument, which shall be an lvalue.
5824
5825 // FIXME: Other qualifiers?
5826 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5827 unsigned ArgQuals = ArgType.getCVRQualifiers();
5828
5829 if ((ParamQuals | ArgQuals) != ParamQuals) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005830 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005831 diag::err_template_arg_ref_bind_ignores_quals)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005832 << ParamType << Arg->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005833 S.Diag(Param->getLocation(), diag::note_template_param_here);
5834 return true;
5835 }
5836 }
5837 }
5838
5839 // At this point, the template argument refers to an object or
5840 // function with external linkage. We now need to check whether the
5841 // argument and parameter types are compatible.
5842 if (!S.Context.hasSameUnqualifiedType(ArgType,
5843 ParamType.getNonReferenceType())) {
5844 // We can't perform this conversion or binding.
5845 if (ParamType->isReferenceType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005846 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
5847 << ParamType << ArgIn->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005848 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005849 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
5850 << ArgIn->getType() << ParamType << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005851 S.Diag(Param->getLocation(), diag::note_template_param_here);
5852 return true;
5853 }
5854 }
5855
5856 return false;
5857}
5858
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005859/// Checks whether the given template argument is the address
Douglas Gregorccb07762009-02-11 19:52:55 +00005860/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005861static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005862CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5863 NonTypeTemplateParmDecl *Param,
5864 QualType ParamType,
5865 Expr *ArgIn,
5866 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005867 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005868 Expr *Arg = ArgIn;
5869 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005870
Douglas Gregorb242683d2010-04-01 18:32:35 +00005871 bool AddressTaken = false;
5872 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005873 if (S.getLangOpts().MicrosoftExt) {
5874 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5875 // dereference and address-of operators.
5876 Arg = Arg->IgnoreParenCasts();
5877
5878 bool ExtWarnMSTemplateArg = false;
5879 UnaryOperatorKind FirstOpKind;
5880 SourceLocation FirstOpLoc;
5881 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5882 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5883 if (UnOpKind == UO_Deref)
5884 ExtWarnMSTemplateArg = true;
5885 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5886 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5887 if (!AddrOpLoc.isValid()) {
5888 FirstOpKind = UnOpKind;
5889 FirstOpLoc = UnOp->getOperatorLoc();
5890 }
5891 } else
5892 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005893 }
David Majnemer61c39a12013-08-23 05:39:39 +00005894 if (FirstOpLoc.isValid()) {
5895 if (ExtWarnMSTemplateArg)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005896 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
5897 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005898
David Majnemer61c39a12013-08-23 05:39:39 +00005899 if (FirstOpKind == UO_AddrOf)
5900 AddressTaken = true;
5901 else if (Arg->getType()->isPointerType()) {
5902 // We cannot let pointers get dereferenced here, that is obviously not a
5903 // constant expression.
5904 assert(FirstOpKind == UO_Deref);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005905 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5906 << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005907 }
5908 }
5909 } else {
5910 // See through any implicit casts we added to fix the type.
5911 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005912
David Majnemer61c39a12013-08-23 05:39:39 +00005913 // C++ [temp.arg.nontype]p1:
5914 //
5915 // A template-argument for a non-type, non-template
5916 // template-parameter shall be one of: [...]
5917 //
5918 // -- the address of an object or function with external
5919 // linkage, including function templates and function
5920 // template-ids but excluding non-static class members,
5921 // expressed as & id-expression where the & is optional if
5922 // the name refers to a function or array, or if the
5923 // corresponding template-parameter is a reference; or
5924
5925 // In C++98/03 mode, give an extension warning on any extra parentheses.
5926 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5927 bool ExtraParens = false;
5928 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5929 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005930 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005931 S.getLangOpts().CPlusPlus11
5932 ? diag::warn_cxx98_compat_template_arg_extra_parens
5933 : diag::ext_template_arg_extra_parens)
5934 << Arg->getSourceRange();
5935 ExtraParens = true;
5936 }
5937
5938 Arg = Parens->getSubExpr();
5939 }
5940
5941 while (SubstNonTypeTemplateParmExpr *subst =
5942 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5943 Arg = subst->getReplacement()->IgnoreImpCasts();
5944
5945 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5946 if (UnOp->getOpcode() == UO_AddrOf) {
5947 Arg = UnOp->getSubExpr();
5948 AddressTaken = true;
5949 AddrOpLoc = UnOp->getOperatorLoc();
5950 }
5951 }
5952
5953 while (SubstNonTypeTemplateParmExpr *subst =
5954 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5955 Arg = subst->getReplacement()->IgnoreImpCasts();
5956 }
John McCall7c454bb2011-07-15 05:09:51 +00005957
David Majnemer07910d62014-06-26 07:48:46 +00005958 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5959 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5960
5961 // If our parameter has pointer type, check for a null template value.
5962 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
Reid Klecknercd016d82017-07-07 22:04:29 +00005963 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5964 Entity)) {
David Majnemer07910d62014-06-26 07:48:46 +00005965 case NPV_NullPointer:
5966 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005967 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5968 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005969 return false;
5970
5971 case NPV_Error:
5972 return true;
5973
5974 case NPV_NotNullPointer:
5975 break;
5976 }
5977 }
5978
Chandler Carruth724a8a12010-01-31 10:01:20 +00005979 // Stop checking the precise nature of the argument if it is value dependent,
5980 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005981 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005982 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005983 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005984 }
David Majnemer61c39a12013-08-23 05:39:39 +00005985
5986 if (isa<CXXUuidofExpr>(Arg)) {
5987 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5988 ArgIn, Arg, ArgType))
5989 return true;
5990
5991 Converted = TemplateArgument(ArgIn);
5992 return false;
5993 }
5994
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005995 if (!DRE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005996 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5997 << Arg->getSourceRange();
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005998 S.Diag(Param->getLocation(), diag::note_template_param_here);
5999 return true;
6000 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00006001
Douglas Gregorccb07762009-02-11 19:52:55 +00006002 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00006003 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006004 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6005 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006006 S.Diag(Param->getLocation(), diag::note_template_param_here);
6007 return true;
6008 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006009
6010 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00006011 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006012 if (!Method->isStatic()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006013 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6014 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006015 S.Diag(Param->getLocation(), diag::note_template_param_here);
6016 return true;
6017 }
Richard Smith9380e0e2012-04-04 21:11:30 +00006018 }
Mike Stump11289f42009-09-09 15:08:12 +00006019
Richard Smith9380e0e2012-04-04 21:11:30 +00006020 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6021 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00006022
Richard Smith9380e0e2012-04-04 21:11:30 +00006023 // A non-type template argument must refer to an object or function.
6024 if (!Func && !Var) {
6025 // We found something, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006026 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6027 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006028 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6029 return true;
6030 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006031
Richard Smith9380e0e2012-04-04 21:11:30 +00006032 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00006033 if (Entity->getFormalLinkage() == InternalLinkage) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006034 S.Diag(Arg->getBeginLoc(),
6035 S.getLangOpts().CPlusPlus11
6036 ? diag::warn_cxx98_compat_template_arg_object_internal
6037 : diag::ext_template_arg_object_internal)
6038 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006039 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6040 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00006041 } else if (!Entity->hasLinkage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006042 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6043 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006044 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6045 << !Func;
6046 return true;
6047 }
6048
6049 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006050 // If the template parameter has pointer type, the function decays.
6051 if (ParamType->isPointerType() && !AddressTaken)
6052 ArgType = S.Context.getPointerType(Func->getType());
6053 else if (AddressTaken && ParamType->isReferenceType()) {
6054 // If we originally had an address-of operator, but the
6055 // parameter has reference type, complain and (if things look
6056 // like they will work) drop the address-of operator.
6057 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
6058 ParamType.getNonReferenceType())) {
6059 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6060 << ParamType;
6061 S.Diag(Param->getLocation(), diag::note_template_param_here);
6062 return true;
6063 }
6064
6065 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6066 << ParamType
6067 << FixItHint::CreateRemoval(AddrOpLoc);
6068 S.Diag(Param->getLocation(), diag::note_template_param_here);
6069
6070 ArgType = Func->getType();
6071 }
Richard Smith9380e0e2012-04-04 21:11:30 +00006072 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006073 // A value of reference type is not an object.
6074 if (Var->getType()->isReferenceType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006075 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6076 << Var->getType() << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006077 S.Diag(Param->getLocation(), diag::note_template_param_here);
6078 return true;
6079 }
6080
Richard Smith9380e0e2012-04-04 21:11:30 +00006081 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00006082 if (Var->getTLSKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006083 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6084 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006085 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6086 return true;
6087 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006088
6089 // If the template parameter has pointer type, we must have taken
6090 // the address of this object.
6091 if (ParamType->isReferenceType()) {
6092 if (AddressTaken) {
6093 // If we originally had an address-of operator, but the
6094 // parameter has reference type, complain and (if things look
6095 // like they will work) drop the address-of operator.
6096 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
6097 ParamType.getNonReferenceType())) {
6098 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6099 << ParamType;
6100 S.Diag(Param->getLocation(), diag::note_template_param_here);
6101 return true;
6102 }
6103
6104 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6105 << ParamType
6106 << FixItHint::CreateRemoval(AddrOpLoc);
6107 S.Diag(Param->getLocation(), diag::note_template_param_here);
6108
6109 ArgType = Var->getType();
6110 }
6111 } else if (!AddressTaken && ParamType->isPointerType()) {
6112 if (Var->getType()->isArrayType()) {
6113 // Array-to-pointer decay.
6114 ArgType = S.Context.getArrayDecayedType(Var->getType());
6115 } else {
6116 // If the template parameter has pointer type but the address of
6117 // this object was not taken, complain and (possibly) recover by
6118 // taking the address of the entity.
6119 ArgType = S.Context.getPointerType(Var->getType());
6120 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006121 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6122 << ParamType;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006123 S.Diag(Param->getLocation(), diag::note_template_param_here);
6124 return true;
6125 }
6126
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006127 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6128 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
Douglas Gregorb242683d2010-04-01 18:32:35 +00006129
6130 S.Diag(Param->getLocation(), diag::note_template_param_here);
6131 }
6132 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006133 }
Mike Stump11289f42009-09-09 15:08:12 +00006134
David Majnemer61c39a12013-08-23 05:39:39 +00006135 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6136 Arg, ArgType))
6137 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006138
6139 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00006140 Converted =
6141 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006142 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00006143 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006144}
6145
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006146/// Checks whether the given template argument is a pointer to
Douglas Gregorccb07762009-02-11 19:52:55 +00006147/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00006148static bool CheckTemplateArgumentPointerToMember(Sema &S,
6149 NonTypeTemplateParmDecl *Param,
6150 QualType ParamType,
6151 Expr *&ResultArg,
6152 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006153 bool Invalid = false;
6154
Douglas Gregor20fdef32012-04-10 17:08:25 +00006155 Expr *Arg = ResultArg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006156 bool ObjCLifetimeConversion;
Douglas Gregorccb07762009-02-11 19:52:55 +00006157
6158 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006159 //
Douglas Gregorccb07762009-02-11 19:52:55 +00006160 // A template-argument for a non-type, non-template
6161 // template-parameter shall be one of: [...]
6162 //
6163 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00006164 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00006165
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006166 // In C++98/03 mode, give an extension warning on any extra parentheses.
6167 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6168 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006169 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00006170 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006171 S.Diag(Arg->getBeginLoc(),
6172 S.getLangOpts().CPlusPlus11
6173 ? diag::warn_cxx98_compat_template_arg_extra_parens
6174 : diag::ext_template_arg_extra_parens)
6175 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006176 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00006177 }
6178
6179 Arg = Parens->getSubExpr();
6180 }
6181
John McCall7c454bb2011-07-15 05:09:51 +00006182 while (SubstNonTypeTemplateParmExpr *subst =
6183 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6184 Arg = subst->getReplacement()->IgnoreImpCasts();
6185
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006186 // A pointer-to-member constant written &Class::member.
6187 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00006188 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006189 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6190 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00006191 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006193 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006194 // A constant of pointer-to-member type.
6195 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006196 ValueDecl *VD = DRE->getDecl();
6197 if (VD->getType()->isMemberPointerType()) {
6198 if (isa<NonTypeTemplateParmDecl>(VD)) {
6199 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6200 Converted = TemplateArgument(Arg);
6201 } else {
6202 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6203 Converted = TemplateArgument(VD, ParamType);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006204 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00006205 return Invalid;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006206 }
6207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006208
Craig Topperc3ec1492014-05-26 06:22:03 +00006209 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006210 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006211
Reid Klecknercd016d82017-07-07 22:04:29 +00006212 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6213
6214 // Check for a null pointer value.
6215 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6216 Entity)) {
6217 case NPV_Error:
6218 return true;
6219 case NPV_NullPointer:
6220 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6221 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6222 /*isNullPtr*/true);
6223 return false;
6224 case NPV_NotNullPointer:
6225 break;
6226 }
6227
6228 if (S.IsQualificationConversion(ResultArg->getType(),
6229 ParamType.getNonReferenceType(), false,
6230 ObjCLifetimeConversion)) {
6231 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6232 ResultArg->getValueKind())
6233 .get();
6234 } else if (!S.Context.hasSameUnqualifiedType(
6235 ResultArg->getType(), ParamType.getNonReferenceType())) {
6236 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006237 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
Reid Klecknercd016d82017-07-07 22:04:29 +00006238 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6239 S.Diag(Param->getLocation(), diag::note_template_param_here);
6240 return true;
6241 }
6242
Douglas Gregorccb07762009-02-11 19:52:55 +00006243 if (!DRE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006244 return S.Diag(Arg->getBeginLoc(),
Douglas Gregor20fdef32012-04-10 17:08:25 +00006245 diag::err_template_arg_not_pointer_to_member_form)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006246 << Arg->getSourceRange();
Douglas Gregorccb07762009-02-11 19:52:55 +00006247
David Majnemer3ac84e62013-10-22 21:56:38 +00006248 if (isa<FieldDecl>(DRE->getDecl()) ||
6249 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6250 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006251 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00006252 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00006253 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6254 "Only non-static member pointers can make it here");
6255
6256 // Okay: this is the address of a non-static member, and therefore
6257 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00006258 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00006259 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00006260 } else {
6261 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00006262 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00006263 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006264 return Invalid;
6265 }
6266
6267 // We found something else, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006268 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6269 << Arg->getSourceRange();
Douglas Gregor20fdef32012-04-10 17:08:25 +00006270 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00006271 return true;
6272}
6273
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006274/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006275/// non-type template parameter.
6276///
Douglas Gregor463421d2009-03-03 04:44:36 +00006277/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00006278/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00006279/// returns the converted template argument. \p ParamType is the
6280/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00006281ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00006282 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00006283 TemplateArgument &Converted,
6284 CheckTemplateArgumentKind CTAK) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006285 SourceLocation StartLoc = Arg->getBeginLoc();
Douglas Gregorc40290e2009-03-09 23:48:35 +00006286
Richard Smith5f274382016-09-28 23:55:27 +00006287 // If the parameter type somehow involves auto, deduce the type now.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006288 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
Richard Smith4ae5ec82017-02-22 20:01:55 +00006289 // During template argument deduction, we allow 'decltype(auto)' to
6290 // match an arbitrary dependent argument.
6291 // FIXME: The language rules don't say what happens in this case.
6292 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6293 // expression is merely instantiation-dependent; is this enough?
6294 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6295 auto *AT = dyn_cast<AutoType>(ParamType);
6296 if (AT && AT->isDecltypeAuto()) {
6297 Converted = TemplateArgument(Arg);
6298 return Arg;
6299 }
6300 }
6301
Richard Smith87d263e2016-12-25 08:05:23 +00006302 // When checking a deduced template argument, deduce from its type even if
6303 // the type is dependent, in order to check the types of non-type template
6304 // arguments line up properly in partial ordering.
6305 Optional<unsigned> Depth;
6306 if (CTAK != CTAK_Specified)
6307 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00006308 if (DeduceAutoType(
6309 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00006310 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00006311 Diag(Arg->getExprLoc(),
6312 diag::err_non_type_template_parm_type_deduction_failure)
6313 << Param->getDeclName() << Param->getType() << Arg->getType()
6314 << Arg->getSourceRange();
6315 Diag(Param->getLocation(), diag::note_template_param_here);
6316 return ExprError();
6317 }
6318 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6319 // an error. The error message normally references the parameter
6320 // declaration, but here we'll pass the argument location because that's
6321 // where the parameter type is deduced.
6322 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6323 if (ParamType.isNull()) {
6324 Diag(Param->getLocation(), diag::note_template_param_here);
6325 return ExprError();
6326 }
6327 }
6328
Richard Smithd663fdd2014-12-17 20:42:37 +00006329 // We should have already dropped all cv-qualifiers by now.
6330 assert(!ParamType.hasQualifiers() &&
6331 "non-type template parameter type cannot be qualified");
6332
6333 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00006334 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00006335 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00006336 // FIXME: If either type is dependent, we skip the check. This isn't
6337 // correct, since during deduction we're supposed to have replaced each
6338 // template parameter with some unique (non-dependent) placeholder.
6339 // FIXME: If the argument type contains 'auto', we carry on and fail the
6340 // type check in order to force specific types to be more specialized than
6341 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6342 // work.
6343 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6344 !Arg->getType()->getContainedAutoType()) {
6345 Converted = TemplateArgument(Arg);
6346 return Arg;
6347 }
6348 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6349 // we should actually be checking the type of the template argument in P,
6350 // not the type of the template argument deduced from A, against the
6351 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00006352 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00006353 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00006354 << ParamType.getUnqualifiedType();
6355 Diag(Param->getLocation(), diag::note_template_param_here);
6356 return ExprError();
6357 }
6358
Richard Smith87d263e2016-12-25 08:05:23 +00006359 // If either the parameter has a dependent type or the argument is
6360 // type-dependent, there's nothing we can check now.
6361 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6362 // FIXME: Produce a cloned, canonical expression?
6363 Converted = TemplateArgument(Arg);
6364 return Arg;
6365 }
6366
Richard Smithe5945872017-01-06 22:52:53 +00006367 // The initialization of the parameter from the argument is
6368 // a constant-evaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006369 EnterExpressionEvaluationContext ConstantEvaluated(
6370 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smithe5945872017-01-06 22:52:53 +00006371
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006372 if (getLangOpts().CPlusPlus17) {
6373 // C++17 [temp.arg.nontype]p1:
Richard Smith410cc892014-11-26 03:26:53 +00006374 // A template-argument for a non-type template parameter shall be
6375 // a converted constant expression of the type of the template-parameter.
6376 APValue Value;
6377 ExprResult ArgResult = CheckConvertedConstantExpression(
6378 Arg, ParamType, Value, CCEK_TemplateArg);
6379 if (ArgResult.isInvalid())
6380 return ExprError();
6381
Richard Smith52e624f2016-12-21 21:42:57 +00006382 // For a value-dependent argument, CheckConvertedConstantExpression is
6383 // permitted (and expected) to be unable to determine a value.
6384 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00006385 Converted = TemplateArgument(ArgResult.get());
6386 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00006387 }
6388
Richard Smithd663fdd2014-12-17 20:42:37 +00006389 QualType CanonParamType = Context.getCanonicalType(ParamType);
6390
Richard Smith410cc892014-11-26 03:26:53 +00006391 // Convert the APValue to a TemplateArgument.
6392 switch (Value.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00006393 case APValue::None:
Richard Smith410cc892014-11-26 03:26:53 +00006394 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006395 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006396 break;
Richard Smithe637cbe2019-05-21 23:15:18 +00006397 case APValue::Indeterminate:
6398 llvm_unreachable("result of constant evaluation should be initialized");
6399 break;
Richard Smith410cc892014-11-26 03:26:53 +00006400 case APValue::Int:
6401 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006402 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00006403 break;
6404 case APValue::MemberPointer: {
6405 assert(ParamType->isMemberPointerType());
6406
6407 // FIXME: We need TemplateArgument representation and mangling for these.
6408 if (!Value.getMemberPointerPath().empty()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006409 Diag(Arg->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00006410 diag::err_template_arg_member_ptr_base_derived_not_supported)
6411 << Value.getMemberPointerDecl() << ParamType
6412 << Arg->getSourceRange();
6413 return ExprError();
6414 }
6415
6416 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00006417 Converted = VD ? TemplateArgument(VD, CanonParamType)
6418 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006419 break;
6420 }
6421 case APValue::LValue: {
6422 // For a non-type template-parameter of pointer or reference type,
6423 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00006424 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6425 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00006426 // -- a temporary object
6427 // -- a string literal
6428 // -- the result of a typeid expression, or
Eric Christopher0d2c56a2017-03-31 01:45:39 +00006429 // -- a predefined __func__ variable
Richard Smithee0ce3022019-05-17 07:06:46 +00006430 APValue::LValueBase Base = Value.getLValueBase();
6431 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6432 if (Base && !VD) {
6433 auto *E = Base.dyn_cast<const Expr *>();
6434 if (E && isa<CXXUuidofExpr>(E)) {
Bill Wendlingff573072019-01-27 07:24:03 +00006435 Converted = TemplateArgument(ArgResult.get()->IgnoreImpCasts());
Richard Smith410cc892014-11-26 03:26:53 +00006436 break;
6437 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006438 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6439 << Arg->getSourceRange();
Richard Smith410cc892014-11-26 03:26:53 +00006440 return ExprError();
6441 }
Richard Smith410cc892014-11-26 03:26:53 +00006442 // -- a subobject
6443 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6444 VD && VD->getType()->isArrayType() &&
Richard Smith5b5e27a2019-05-10 20:05:31 +00006445 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
Richard Smith410cc892014-11-26 03:26:53 +00006446 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6447 // Per defect report (no number yet):
6448 // ... other than a pointer to the first element of a complete array
6449 // object.
6450 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6451 Value.isLValueOnePastTheEnd()) {
6452 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6453 << Value.getAsString(Context, ParamType);
6454 return ExprError();
6455 }
Richard Smithd663fdd2014-12-17 20:42:37 +00006456 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00006457 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00006458 assert((!VD || !ParamType->isNullPtrType()) &&
6459 "non-null value of type nullptr_t?");
6460 Converted = VD ? TemplateArgument(VD, CanonParamType)
6461 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006462 break;
6463 }
6464 case APValue::AddrLabelDiff:
6465 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
Leonard Chan86285d22019-01-16 18:53:05 +00006466 case APValue::FixedPoint:
Richard Smith410cc892014-11-26 03:26:53 +00006467 case APValue::Float:
6468 case APValue::ComplexInt:
6469 case APValue::ComplexFloat:
6470 case APValue::Vector:
6471 case APValue::Array:
6472 case APValue::Struct:
6473 case APValue::Union:
6474 llvm_unreachable("invalid kind for template argument");
6475 }
6476
6477 return ArgResult.get();
6478 }
6479
Douglas Gregor86560402009-02-10 23:36:10 +00006480 // C++ [temp.arg.nontype]p5:
6481 // The following conversions are performed on each expression used
6482 // as a non-type template-argument. If a non-type
6483 // template-argument cannot be converted to the type of the
6484 // corresponding template-parameter then the program is
6485 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00006486 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00006487 // C++11:
6488 // -- for a non-type template-parameter of integral or
6489 // enumeration type, conversions permitted in a converted
6490 // constant expression are applied.
6491 //
6492 // C++98:
6493 // -- for a non-type template-parameter of integral or
6494 // enumeration type, integral promotions (4.5) and integral
6495 // conversions (4.7) are applied.
6496
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006497 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00006498 // C++ [temp.arg.nontype]p1:
6499 // A template-argument for a non-type, non-template template-parameter
6500 // shall be one of:
6501 //
6502 // -- for a non-type template-parameter of integral or enumeration
6503 // type, a converted constant expression of the type of the
6504 // template-parameter; or
6505 llvm::APSInt Value;
6506 ExprResult ArgResult =
6507 CheckConvertedConstantExpression(Arg, ParamType, Value,
6508 CCEK_TemplateArg);
6509 if (ArgResult.isInvalid())
6510 return ExprError();
6511
Richard Smith01bfa682016-12-27 02:02:09 +00006512 // We can't check arbitrary value-dependent arguments.
6513 if (ArgResult.get()->isValueDependent()) {
6514 Converted = TemplateArgument(ArgResult.get());
6515 return ArgResult;
6516 }
6517
Richard Smithf8379a02012-01-18 23:55:52 +00006518 // Widen the argument value to sizeof(parameter type). This is almost
6519 // always a no-op, except when the parameter type is bool. In
6520 // that case, this may extend the argument from 1 bit to 8 bits.
6521 QualType IntegerType = ParamType;
6522 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6523 IntegerType = Enum->getDecl()->getIntegerType();
6524 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6525
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006526 Converted = TemplateArgument(Context, Value,
6527 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00006528 return ArgResult;
6529 }
6530
Richard Smith08b12f12011-10-27 22:11:44 +00006531 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6532 if (ArgResult.isInvalid())
6533 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006534 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00006535
6536 QualType ArgType = Arg->getType();
6537
Douglas Gregor86560402009-02-10 23:36:10 +00006538 // C++ [temp.arg.nontype]p1:
6539 // A template-argument for a non-type, non-template
6540 // template-parameter shall be one of:
6541 //
6542 // -- an integral constant-expression of integral or enumeration
6543 // type; or
6544 // -- the name of a non-type template-parameter; or
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006545 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00006546 if (!ArgType->isIntegralOrEnumerationType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006547 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6548 << ArgType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006549 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006550 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00006551 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00006552 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6553 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006554
Douglas Gregore2b37442012-05-04 22:38:52 +00006555 public:
6556 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00006557
6558 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6559 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00006560 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6561 }
6562 } Diagnoser(ArgType);
6563
6564 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006565 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00006566 if (!Arg)
6567 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006568 }
6569
Richard Smithd663fdd2014-12-17 20:42:37 +00006570 // From here on out, all we care about is the unqualified form
6571 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006572 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00006573
6574 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00006575 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00006576 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00006577 } else if (ParamType->isBooleanType()) {
6578 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006579 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006580 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6581 !ParamType->isEnumeralType()) {
6582 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006583 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006584 } else {
6585 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006586 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6587 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006588 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006589 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006590 }
6591
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006592 // Add the value of this argument to the list of converted
6593 // arguments. We use the bitwidth and signedness of the template
6594 // parameter.
6595 if (Arg->isValueDependent()) {
6596 // The argument is value-dependent. Create a new
6597 // TemplateArgument with the converted expression.
6598 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006599 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006600 }
6601
Douglas Gregor52aba872009-03-14 00:20:21 +00006602 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00006603 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00006604 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00006605
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006606 if (ParamType->isBooleanType()) {
6607 // Value must be zero or one.
6608 Value = Value != 0;
6609 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6610 if (Value.getBitWidth() != AllowedBits)
6611 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006612 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006613 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006614 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006615
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006616 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006617 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006618 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006619 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006620 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006621 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00006622
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006623 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006624 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006625 && (OldValue.isSigned() && OldValue.isNegative())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006626 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6627 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6628 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006629 Diag(Param->getLocation(), diag::note_template_param_here);
6630 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006631
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006632 // Complain if we overflowed the template parameter's type.
6633 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006634 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006635 RequiredBits = OldValue.getActiveBits();
6636 else if (OldValue.isUnsigned())
6637 RequiredBits = OldValue.getActiveBits() + 1;
6638 else
6639 RequiredBits = OldValue.getMinSignedBits();
6640 if (RequiredBits > AllowedBits) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006641 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6642 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6643 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006644 Diag(Param->getLocation(), diag::note_template_param_here);
6645 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006646 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006647
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006648 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006649 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006650 ? Context.getCanonicalType(ParamType)
6651 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006652 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006653 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006654
Richard Smith08b12f12011-10-27 22:11:44 +00006655 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006656 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6657
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006658 // Handle pointer-to-function, reference-to-function, and
6659 // pointer-to-member-function all in (roughly) the same way.
6660 if (// -- For a non-type template-parameter of type pointer to
6661 // function, only the function-to-pointer conversion (4.3) is
6662 // applied. If the template-argument represents a set of
6663 // overloaded functions (or a pointer to such), the matching
6664 // function is selected from the set (13.4).
6665 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006666 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006667 // -- For a non-type template-parameter of type reference to
6668 // function, no conversions apply. If the template-argument
6669 // represents a set of overloaded functions, the matching
6670 // function is selected from the set (13.4).
6671 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006672 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006673 // -- For a non-type template-parameter of type pointer to
6674 // member function, no conversions apply. If the
6675 // template-argument represents a set of overloaded member
6676 // functions, the matching member function is selected from
6677 // the set (13.4).
6678 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006679 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006680 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006681
Douglas Gregor064fdb22010-04-14 23:11:21 +00006682 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006683 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006684 true,
6685 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006686 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006687 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006688
6689 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6690 ArgType = Arg->getType();
6691 } else
John Wiegley01296292011-04-08 18:41:53 +00006692 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006694
John Wiegley01296292011-04-08 18:41:53 +00006695 if (!ParamType->isMemberPointerType()) {
6696 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6697 ParamType,
6698 Arg, Converted))
6699 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006700 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006701 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006702
Douglas Gregor20fdef32012-04-10 17:08:25 +00006703 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6704 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006705 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006706 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006707 }
6708
Chris Lattner696197c2009-02-20 21:37:53 +00006709 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006710 // -- for a non-type template-parameter of type pointer to
6711 // object, qualification conversions (4.4) and the
6712 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006713 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006714 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006715 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006716
John Wiegley01296292011-04-08 18:41:53 +00006717 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6718 ParamType,
6719 Arg, Converted))
6720 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006721 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006722 }
Mike Stump11289f42009-09-09 15:08:12 +00006723
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006724 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006725 // -- For a non-type template-parameter of type reference to
6726 // object, no conversions apply. The type referred to by the
6727 // reference may be more cv-qualified than the (otherwise
6728 // identical) type of the template-argument. The
6729 // template-parameter is bound directly to the
6730 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006731 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006732 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006733
Douglas Gregor064fdb22010-04-14 23:11:21 +00006734 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006735 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6736 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006737 true,
6738 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006739 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006740 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006741
6742 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6743 ArgType = Arg->getType();
6744 } else
John Wiegley01296292011-04-08 18:41:53 +00006745 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006747
John Wiegley01296292011-04-08 18:41:53 +00006748 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6749 ParamType,
6750 Arg, Converted))
6751 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006752 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006753 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006754
Douglas Gregor20fdef32012-04-10 17:08:25 +00006755 // Deal with parameters of type std::nullptr_t.
6756 if (ParamType->isNullPtrType()) {
6757 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6758 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006759 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006760 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006761
Douglas Gregor20fdef32012-04-10 17:08:25 +00006762 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6763 case NPV_NotNullPointer:
6764 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6765 << Arg->getType() << ParamType;
6766 Diag(Param->getLocation(), diag::note_template_param_here);
6767 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006768
Douglas Gregor20fdef32012-04-10 17:08:25 +00006769 case NPV_Error:
6770 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006771
Douglas Gregor20fdef32012-04-10 17:08:25 +00006772 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006773 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006774 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6775 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006776 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006777 }
6778 }
6779
Douglas Gregor0e558532009-02-11 16:16:59 +00006780 // -- For a non-type template-parameter of type pointer to data
6781 // member, qualification conversions (4.4) are applied.
6782 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6783
Douglas Gregor20fdef32012-04-10 17:08:25 +00006784 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6785 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006786 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006787 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006788}
6789
Richard Smith26b86ea2016-12-31 21:41:23 +00006790static void DiagnoseTemplateParameterListArityMismatch(
6791 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6792 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6793
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006794/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006795/// template template parameter.
6796///
6797/// This routine implements the semantics of C++ [temp.arg.template].
6798/// It returns true if an error occurred, and false otherwise.
Richard Smith5d331022018-03-08 01:07:33 +00006799bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6800 TemplateArgumentLoc &Arg) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006801 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006802 TemplateDecl *Template = Name.getAsTemplateDecl();
6803 if (!Template) {
6804 // Any dependent template name is fine.
6805 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6806 return false;
6807 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006808
Richard Smith26b86ea2016-12-31 21:41:23 +00006809 if (Template->isInvalidDecl())
6810 return true;
6811
Richard Smith3f1b5d02011-05-05 21:57:07 +00006812 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006813 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006814 // the name of a class template or an alias template, expressed as an
6815 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006816 // primary class templates are considered when matching the
6817 // template template argument with the corresponding parameter;
6818 // partial specializations are not considered even if their
6819 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006820 //
6821 // Note that we also allow template template parameters here, which
6822 // will happen when we are dealing with, e.g., class template
6823 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006824 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006825 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006826 !isa<TypeAliasTemplateDecl>(Template) &&
6827 !isa<BuiltinTemplateDecl>(Template)) {
6828 assert(isa<FunctionTemplateDecl>(Template) &&
6829 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006830 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006831 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6832 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006833 }
6834
Richard Smith26b86ea2016-12-31 21:41:23 +00006835 // C++1z [temp.arg.template]p3: (DR 150)
6836 // A template-argument matches a template template-parameter P when P
6837 // is at least as specialized as the template-argument A.
6838 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6839 // Quick check for the common case:
6840 // If P contains a parameter pack, then A [...] matches P if each of A's
6841 // template parameters matches the corresponding template parameter in
6842 // the template-parameter-list of P.
6843 if (TemplateParameterListsAreEqual(
6844 Template->getTemplateParameters(), Params, false,
6845 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6846 return false;
6847
6848 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6849 Arg.getLocation()))
6850 return false;
6851 // FIXME: Produce better diagnostics for deduction failures.
6852 }
6853
Douglas Gregor85e0f662009-02-10 00:24:35 +00006854 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006855 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006856 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006857 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006858 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006859}
6860
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006861/// Given a non-type template argument that refers to a
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006862/// declaration and the type of its corresponding non-type template
6863/// parameter, produce an expression that properly refers to that
6864/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006865ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006866Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6867 QualType ParamType,
6868 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006869 // C++ [temp.param]p8:
6870 //
6871 // A non-type template-parameter of type "array of T" or
6872 // "function returning T" is adjusted to be of type "pointer to
6873 // T" or "pointer to function returning T", respectively.
6874 if (ParamType->isArrayType())
6875 ParamType = Context.getArrayDecayedType(ParamType);
6876 else if (ParamType->isFunctionType())
6877 ParamType = Context.getPointerType(ParamType);
6878
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006879 // For a NULL non-type template argument, return nullptr casted to the
6880 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006881 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006882 return ImpCastExprToType(
6883 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6884 ParamType,
6885 ParamType->getAs<MemberPointerType>()
6886 ? CK_NullToMemberPointer
6887 : CK_NullToPointer);
6888 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006889 assert(Arg.getKind() == TemplateArgument::Declaration &&
6890 "Only declaration template arguments permitted here");
6891
George Burgess IV00f70bd2018-03-01 05:43:23 +00006892 ValueDecl *VD = Arg.getAsDecl();
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006893
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006894 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006895 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6896 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006897 // If the value is a class member, we might have a pointer-to-member.
6898 // Determine whether the non-type template template parameter is of
6899 // pointer-to-member type. If so, we need to build an appropriate
6900 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6901 // would refer to the member itself.
6902 if (ParamType->isMemberPointerType()) {
6903 QualType ClassType
6904 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6905 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006906 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006907 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006908 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006909 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006910
6911 // The actual value-ness of this is unimportant, but for
6912 // internal consistency's sake, references to instance methods
6913 // are r-values.
6914 ExprValueKind VK = VK_LValue;
6915 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6916 VK = VK_RValue;
6917
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006918 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006919 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006920 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006921 Loc,
6922 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006923 if (RefExpr.isInvalid())
6924 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006925
John McCalle3027922010-08-25 11:45:40 +00006926 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006927
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006928 // We might need to perform a trailing qualification conversion, since
6929 // the element type on the parameter could be more qualified than the
6930 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006931 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006932 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006933 ParamType.getUnqualifiedType(), false,
6934 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006935 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006936
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006937 assert(!RefExpr.isInvalid() &&
6938 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006939 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006940 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006941 }
6942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006943
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006944 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006945
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006946 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006947 // When the non-type template parameter is a pointer, take the
6948 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006949 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006950 if (RefExpr.isInvalid())
6951 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006952
Richard Smithfc6fca12017-01-28 00:38:35 +00006953 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6954 (T->isFunctionType() || T->isArrayType())) {
6955 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006956 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006957 if (RefExpr.isInvalid())
6958 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006959
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006960 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006961 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006962
Douglas Gregorb242683d2010-04-01 18:32:35 +00006963 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006964 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006965 }
6966
John McCall7decc9e2010-11-18 06:31:45 +00006967 ExprValueKind VK = VK_RValue;
6968
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006969 // If the non-type template parameter has reference type, qualify the
6970 // resulting declaration reference with the extra qualifiers on the
6971 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006972 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6973 VK = VK_LValue;
6974 T = Context.getQualifiedType(T,
6975 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006976 } else if (isa<FunctionDecl>(VD)) {
6977 // References to functions are always lvalues.
6978 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006980
John McCall7decc9e2010-11-18 06:31:45 +00006981 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006982}
6983
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006984/// Construct a new expression that refers to the given
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006985/// integral template argument with the given source-location
6986/// information.
6987///
6988/// This routine takes care of the mapping from an integral template
6989/// argument (which may have any integral type) to the appropriate
6990/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006991ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006992Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6993 SourceLocation Loc) {
6994 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006995 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006996 QualType OrigT = Arg.getIntegralType();
6997
6998 // If this is an enum type that we're instantiating, we need to use an integer
6999 // type the same size as the enumerator. We don't want to build an
7000 // IntegerLiteral with enum type. The integer type of an enum type can be of
7001 // any integral type with C++11 enum classes, make sure we create the right
7002 // type of literal for it.
7003 QualType T = OrigT;
7004 if (const EnumType *ET = OrigT->getAs<EnumType>())
7005 T = ET->getDecl()->getIntegerType();
7006
7007 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00007008 if (T->isAnyCharacterType()) {
7009 CharacterLiteral::CharacterKind Kind;
7010 if (T->isWideCharType())
7011 Kind = CharacterLiteral::Wide;
Richard Smith3a8244d2018-05-01 05:02:45 +00007012 else if (T->isChar8Type() && getLangOpts().Char8)
7013 Kind = CharacterLiteral::UTF8;
Douglas Gregorfb65e592011-07-27 05:40:30 +00007014 else if (T->isChar16Type())
7015 Kind = CharacterLiteral::UTF16;
7016 else if (T->isChar32Type())
7017 Kind = CharacterLiteral::UTF32;
7018 else
7019 Kind = CharacterLiteral::Ascii;
7020
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007021 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
7022 Kind, T, Loc);
7023 } else if (T->isBooleanType()) {
7024 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
7025 T, Loc);
7026 } else if (T->isNullPtrType()) {
7027 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
7028 } else {
7029 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00007030 }
7031
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007032 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00007033 // FIXME: This is a hack. We need a better way to handle substituted
7034 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00007035 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
7036 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007037 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00007038 Loc, Loc);
7039 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00007040
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007041 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007042}
7043
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007044/// Match two template parameters within template parameter lists.
Douglas Gregor641040a2011-01-12 23:45:44 +00007045static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
7046 bool Complain,
7047 Sema::TemplateParameterListEqualKind Kind,
7048 SourceLocation TemplateArgLoc) {
7049 // Check the actual kind (type, non-type, template).
7050 if (Old->getKind() != New->getKind()) {
7051 if (Complain) {
7052 unsigned NextDiag = diag::err_template_param_different_kind;
7053 if (TemplateArgLoc.isValid()) {
7054 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7055 NextDiag = diag::note_template_param_different_kind;
7056 }
7057 S.Diag(New->getLocation(), NextDiag)
7058 << (Kind != Sema::TPL_TemplateMatch);
7059 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7060 << (Kind != Sema::TPL_TemplateMatch);
7061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007062
Douglas Gregor641040a2011-01-12 23:45:44 +00007063 return false;
7064 }
7065
Richard Smith26b86ea2016-12-31 21:41:23 +00007066 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007067 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007068 // template template parameter, the template template parameter can have
7069 // a parameter pack where the template template argument does not.
7070 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7071 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7072 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00007073 if (Complain) {
7074 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7075 if (TemplateArgLoc.isValid()) {
7076 S.Diag(TemplateArgLoc,
7077 diag::err_template_arg_template_params_mismatch);
7078 NextDiag = diag::note_template_parameter_pack_non_pack;
7079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007080
Douglas Gregor641040a2011-01-12 23:45:44 +00007081 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7082 : isa<NonTypeTemplateParmDecl>(New)? 1
7083 : 2;
7084 S.Diag(New->getLocation(), NextDiag)
7085 << ParamKind << New->isParameterPack();
7086 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7087 << ParamKind << Old->isParameterPack();
7088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007089
Douglas Gregor641040a2011-01-12 23:45:44 +00007090 return false;
7091 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007092
Douglas Gregor641040a2011-01-12 23:45:44 +00007093 // For non-type template parameters, check the type of the parameter.
7094 if (NonTypeTemplateParmDecl *OldNTTP
7095 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7096 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007097
Douglas Gregor641040a2011-01-12 23:45:44 +00007098 // If we are matching a template template argument to a template
7099 // template parameter and one of the non-type template parameter types
Richard Smith13894182017-04-13 21:37:24 +00007100 // is dependent, then we must wait until template instantiation time
7101 // to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00007102 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith13894182017-04-13 21:37:24 +00007103 (OldNTTP->getType()->isDependentType() ||
7104 NewNTTP->getType()->isDependentType()))
Douglas Gregor641040a2011-01-12 23:45:44 +00007105 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007106
Douglas Gregor641040a2011-01-12 23:45:44 +00007107 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
7108 if (Complain) {
7109 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7110 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007111 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00007112 diag::err_template_arg_template_params_mismatch);
7113 NextDiag = diag::note_template_nontype_parm_different_type;
7114 }
7115 S.Diag(NewNTTP->getLocation(), NextDiag)
7116 << NewNTTP->getType()
7117 << (Kind != Sema::TPL_TemplateMatch);
7118 S.Diag(OldNTTP->getLocation(),
7119 diag::note_template_nontype_parm_prev_declaration)
7120 << OldNTTP->getType();
7121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007122
Douglas Gregor641040a2011-01-12 23:45:44 +00007123 return false;
7124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007125
Douglas Gregor641040a2011-01-12 23:45:44 +00007126 return true;
7127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007128
Douglas Gregor641040a2011-01-12 23:45:44 +00007129 // For template template parameters, check the template parameter types.
7130 // The template parameter lists of template template
7131 // parameters must agree.
7132 if (TemplateTemplateParmDecl *OldTTP
7133 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007134 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00007135 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7136 OldTTP->getTemplateParameters(),
7137 Complain,
7138 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007139 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00007140 : Kind),
7141 TemplateArgLoc);
7142 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007143
Douglas Gregor641040a2011-01-12 23:45:44 +00007144 return true;
7145}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007146
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007147/// Diagnose a known arity mismatch when comparing template argument
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007148/// lists.
7149static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007150void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007151 TemplateParameterList *New,
7152 TemplateParameterList *Old,
7153 Sema::TemplateParameterListEqualKind Kind,
7154 SourceLocation TemplateArgLoc) {
7155 unsigned NextDiag = diag::err_template_param_list_different_arity;
7156 if (TemplateArgLoc.isValid()) {
7157 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7158 NextDiag = diag::note_template_param_list_different_arity;
7159 }
7160 S.Diag(New->getTemplateLoc(), NextDiag)
7161 << (New->size() > Old->size())
7162 << (Kind != Sema::TPL_TemplateMatch)
7163 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7164 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7165 << (Kind != Sema::TPL_TemplateMatch)
7166 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7167}
7168
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007169/// Determine whether the given template parameter lists are
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007170/// equivalent.
7171///
Mike Stump11289f42009-09-09 15:08:12 +00007172/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007173/// source code as part of a new template declaration.
7174///
7175/// \param Old The old template parameter list, typically found via
7176/// name lookup of the template declared with this template parameter
7177/// list.
7178///
7179/// \param Complain If true, this routine will produce a diagnostic if
7180/// the template parameter lists are not equivalent.
7181///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007182/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00007183///
7184/// \param TemplateArgLoc If this source location is valid, then we
7185/// are actually checking the template parameter list of a template
7186/// argument (New) against the template parameter list of its
7187/// corresponding template template parameter (Old). We produce
7188/// slightly different diagnostics in this scenario.
7189///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007190/// \returns True if the template parameter lists are equal, false
7191/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00007192bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007193Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7194 TemplateParameterList *Old,
7195 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007196 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00007197 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007198 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7199 if (Complain)
7200 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7201 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007202
7203 return false;
7204 }
7205
Douglas Gregor641040a2011-01-12 23:45:44 +00007206 // C++0x [temp.arg.template]p3:
7207 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007208 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00007209 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007210 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007211 // template-parameter-list of P. [...]
7212 TemplateParameterList::iterator NewParm = New->begin();
7213 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007214 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007215 OldParmEnd = Old->end();
7216 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00007217 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7218 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007219 if (NewParm == NewParmEnd) {
7220 if (Complain)
7221 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7222 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007223
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007224 return false;
7225 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007226
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007227 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7228 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007229 return false;
7230
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007231 ++NewParm;
7232 continue;
7233 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007234
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007235 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007236 // [...] When P's template- parameter-list contains a template parameter
7237 // pack (14.5.3), the template parameter pack will match zero or more
7238 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007239 // template-parameter-list of A with the same type and form as the
7240 // template parameter pack in P (ignoring whether those template
7241 // parameters are template parameter packs).
7242 for (; NewParm != NewParmEnd; ++NewParm) {
7243 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7244 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007245 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007246 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007247 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007248
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007249 // Make sure we exhausted all of the arguments.
7250 if (NewParm != NewParmEnd) {
7251 if (Complain)
7252 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7253 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007254
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007255 return false;
7256 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007257
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007258 return true;
7259}
7260
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007261/// Check whether a template can be declared within this scope.
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007262///
7263/// If the template declaration is valid in this scope, returns
7264/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00007265bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007266Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00007267 if (!S)
7268 return false;
7269
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007270 // Find the nearest enclosing declaration scope.
7271 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7272 (S->getFlags() & Scope::TemplateParamScope) != 0)
7273 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00007274
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007275 // C++ [temp]p4:
7276 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007277 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00007278 if (Ctx && Ctx->isExternCContext()) {
7279 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7280 << TemplateParams->getSourceRange();
7281 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7282 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7283 return true;
7284 }
Richard Smith8df390f2016-09-08 23:14:54 +00007285 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007286
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007287 // C++ [temp]p2:
7288 // A template-declaration can appear only as a namespace scope or
7289 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00007290 if (Ctx) {
7291 if (Ctx->isFileContext())
7292 return false;
7293 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7294 // C++ [temp.mem]p2:
7295 // A local class shall not have member templates.
7296 if (RD->isLocalClass())
7297 return Diag(TemplateParams->getTemplateLoc(),
7298 diag::err_template_inside_local_class)
7299 << TemplateParams->getSourceRange();
7300 else
7301 return false;
7302 }
7303 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007304
Mike Stump11289f42009-09-09 15:08:12 +00007305 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007306 diag::err_template_outside_namespace_or_class_scope)
7307 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007308}
Douglas Gregor67a65642009-02-17 23:15:12 +00007309
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007310/// Determine what kind of template specialization the given declaration
Douglas Gregor54888652009-10-07 00:13:32 +00007311/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007312static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00007313 if (!D)
7314 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007315
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007316 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7317 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00007318 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7319 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007320 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7321 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007322
Douglas Gregor54888652009-10-07 00:13:32 +00007323 return TSK_Undeclared;
7324}
7325
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007326/// Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007327/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00007328///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007329/// This routine determines whether a template specialization can be declared
7330/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00007331///
7332/// \param S the semantic analysis object for which this check is being
7333/// performed.
7334///
7335/// \param Specialized the entity being specialized or instantiated, which
7336/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007337/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00007338/// member class).
7339///
7340/// \param PrevDecl the previous declaration of this entity, if any.
7341///
7342/// \param Loc the location of the explicit specialization or instantiation of
7343/// this entity.
7344///
7345/// \param IsPartialSpecialization whether this is a partial specialization of
7346/// a class template.
7347///
Douglas Gregor54888652009-10-07 00:13:32 +00007348/// \returns true if there was an error that we cannot recover from, false
7349/// otherwise.
7350static bool CheckTemplateSpecializationScope(Sema &S,
7351 NamedDecl *Specialized,
7352 NamedDecl *PrevDecl,
7353 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007354 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00007355 // Keep these "kind" numbers in sync with the %select statements in the
7356 // various diagnostics emitted by this routine.
7357 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007358 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007359 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007360 else if (isa<VarTemplateDecl>(Specialized))
7361 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007362 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007363 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007364 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007365 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007366 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00007367 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007368 else if (isa<RecordDecl>(Specialized))
7369 EntityKind = 7;
7370 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7371 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00007372 else {
Richard Smith7d137e32012-03-23 03:33:32 +00007373 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007374 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007375 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00007376 return true;
7377 }
7378
Douglas Gregorf47b9112009-02-25 22:02:03 +00007379 // C++ [temp.expl.spec]p2:
Richard Smithc660c8f2018-03-16 13:36:56 +00007380 // An explicit specialization may be declared in any scope in which
7381 // the corresponding primary template may be defined.
Sebastian Redl50c68252010-08-31 00:36:30 +00007382 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00007383 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007384 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007385 return true;
7386 }
Douglas Gregore4b05162009-10-07 17:21:34 +00007387
7388 // C++ [temp.class.spec]p6:
Richard Smithc660c8f2018-03-16 13:36:56 +00007389 // A class template partial specialization may be declared in any
7390 // scope in which the primary template may be defined.
7391 DeclContext *SpecializedContext =
7392 Specialized->getDeclContext()->getRedeclContext();
7393 DeclContext *DC = S.CurContext->getRedeclContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00007394
Richard Smithc660c8f2018-03-16 13:36:56 +00007395 // Make sure that this redeclaration (or definition) occurs in the same
7396 // scope or an enclosing namespace.
7397 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7398 : DC->Equals(SpecializedContext))) {
Richard Smitha98f8fc2013-12-07 05:09:50 +00007399 if (isa<TranslationUnitDecl>(SpecializedContext))
7400 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7401 << EntityKind << Specialized;
Richard Smithc660c8f2018-03-16 13:36:56 +00007402 else {
7403 auto *ND = cast<NamedDecl>(SpecializedContext);
Alexey Bataev0068cb22015-03-20 07:21:46 +00007404 int Diag = diag::err_template_spec_redecl_out_of_scope;
Richard Smithc660c8f2018-03-16 13:36:56 +00007405 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
Alexey Bataev0068cb22015-03-20 07:21:46 +00007406 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7407 S.Diag(Loc, Diag) << EntityKind << Specialized
Richard Smithc660c8f2018-03-16 13:36:56 +00007408 << ND << isa<CXXRecordDecl>(ND);
7409 }
Richard Smitha98f8fc2013-12-07 05:09:50 +00007410
7411 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007412
Richard Smithc660c8f2018-03-16 13:36:56 +00007413 // Don't allow specializing in the wrong class during error recovery.
7414 // Otherwise, things can go horribly wrong.
7415 if (DC->isRecord())
7416 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007418
Douglas Gregorf47b9112009-02-25 22:02:03 +00007419 return false;
7420}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007421
Richard Smith57aae072016-12-28 02:37:25 +00007422static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7423 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00007424 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007425 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007426 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00007427 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007428 return E->getSourceRange();
7429 return Checker.MatchLoc;
7430}
7431
7432static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7433 if (!TL.getType()->isDependentType())
7434 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007435 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007436 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00007437 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007438 return TL.getSourceRange();
7439 return Checker.MatchLoc;
7440}
7441
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007442/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007443/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007444static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007445 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7446 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007447 for (unsigned I = 0; I != NumArgs; ++I) {
7448 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007449 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007450 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7451 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007452 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007453
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007454 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007455 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007456
Eli Friedmanb826a002012-09-26 02:36:12 +00007457 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007458 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00007459
7460 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007461
Douglas Gregor98318c22011-01-03 21:37:45 +00007462 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007463 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7464 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00007465
7466 // Strip off any implicit casts we added as part of type checking.
7467 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7468 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007469
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007470 // C++ [temp.class.spec]p8:
7471 // A non-type argument is non-specialized if it is the name of a
7472 // non-type parameter. All other non-type arguments are
7473 // specialized.
7474 //
7475 // Below, we check the two conditions that only apply to
7476 // specialized non-type arguments, so skip any non-specialized
7477 // arguments.
7478 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00007479 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007480 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007481
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007482 // C++ [temp.class.spec]p9:
7483 // Within the argument list of a class template partial
7484 // specialization, the following restrictions apply:
7485 // -- A partially specialized non-type argument expression
7486 // shall not involve a template parameter of the partial
7487 // specialization except when the argument expression is a
7488 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00007489 // -- The type of a template parameter corresponding to a
7490 // specialized non-type argument shall not be dependent on a
7491 // parameter of the specialization.
7492 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7493 // We implement a compromise between the original rules and DR1315:
7494 // -- A specialized non-type template argument shall not be
7495 // type-dependent and the corresponding template parameter
7496 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00007497 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00007498 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00007499 if (ParamUseRange.isValid()) {
7500 if (IsDefaultArgument) {
7501 S.Diag(TemplateNameLoc,
7502 diag::err_dependent_non_type_arg_in_partial_spec);
7503 S.Diag(ParamUseRange.getBegin(),
7504 diag::note_dependent_non_type_default_arg_in_partial_spec)
7505 << ParamUseRange;
7506 } else {
7507 S.Diag(ParamUseRange.getBegin(),
7508 diag::err_dependent_non_type_arg_in_partial_spec)
7509 << ParamUseRange;
7510 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007511 return true;
7512 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007513
Richard Smith6056d5e2014-02-09 00:54:43 +00007514 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00007515 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00007516 if (ParamUseRange.isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007517 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
Richard Smith6056d5e2014-02-09 00:54:43 +00007518 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007519 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00007520 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00007521 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7522 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007523 return true;
7524 }
7525 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007526
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007527 return false;
7528}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007529
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007530/// Check the non-type template arguments of a class template
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007531/// partial specialization according to C++ [temp.class.spec]p9.
7532///
Richard Smith6056d5e2014-02-09 00:54:43 +00007533/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00007534/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00007535/// template.
7536/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00007537/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00007538/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007539///
Richard Smith6056d5e2014-02-09 00:54:43 +00007540/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00007541bool Sema::CheckTemplatePartialSpecializationArgs(
7542 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7543 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7544 // We have to be conservative when checking a template in a dependent
7545 // context.
7546 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7547 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007548
Richard Smith57aae072016-12-28 02:37:25 +00007549 TemplateParameterList *TemplateParams =
7550 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007551 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7552 NonTypeTemplateParmDecl *Param
7553 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7554 if (!Param)
7555 continue;
7556
Richard Smith57aae072016-12-28 02:37:25 +00007557 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7558 Param, &TemplateArgs[I],
7559 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007560 return true;
7561 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007562
7563 return false;
7564}
7565
Erich Keanec480f302018-07-12 21:09:05 +00007566DeclResult Sema::ActOnClassTemplateSpecialization(
7567 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7568 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7569 const ParsedAttributesView &Attr,
7570 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007571 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007572
Richard Smith4b55a9c2014-04-17 03:29:33 +00007573 CXXScopeSpec &SS = TemplateId.SS;
7574
Abramo Bagnara60804e12011-03-18 15:16:37 +00007575 // NOTE: KWLoc is the location of the tag keyword. This will instead
7576 // store the location of the outermost template keyword in the declaration.
7577 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007578 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7579 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7580 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7581 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007582
Douglas Gregor67a65642009-02-17 23:15:12 +00007583 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007584 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007585 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007586 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7587
7588 if (!ClassTemplate) {
7589 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007590 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007591 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7592 return true;
7593 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007594
Richard Smithf445f192017-02-09 21:04:43 +00007595 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007596 bool isPartialSpecialization = false;
7597
Douglas Gregorf47b9112009-02-25 22:02:03 +00007598 // Check the validity of the template headers that introduce this
7599 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007600 // FIXME: We probably shouldn't complain about these headers for
7601 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007602 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007603 TemplateParameterList *TemplateParams =
7604 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007605 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007606 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007607 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007608 if (Invalid)
7609 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007610
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007611 if (TemplateParams && TemplateParams->size() > 0) {
7612 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007613
Douglas Gregorec9518b2010-12-21 08:14:57 +00007614 if (TUK == TUK_Friend) {
7615 Diag(KWLoc, diag::err_partial_specialization_friend)
7616 << SourceRange(LAngleLoc, RAngleLoc);
7617 return true;
7618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007619
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007620 // C++ [temp.class.spec]p10:
7621 // The template parameter list of a specialization shall not
7622 // contain default template argument values.
7623 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7624 Decl *Param = TemplateParams->getParam(I);
7625 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7626 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007627 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007628 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007629 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007630 }
7631 } else if (NonTypeTemplateParmDecl *NTTP
7632 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7633 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007634 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007635 diag::err_default_arg_in_partial_spec)
7636 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007637 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007638 }
7639 } else {
7640 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007641 if (TTP->hasDefaultArgument()) {
7642 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007643 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007644 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007645 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007646 }
7647 }
7648 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007649 } else if (TemplateParams) {
7650 if (TUK == TUK_Friend)
7651 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007652 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007653 SourceRange(TemplateParams->getTemplateLoc(),
7654 TemplateParams->getRAngleLoc()))
7655 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007656 } else {
7657 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007658 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007659
Douglas Gregor67a65642009-02-17 23:15:12 +00007660 // Check that the specialization uses the same tag kind as the
7661 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007662 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7663 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007664 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007665 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007666 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007667 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007668 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007669 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007670 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007671 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007672 diag::note_previous_use);
7673 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7674 }
7675
Douglas Gregorc40290e2009-03-09 23:48:35 +00007676 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007677 TemplateArgumentListInfo TemplateArgs =
7678 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007679
Douglas Gregor14406932011-01-03 20:35:03 +00007680 // Check for unexpanded parameter packs in any of the template arguments.
7681 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007682 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007683 UPPC_PartialSpecialization))
7684 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007685
Douglas Gregor67a65642009-02-17 23:15:12 +00007686 // Check that the template argument list is well-formed for this
7687 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007688 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007689 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7690 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007691 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007692
Douglas Gregor2373c592009-05-31 09:31:02 +00007693 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007694 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007695 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007696 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7697 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007698 return true;
7699
Richard Smith57aae072016-12-28 02:37:25 +00007700 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7701 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007702 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007703 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007704 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007705 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007706 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7707 << ClassTemplate->getDeclName();
7708 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007709 }
7710 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007711
Craig Topperc3ec1492014-05-26 06:22:03 +00007712 void *InsertPos = nullptr;
7713 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007714
7715 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007716 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007717 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007718 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007719 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007720
Craig Topperc3ec1492014-05-26 06:22:03 +00007721 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007722
Douglas Gregorf47b9112009-02-25 22:02:03 +00007723 // Check whether we can declare a class template specialization in
7724 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007725 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007726 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7727 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007728 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007729 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007730
Douglas Gregor15301382009-07-30 17:40:51 +00007731 // The canonical type
7732 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007733 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007734 // Build the canonical type that describes the converted template
7735 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007736 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7737 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007738 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007739
7740 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007741 ClassTemplate->getInjectedClassNameSpecialization())) {
7742 // C++ [temp.class.spec]p9b3:
7743 //
7744 // -- The argument list of the specialization shall not be identical
7745 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007746 //
7747 // This rule has since been removed, because it's redundant given DR1495,
7748 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007749 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007750 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007751 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007752 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7753 ClassTemplate->getIdentifier(),
7754 TemplateNameLoc,
7755 Attr,
7756 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007757 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007758 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007759 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007760 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007761 }
Douglas Gregor15301382009-07-30 17:40:51 +00007762
Douglas Gregor2373c592009-05-31 09:31:02 +00007763 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007764 ClassTemplatePartialSpecializationDecl *PrevPartial
7765 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007766 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007767 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007768 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007769 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007770 TemplateParams,
7771 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007772 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007773 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007774 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007775 PrevPartial);
Bruno Ricci4224c872018-12-21 14:35:24 +00007776 SetNestedNameSpecifier(*this, Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007777 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007778 Partial->setTemplateParameterListsInfo(
7779 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007780 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007781
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007782 if (!PrevPartial)
7783 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007784 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007785
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007786 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007787 // template specialization, make a note of that.
7788 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7789 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007790
Richard Smith57aae072016-12-28 02:37:25 +00007791 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007792 } else {
7793 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007794 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007795 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007796 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007797 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007798 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007799 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007800 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007801 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00007802 SetNestedNameSpecifier(*this, Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007803 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007804 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007805 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007806 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007807
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007808 if (!PrevDecl)
7809 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007810
David Majnemer678f50b2015-11-18 19:49:19 +00007811 if (CurContext->isDependentContext()) {
David Majnemer678f50b2015-11-18 19:49:19 +00007812 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7813 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007814 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007815 } else {
7816 CanonType = Context.getTypeDeclType(Specialization);
7817 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007818 }
7819
Douglas Gregor06db9f52009-10-12 20:18:28 +00007820 // C++ [temp.expl.spec]p6:
7821 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007822 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007823 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007824 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007825 // use occurs; no diagnostic is required.
7826 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007827 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007828 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007829 // Is there any previous explicit specialization declaration?
7830 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7831 Okay = true;
7832 break;
7833 }
7834 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007835
Douglas Gregorc854c662010-02-26 06:03:23 +00007836 if (!Okay) {
7837 SourceRange Range(TemplateNameLoc, RAngleLoc);
7838 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7839 << Context.getTypeDeclType(Specialization) << Range;
7840
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007841 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007842 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007843 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007844 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007845 return true;
7846 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007847 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007848
Douglas Gregor2208a292009-09-26 20:57:03 +00007849 // If this is not a friend, note that this is an explicit specialization.
7850 if (TUK != TUK_Friend)
7851 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007852
7853 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007854 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007855 RecordDecl *Def = Specialization->getDefinition();
7856 NamedDecl *Hidden = nullptr;
7857 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7858 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00007859 SkipBody->Previous = Def;
Richard Smith858e0e02017-05-11 23:11:16 +00007860 makeMergedDefinitionVisible(Hidden);
Richard Smithc7e6ff02015-05-18 20:36:47 +00007861 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007862 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007863 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007864 Diag(Def->getLocation(), diag::note_previous_definition);
7865 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007866 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007867 }
7868 }
7869
Erich Keanec480f302018-07-12 21:09:05 +00007870 ProcessDeclAttributeList(S, Specialization, Attr);
John McCall659a3372010-12-18 03:30:47 +00007871
Richard Smith034b94a2012-08-17 03:20:55 +00007872 // Add alignment attributes if necessary; these attributes are checked when
7873 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00007874 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Richard Smith034b94a2012-08-17 03:20:55 +00007875 AddAlignmentAttributesForRecord(Specialization);
7876 AddMsStructLayoutForRecord(Specialization);
7877 }
7878
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007879 if (ModulePrivateLoc.isValid())
7880 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7881 << (isPartialSpecialization? 1 : 0)
7882 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007883
Douglas Gregord56a91e2009-02-26 22:19:44 +00007884 // Build the fully-sugared type for this class template
7885 // specialization as the user wrote in the specialization
7886 // itself. This means that we'll pretty-print the type retrieved
7887 // from the specialization's declaration the way that the user
7888 // actually wrote the specialization, rather than formatting the
7889 // name based on the "canonical" representation used to store the
7890 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007891 TypeSourceInfo *WrittenTy
7892 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7893 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007894 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007895 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007896 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007897 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007898
Douglas Gregor1e249f82009-02-25 22:18:32 +00007899 // C++ [temp.expl.spec]p9:
7900 // A template explicit specialization is in the scope of the
7901 // namespace in which the template was defined.
7902 //
7903 // We actually implement this paragraph where we set the semantic
7904 // context (in the creation of the ClassTemplateSpecializationDecl),
7905 // but we also maintain the lexical context where the actual
7906 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007907 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007908
Douglas Gregor67a65642009-02-17 23:15:12 +00007909 // We may be starting the definition of this specialization.
Richard Smithc4577662018-09-12 02:13:47 +00007910 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregor67a65642009-02-17 23:15:12 +00007911 Specialization->startDefinition();
7912
Douglas Gregor2208a292009-09-26 20:57:03 +00007913 if (TUK == TUK_Friend) {
7914 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7915 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007916 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007917 /*FIXME:*/KWLoc);
7918 Friend->setAccess(AS_public);
7919 CurContext->addDecl(Friend);
7920 } else {
7921 // Add the specialization into its lexical context, so that it can
7922 // be seen when iterating through the list of declarations in that
7923 // context. However, specializations are not found by name lookup.
7924 CurContext->addDecl(Specialization);
7925 }
Richard Smithc4577662018-09-12 02:13:47 +00007926
7927 if (SkipBody && SkipBody->ShouldSkip)
7928 return SkipBody->Previous;
7929
John McCall48871652010-08-21 09:40:31 +00007930 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007931}
Douglas Gregor333489b2009-03-27 23:10:48 +00007932
John McCall48871652010-08-21 09:40:31 +00007933Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007934 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007935 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007936 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007937 ActOnDocumentableDecl(NewDecl);
7938 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007939}
7940
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007941/// Strips various properties off an implicit instantiation
John McCall4f7ced62010-02-11 01:33:53 +00007942/// that has just been explicitly specialized.
7943static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007944 D->dropAttr<DLLImportAttr>();
7945 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007946
Nico Webere4974382014-12-19 23:52:45 +00007947 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007948 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007949}
7950
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007951/// Compute the diagnostic location for an explicit instantiation
Nico Webera8f80b32012-01-09 19:52:25 +00007952// declaration or definition.
7953static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007954 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007955 // Explicit instantiations following a specialization have no effect and
7956 // hence no PointOfInstantiation. In that case, walk decl backwards
7957 // until a valid name loc is found.
7958 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007959 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7960 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007961 PrevDiagLoc = Prev->getLocation();
7962 }
7963 assert(PrevDiagLoc.isValid() &&
7964 "Explicit instantiation without point of instantiation?");
7965 return PrevDiagLoc;
7966}
7967
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007968/// Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007969/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007970/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007971/// new specialization/instantiation will have any effect.
7972///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007973/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007974/// instantiation.
7975///
7976/// \param NewTSK the kind of the new explicit specialization or instantiation.
7977///
7978/// \param PrevDecl the previous declaration of the entity.
7979///
7980/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7981///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007982/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007983/// declaration was instantiated (either implicitly or explicitly).
7984///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007985/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007986/// specialization or instantiation has no effect and should be ignored.
7987///
7988/// \returns true if there was an error that should prevent the introduction of
7989/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007990bool
7991Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7992 TemplateSpecializationKind NewTSK,
7993 NamedDecl *PrevDecl,
7994 TemplateSpecializationKind PrevTSK,
7995 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007996 bool &HasNoEffect) {
7997 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007998
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007999 switch (NewTSK) {
8000 case TSK_Undeclared:
8001 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00008002 assert(
8003 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8004 "previous declaration must be implicit!");
8005 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008006
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008007 case TSK_ExplicitSpecialization:
8008 switch (PrevTSK) {
8009 case TSK_Undeclared:
8010 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008011 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008012 // explicitly specialized or has merely been mentioned without any
8013 // instantiation.
8014 return false;
8015
8016 case TSK_ImplicitInstantiation:
8017 if (PrevPointOfInstantiation.isInvalid()) {
8018 // The declaration itself has not actually been instantiated, so it is
8019 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00008020 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008021 return false;
8022 }
8023 // Fall through
Galina Kistanova3779cb32017-06-07 06:25:05 +00008024 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008025
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008026 case TSK_ExplicitInstantiationDeclaration:
8027 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008028 assert((PrevTSK == TSK_ImplicitInstantiation ||
8029 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008030 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008031
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008032 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008033 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008034 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008035 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008036 // implicit instantiation to take place, in every translation unit in
8037 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00008038 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00008039 // Is there any previous explicit specialization declaration?
8040 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
8041 return false;
8042 }
8043
Douglas Gregor1d957a32009-10-27 18:42:08 +00008044 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008045 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008046 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008047 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008048
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008049 return true;
8050 }
Galina Kistanova1d36e832017-06-08 18:20:32 +00008051 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008052
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008053 case TSK_ExplicitInstantiationDeclaration:
8054 switch (PrevTSK) {
8055 case TSK_ExplicitInstantiationDeclaration:
8056 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00008057 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008058 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008059
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008060 case TSK_Undeclared:
8061 case TSK_ImplicitInstantiation:
8062 // We're explicitly instantiating something that may have already been
8063 // implicitly instantiated; that's fine.
8064 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008065
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008066 case TSK_ExplicitSpecialization:
8067 // C++0x [temp.explicit]p4:
8068 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008069 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008070 // specialization for that template, the explicit instantiation has no
8071 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008072 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008073 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008074
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008075 case TSK_ExplicitInstantiationDefinition:
8076 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008077 // If an entity is the subject of both an explicit instantiation
8078 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008079 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008080 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00008081 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00008082
8083 // Explicit instantiations following a specialization have no effect and
8084 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8085 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00008086 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8087 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008088 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008089 return false;
8090 }
Bruno Riccid8c17672018-12-21 20:38:06 +00008091 llvm_unreachable("Unexpected TemplateSpecializationKind!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008092
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008093 case TSK_ExplicitInstantiationDefinition:
8094 switch (PrevTSK) {
8095 case TSK_Undeclared:
8096 case TSK_ImplicitInstantiation:
8097 // We're explicitly instantiating something that may have already been
8098 // implicitly instantiated; that's fine.
8099 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008100
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008101 case TSK_ExplicitSpecialization:
8102 // C++ DR 259, C++0x [temp.explicit]p4:
8103 // For a given set of template parameters, if an explicit
8104 // instantiation of a template appears after a declaration of
8105 // an explicit specialization for that template, the explicit
8106 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00008107 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00008108 << PrevDecl;
8109 Diag(PrevDecl->getLocation(),
8110 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008111 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008112 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008113
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008114 case TSK_ExplicitInstantiationDeclaration:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008115 // We're explicitly instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008116 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00008117
8118 // C++0x [temp.explicit]p4:
8119 // For a given set of template parameters, if an explicit instantiation
8120 // of a template appears after a declaration of an explicit
8121 // specialization for that template, the explicit instantiation has no
8122 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00008123 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00008124 // Is there any previous explicit specialization declaration?
8125 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8126 HasNoEffect = true;
8127 break;
8128 }
8129 }
8130
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008131 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008132
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008133 case TSK_ExplicitInstantiationDefinition:
8134 // C++0x [temp.spec]p5:
8135 // For a given template and a given set of template-arguments,
8136 // - an explicit instantiation definition shall appear at most once
8137 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008138
8139 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8140 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00008141 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008142 : diag::err_explicit_instantiation_duplicate)
8143 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00008144 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00008145 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008146 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008147 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008148 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008150
David Blaikie83d382b2011-09-23 05:06:16 +00008151 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008152}
8153
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008154/// Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00008155/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00008156///
James Dennettf14a6e52012-06-15 22:23:43 +00008157/// The only possible way to get a dependent function template specialization
8158/// is with a friend declaration, like so:
8159///
8160/// \code
8161/// template \<class T> void foo(T);
8162/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00008163/// friend void foo<>(T);
8164/// };
James Dennettf14a6e52012-06-15 22:23:43 +00008165/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00008166///
8167/// There really isn't any useful analysis we can do here, so we
8168/// just store the information.
8169bool
8170Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8171 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8172 LookupResult &Previous) {
8173 // Remove anything from Previous that isn't a function template in
8174 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00008175 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00008176 LookupResult::Filter F = Previous.makeFilter();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008177 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8178 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
John McCallb9c78482010-04-08 09:05:18 +00008179 while (F.hasNext()) {
8180 NamedDecl *D = F.next()->getUnderlyingDecl();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008181 if (!isa<FunctionTemplateDecl>(D)) {
John McCallb9c78482010-04-08 09:05:18 +00008182 F.erase();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008183 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8184 continue;
8185 }
8186
8187 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8188 D->getDeclContext()->getRedeclContext())) {
8189 F.erase();
8190 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8191 continue;
8192 }
John McCallb9c78482010-04-08 09:05:18 +00008193 }
8194 F.done();
8195
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008196 if (Previous.empty()) {
8197 Diag(FD->getLocation(),
8198 diag::err_dependent_function_template_spec_no_match);
8199 for (auto &P : DiscardedCandidates)
8200 Diag(P.second->getLocation(),
8201 diag::note_dependent_function_template_spec_discard_reason)
8202 << P.first;
8203 return true;
8204 }
John McCallb9c78482010-04-08 09:05:18 +00008205
8206 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8207 ExplicitTemplateArgs);
8208 return false;
8209}
8210
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008211/// Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008212/// specialization.
8213///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008214/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008215/// explicit function template specialization. On successful completion,
8216/// the function declaration \p FD will become a function template
8217/// specialization.
8218///
8219/// \param FD the function declaration, which will be updated to become a
8220/// function template specialization.
8221///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008222/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8223/// if any. Note that this may be valid info even when 0 arguments are
8224/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8225/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008226///
Francois Pichet3a44e432011-07-08 06:21:47 +00008227/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008228/// this function specialization.
Richard Smith8ce732b2019-01-07 06:00:46 +00008229///
8230/// \param QualifiedFriend whether this is a lookup for a qualified friend
8231/// declaration with no explicit template argument list that might be
8232/// befriending a function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008233bool Sema::CheckFunctionTemplateSpecialization(
8234 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smith8ce732b2019-01-07 06:00:46 +00008235 LookupResult &Previous, bool QualifiedFriend) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008236 // The set of function template specializations that could match this
8237 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00008238 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008239 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8240 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008241
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008242 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8243 ConvertedTemplateArgs;
8244
Sebastian Redl50c68252010-08-31 00:36:30 +00008245 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00008246 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8247 I != E; ++I) {
8248 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8249 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008250 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008251 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00008252 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8253 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008254 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008255
Richard Smith574f4f62013-01-14 05:37:29 +00008256 // When matching a constexpr member function template specialization
8257 // against the primary template, we don't yet know whether the
8258 // specialization has an implicit 'const' (because we don't know whether
8259 // it will be a static member function until we know which template it
8260 // specializes), so adjust it now assuming it specializes this template.
8261 QualType FT = FD->getType();
8262 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008263 CXXMethodDecl *OldMD =
8264 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00008265 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008266 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00008267 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00008268 EPI.TypeQuals.addConst();
Alp Toker314cc812014-01-25 16:55:45 +00008269 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008270 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00008271 }
8272 }
8273
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008274 TemplateArgumentListInfo Args;
8275 if (ExplicitTemplateArgs)
8276 Args = *ExplicitTemplateArgs;
8277
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008278 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008279 // A trailing template-argument can be left unspecified in the
8280 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008281 // provided it can be deduced from the function argument type.
8282 // Perform template argument deduction to determine whether we may be
8283 // specializing this template.
8284 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00008285 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008286 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00008287 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8288 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00008289 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8290 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008291 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008292 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00008293 FailedCandidates.addCandidate().set(
8294 I.getPair(), FunTmpl->getTemplatedDecl(),
8295 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008296 (void)TDK;
8297 continue;
8298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008299
Artem Belevich64135c32016-12-08 19:38:13 +00008300 // Target attributes are part of the cuda function signature, so
8301 // the deduced template's cuda target must match that of the
8302 // specialization. Given that C++ template deduction does not
8303 // take target attributes into account, we reject candidates
8304 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008305 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00008306 IdentifyCUDATarget(Specialization,
8307 /* IgnoreImplicitHDAttributes = */ true) !=
8308 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008309 FailedCandidates.addCandidate().set(
8310 I.getPair(), FunTmpl->getTemplatedDecl(),
8311 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8312 continue;
8313 }
8314
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008315 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008316 if (ExplicitTemplateArgs)
8317 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00008318 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008319 }
8320 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008321
Richard Smith8ce732b2019-01-07 06:00:46 +00008322 // For a qualified friend declaration (with no explicit marker to indicate
8323 // that a template specialization was intended), note all (template and
8324 // non-template) candidates.
8325 if (QualifiedFriend && Candidates.empty()) {
8326 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8327 << FD->getDeclName() << FDLookupContext;
8328 // FIXME: We should form a single candidate list and diagnose all
8329 // candidates at once, to get proper sorting and limiting.
8330 for (auto *OldND : Previous) {
8331 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8332 NoteOverloadCandidate(OldND, OldFD, FD->getType(), false);
8333 }
8334 FailedCandidates.NoteCandidates(*this, FD->getLocation());
8335 return true;
8336 }
8337
Douglas Gregor5de279c2009-09-26 03:41:46 +00008338 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008339 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith8ce732b2019-01-07 06:00:46 +00008340 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008341 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8342 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00008343 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008344 PDiag(diag::note_function_template_spec_matched));
8345
John McCall58cc69d2010-01-27 01:50:18 +00008346 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008347 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008348
8349 // Ignore access information; it doesn't figure into redeclaration checking.
8350 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00008351
8352 FunctionTemplateSpecializationInfo *SpecInfo
8353 = Specialization->getTemplateSpecializationInfo();
8354 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00008355
8356 // Note: do not overwrite location info if previous template
8357 // specialization kind was explicit.
8358 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00008359 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00008360 Specialization->setLocation(FD->getLocation());
Richard Smith54f04402017-05-18 02:29:20 +00008361 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
Richard Smith5b8b3db2012-02-20 23:28:05 +00008362 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8363 // function can differ from the template declaration with respect to
8364 // the constexpr specifier.
Richard Smith77e9e842017-05-09 23:02:10 +00008365 // FIXME: We need an update record for this AST mutation.
8366 // FIXME: What if there are multiple such prior declarations (for instance,
8367 // from different modules)?
Richard Smith5b8b3db2012-02-20 23:28:05 +00008368 Specialization->setConstexpr(FD->isConstexpr());
8369 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008370
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008371 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00008372 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00008373
8374 // If this is a friend declaration, then we're not really declaring
8375 // an explicit specialization.
8376 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008377
Douglas Gregor54888652009-10-07 00:13:32 +00008378 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00008379 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008380 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00008381 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008382 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008383 false))
Douglas Gregor54888652009-10-07 00:13:32 +00008384 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008385
8386 // C++ [temp.expl.spec]p6:
8387 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008388 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008389 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008390 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008391 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008392 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00008393 if (!isFriend &&
8394 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00008395 TSK_ExplicitSpecialization,
8396 Specialization,
8397 SpecInfo->getTemplateSpecializationKind(),
8398 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008399 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008400 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008401
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008402 // Mark the prior declaration as an explicit specialization, so that later
8403 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008404 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00008405 // Since explicit specializations do not inherit '=delete' from their
8406 // primary function template - check if the 'specialization' that was
8407 // implicitly generated (during template argument deduction for partial
8408 // ordering) from the most specialized of all the function templates that
8409 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8410 // first check that it was implicitly generated during template argument
8411 // deduction by making sure it wasn't referenced, and then reset the deleted
8412 // flag to not-deleted, so that we can inherit that information from 'FD'.
8413 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8414 !Specialization->getCanonicalDecl()->isReferenced()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008415 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali81a88be2016-06-14 03:23:15 +00008416 assert(
8417 Specialization->getCanonicalDecl() == Specialization &&
8418 "This must be the only existing declaration of this specialization");
Richard Smith77e9e842017-05-09 23:02:10 +00008419 // FIXME: We need an update record for this AST mutation.
Faisal Vali81a88be2016-06-14 03:23:15 +00008420 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008421 }
Richard Smith54f04402017-05-18 02:29:20 +00008422 // FIXME: We need an update record for this AST mutation.
John McCall816d75b2010-03-24 07:46:06 +00008423 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008424 MarkUnusedFileScopedDecl(Specialization);
8425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008426
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008427 // Turn the given function declaration into a function template
8428 // specialization, with the template arguments from the previous
8429 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008430 // Take copies of (semantic and syntactic) template argument lists.
8431 const TemplateArgumentList* TemplArgs = new (Context)
8432 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008433 FD->setFunctionTemplateSpecialization(
8434 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8435 SpecInfo->getTemplateSpecializationKind(),
8436 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008437
Artem Belevich64135c32016-12-08 19:38:13 +00008438 // A function template specialization inherits the target attributes
8439 // of its template. (We require the attributes explicitly in the
8440 // code to match, but a template may have implicit attributes by
8441 // virtue e.g. of being constexpr, and it passes these implicit
8442 // attributes on to its specializations.)
8443 if (LangOpts.CUDA)
8444 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8445
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008446 // The "previous declaration" for this function template specialization is
8447 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00008448 Previous.clear();
8449 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008450 return false;
8451}
8452
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008453/// Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008454/// specialization.
8455///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008456/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008457/// explicit member function specialization. On successful completion,
8458/// the function declaration \p FD will become a member function
8459/// specialization.
8460///
Douglas Gregor86d142a2009-10-08 07:24:58 +00008461/// \param Member the member declaration, which will be updated to become a
8462/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008463///
John McCall1f82f242009-11-18 22:49:29 +00008464/// \param Previous the set of declarations, one of which may be specialized
8465/// by this function specialization; the set will be modified to contain the
8466/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008467bool
John McCall1f82f242009-11-18 22:49:29 +00008468Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008469 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00008470
Douglas Gregor86d142a2009-10-08 07:24:58 +00008471 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00008472 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00008473 NamedDecl *Instantiation = nullptr;
8474 NamedDecl *InstantiatedFrom = nullptr;
8475 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008476
John McCall1f82f242009-11-18 22:49:29 +00008477 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008478 // Nowhere to look anyway.
8479 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008480 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8481 I != E; ++I) {
8482 NamedDecl *D = (*I)->getUnderlyingDecl();
8483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00008484 QualType Adjusted = Function->getType();
8485 if (!hasExplicitCallingConv(Adjusted))
8486 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
Richard Smith4576a772018-09-10 06:35:32 +00008487 // This doesn't handle deduced return types, but both function
8488 // declarations should be undeduced at this point.
Rafael Espindola66747222013-12-10 00:59:31 +00008489 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008490 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008491 Instantiation = Method;
8492 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008493 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008494 break;
8495 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008496 }
8497 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00008498 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008499 VarDecl *PrevVar;
8500 if (Previous.isSingleResult() &&
8501 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00008502 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008503 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008504 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008505 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008506 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008507 }
8508 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008509 CXXRecordDecl *PrevRecord;
8510 if (Previous.isSingleResult() &&
8511 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008512 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008513 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008514 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008515 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008516 }
Richard Smith7d137e32012-03-23 03:33:32 +00008517 } else if (isa<EnumDecl>(Member)) {
8518 EnumDecl *PrevEnum;
8519 if (Previous.isSingleResult() &&
8520 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008521 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00008522 Instantiation = PrevEnum;
8523 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8524 MSInfo = PrevEnum->getMemberSpecializationInfo();
8525 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008526 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008527
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008528 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008529 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008530 // specializations are always out-of-line, the caller will complain about
8531 // this mismatch later.
8532 return false;
8533 }
John McCalle820e5e2010-04-13 20:37:33 +00008534
Richard Smith77e9e842017-05-09 23:02:10 +00008535 // A member specialization in a friend declaration isn't really declaring
8536 // an explicit specialization, just identifying a specific (possibly implicit)
8537 // specialization. Don't change the template specialization kind.
8538 //
8539 // FIXME: Is this really valid? Other compilers reject.
John McCalle820e5e2010-04-13 20:37:33 +00008540 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8541 // Preserve instantiation information.
8542 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8543 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8544 cast<CXXMethodDecl>(InstantiatedFrom),
8545 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8546 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8547 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8548 cast<CXXRecordDecl>(InstantiatedFrom),
8549 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8550 }
8551
8552 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008553 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00008554 return false;
8555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008556
Douglas Gregor86d142a2009-10-08 07:24:58 +00008557 // Make sure that this is a specialization of a member.
8558 if (!InstantiatedFrom) {
8559 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8560 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008561 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8562 return true;
8563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008564
Douglas Gregor06db9f52009-10-12 20:18:28 +00008565 // C++ [temp.expl.spec]p6:
8566 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00008567 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008568 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008569 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008570 // use occurs; no diagnostic is required.
8571 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00008572
Abramo Bagnara8075c852010-06-12 07:44:57 +00008573 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00008574 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8575 TSK_ExplicitSpecialization,
8576 Instantiation,
8577 MSInfo->getTemplateSpecializationKind(),
8578 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008579 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008580 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008581
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008582 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008583 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008584 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008585 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008586 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008587 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008588
Richard Smith77e9e842017-05-09 23:02:10 +00008589 // Note that this member specialization is an "instantiation of" the
8590 // corresponding member of the original template.
8591 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008592 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8593 if (InstantiationFunction->getTemplateSpecializationKind() ==
8594 TSK_ImplicitInstantiation) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008595 // Explicit specializations of member functions of class templates do not
8596 // inherit '=delete' from the member function they are specializing.
8597 if (InstantiationFunction->isDeleted()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008598 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008599 assert(InstantiationFunction->getCanonicalDecl() ==
8600 InstantiationFunction);
Richard Smith77e9e842017-05-09 23:02:10 +00008601 // FIXME: We need an update record for this AST mutation.
Richard Smith5f274382016-09-28 23:55:27 +00008602 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008603 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008605
Richard Smith77e9e842017-05-09 23:02:10 +00008606 MemberFunction->setInstantiationOfMemberFunction(
8607 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8608 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8609 MemberVar->setInstantiationOfStaticDataMember(
Larisse Voufo39a1e502013-08-06 01:03:05 +00008610 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008611 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8612 MemberClass->setInstantiationOfMemberClass(
8613 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8614 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8615 MemberEnum->setInstantiationOfMemberEnum(
Richard Smith7d137e32012-03-23 03:33:32 +00008616 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008617 } else {
8618 llvm_unreachable("unknown member specialization kind");
Douglas Gregor86d142a2009-10-08 07:24:58 +00008619 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008620
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008621 // Save the caller the trouble of having to figure out which declaration
8622 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008623 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008624 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008625 return false;
8626}
8627
Richard Smith77e9e842017-05-09 23:02:10 +00008628/// Complete the explicit specialization of a member of a class template by
8629/// updating the instantiated member to be marked as an explicit specialization.
8630///
8631/// \param OrigD The member declaration instantiated from the template.
8632/// \param Loc The location of the explicit specialization of the member.
8633template<typename DeclT>
8634static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8635 SourceLocation Loc) {
8636 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8637 return;
8638
8639 // FIXME: Inform AST mutation listeners of this AST mutation.
8640 // FIXME: If there are multiple in-class declarations of the member (from
8641 // multiple modules, or a declaration and later definition of a member type),
8642 // should we update all of them?
8643 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8644 OrigD->setLocation(Loc);
8645}
8646
8647void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8648 LookupResult &Previous) {
8649 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8650 if (Instantiation == Member)
8651 return;
8652
8653 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8654 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8655 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8656 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8657 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8658 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8659 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8660 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8661 else
8662 llvm_unreachable("unknown member specialization kind");
8663}
8664
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008665/// Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008666///
8667/// \returns true if a serious error occurs, false otherwise.
8668static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008669 SourceLocation InstLoc,
8670 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008671 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8672 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008673
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008674 if (CurContext->isRecord()) {
8675 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8676 << D;
8677 return true;
8678 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008679
Richard Smith050d2612011-10-18 02:28:33 +00008680 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008681 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008682 // template. If the name declared in the explicit instantiation is an
8683 // unqualified name, the explicit instantiation shall appear in the
8684 // namespace where its template is declared or, if that namespace is inline
8685 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008686 //
8687 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008688 if (WasQualifiedName) {
8689 if (CurContext->Encloses(OrigContext))
8690 return false;
8691 } else {
8692 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8693 return false;
8694 }
8695
8696 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8697 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008698 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008699 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008700 diag::err_explicit_instantiation_out_of_scope :
8701 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008702 << D << NS;
8703 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008704 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008705 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008706 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8707 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8708 << D << NS;
8709 } else
8710 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008711 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008712 diag::err_explicit_instantiation_must_be_global :
8713 diag::warn_explicit_instantiation_must_be_global_0x)
8714 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008715 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008716 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008717}
8718
Richard Smith0d923af2019-04-26 01:51:07 +00008719/// Common checks for whether an explicit instantiation of \p D is valid.
8720static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
8721 SourceLocation InstLoc,
8722 bool WasQualifiedName,
8723 TemplateSpecializationKind TSK) {
8724 // C++ [temp.explicit]p13:
8725 // An explicit instantiation declaration shall not name a specialization of
8726 // a template with internal linkage.
8727 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8728 D->getFormalLinkage() == InternalLinkage) {
8729 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
8730 return true;
8731 }
8732
8733 // C++11 [temp.explicit]p3: [DR 275]
8734 // An explicit instantiation shall appear in an enclosing namespace of its
8735 // template.
8736 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
8737 return true;
8738
8739 return false;
8740}
8741
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008742/// Determine whether the given scope specifier has a template-id in it.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008743static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8744 if (!SS.isSet())
8745 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008746
Richard Smith050d2612011-10-18 02:28:33 +00008747 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008748 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008749 // or a static data member of a class template specialization, the name of
8750 // the class template specialization in the qualified-id for the member
8751 // name shall be a simple-template-id.
8752 //
8753 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008754 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8755 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008756 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008757 if (isa<TemplateSpecializationType>(T))
8758 return true;
8759
8760 return false;
8761}
8762
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008763/// Make a dllexport or dllimport attr on a class template specialization take
8764/// effect.
8765static void dllExportImportClassTemplateSpecialization(
8766 Sema &S, ClassTemplateSpecializationDecl *Def) {
8767 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8768 assert(A && "dllExportImportClassTemplateSpecialization called "
8769 "on Def without dllexport or dllimport");
8770
8771 // We reject explicit instantiations in class scope, so there should
8772 // never be any delayed exported classes to worry about.
8773 assert(S.DelayedDllExportClasses.empty() &&
8774 "delayed exports present at explicit instantiation");
8775 S.checkClassLevelDLLAttribute(Def);
8776
8777 // Propagate attribute to base class templates.
8778 for (auto &B : Def->bases()) {
8779 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8780 B.getType()->getAsCXXRecordDecl()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008781 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008782 }
8783
8784 S.referenceDLLExportedClassMethods();
8785}
8786
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008787// Explicit instantiation of a class template specialization
Erich Keanec480f302018-07-12 21:09:05 +00008788DeclResult Sema::ActOnExplicitInstantiation(
8789 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8790 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8791 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
8792 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
8793 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008794 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008795 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008796 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008797 // Check that the specialization uses the same tag kind as the
8798 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008799 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8800 assert(Kind != TTK_Enum &&
8801 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008802
Richard Trieu265c3442016-04-05 21:13:54 +00008803 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8804
8805 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008806 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8807 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008808 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008809 return true;
8810 }
8811
Douglas Gregord9034f02009-05-14 16:41:31 +00008812 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008813 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008814 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008815 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008816 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008817 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008818 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008819 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008820 diag::note_previous_use);
8821 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8822 }
8823
Douglas Gregore47f5a72009-10-14 23:41:34 +00008824 // C++0x [temp.explicit]p2:
8825 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008826 // definition and an explicit instantiation declaration. An explicit
8827 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008828 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8829 ? TSK_ExplicitInstantiationDefinition
8830 : TSK_ExplicitInstantiationDeclaration;
8831
Martin Storsjo5be69bc2019-04-26 08:09:51 +00008832 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8833 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
8834 // Check for dllexport class template instantiation declarations,
8835 // except for MinGW mode.
Erich Keanee891aa92018-07-13 15:07:47 +00008836 for (const ParsedAttr &AL : Attr) {
8837 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00008838 Diag(ExternLoc,
8839 diag::warn_attribute_dllexport_explicit_instantiation_decl);
Erich Keanec480f302018-07-12 21:09:05 +00008840 Diag(AL.getLoc(), diag::note_attribute);
Hans Wennborgfd76d912015-01-15 21:18:30 +00008841 break;
8842 }
8843 }
8844
8845 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8846 Diag(ExternLoc,
8847 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8848 Diag(A->getLocation(), diag::note_attribute);
8849 }
8850 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008851
Hans Wennborga86a83b2016-05-26 19:42:56 +00008852 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8853 // instantiation declarations for most purposes.
8854 bool DLLImportExplicitInstantiationDef = false;
8855 if (TSK == TSK_ExplicitInstantiationDefinition &&
8856 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8857 // Check for dllimport class template instantiation definitions.
8858 bool DLLImport =
8859 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
Erich Keanee891aa92018-07-13 15:07:47 +00008860 for (const ParsedAttr &AL : Attr) {
8861 if (AL.getKind() == ParsedAttr::AT_DLLImport)
Hans Wennborga86a83b2016-05-26 19:42:56 +00008862 DLLImport = true;
Erich Keanee891aa92018-07-13 15:07:47 +00008863 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborga86a83b2016-05-26 19:42:56 +00008864 // dllexport trumps dllimport here.
8865 DLLImport = false;
8866 break;
8867 }
8868 }
8869 if (DLLImport) {
8870 TSK = TSK_ExplicitInstantiationDeclaration;
8871 DLLImportExplicitInstantiationDef = true;
8872 }
8873 }
8874
Douglas Gregora1f49972009-05-13 00:25:59 +00008875 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008876 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008877 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008878
8879 // Check that the template argument list is well-formed for this
8880 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008881 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008882 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8883 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008884 return true;
8885
Douglas Gregora1f49972009-05-13 00:25:59 +00008886 // Find the class template specialization declaration that
8887 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008888 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008889 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008890 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008891
Abramo Bagnara8075c852010-06-12 07:44:57 +00008892 TemplateSpecializationKind PrevDecl_TSK
8893 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8894
Martin Storsjo5be69bc2019-04-26 08:09:51 +00008895 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
8896 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
8897 // Check for dllexport class template instantiation definitions in MinGW
8898 // mode, if a previous declaration of the instantiation was seen.
8899 for (const ParsedAttr &AL : Attr) {
8900 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
8901 Diag(AL.getLoc(),
8902 diag::warn_attribute_dllexport_explicit_instantiation_def);
8903 break;
8904 }
8905 }
8906 }
8907
Richard Smith0d923af2019-04-26 01:51:07 +00008908 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
8909 SS.isSet(), TSK))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008910 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008911
Craig Topperc3ec1492014-05-26 06:22:03 +00008912 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008913
Abramo Bagnara8075c852010-06-12 07:44:57 +00008914 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008915 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008916 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008917 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008918 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008919 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008920 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008921
Abramo Bagnara8075c852010-06-12 07:44:57 +00008922 // Even though HasNoEffect == true means that this explicit instantiation
8923 // has no effect on semantics, we go on to put its syntax in the AST.
8924
8925 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8926 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008927 // Since the only prior class template specialization with these
8928 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008929 // declaration node as our own, updating the source location
8930 // for the template name to reflect our new declaration.
8931 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008932 Specialization = PrevDecl;
8933 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008934 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008935 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008936
8937 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8938 DLLImportExplicitInstantiationDef) {
8939 // The new specialization might add a dllimport attribute.
8940 HasNoEffect = false;
8941 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008942 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008943
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008944 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008945 // Create a new class template specialization declaration node for
8946 // this explicit specialization.
8947 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008948 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008949 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008950 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008951 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008952 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008953 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00008954 SetNestedNameSpecifier(*this, Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008955
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008956 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008957 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008958 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008959 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008960 }
8961
8962 // Build the fully-sugared type for this explicit instantiation as
8963 // the user wrote in the explicit instantiation itself. This means
8964 // that we'll pretty-print the type retrieved from the
8965 // specialization's declaration the way that the user actually wrote
8966 // the explicit instantiation, rather than formatting the name based
8967 // on the "canonical" representation used to store the template
8968 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008969 TypeSourceInfo *WrittenTy
8970 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8971 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008972 Context.getTypeDeclType(Specialization));
8973 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008974
Abramo Bagnara8075c852010-06-12 07:44:57 +00008975 // Set source locations for keywords.
8976 Specialization->setExternLoc(ExternLoc);
8977 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008978 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008979
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008980 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Erich Keanec480f302018-07-12 21:09:05 +00008981 ProcessDeclAttributeList(S, Specialization, Attr);
Rafael Espindola0b062072012-01-03 06:04:21 +00008982
Abramo Bagnara8075c852010-06-12 07:44:57 +00008983 // Add the explicit instantiation into its lexical context. However,
8984 // since explicit instantiations are never found by name lookup, we
8985 // just put it into the declaration context directly.
8986 Specialization->setLexicalDeclContext(CurContext);
8987 CurContext->addDecl(Specialization);
8988
8989 // Syntax is now OK, so return if it has no other effect on semantics.
8990 if (HasNoEffect) {
8991 // Set the template specialization kind.
8992 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008993 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008994 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008995
8996 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008997 // A definition of a class template or class member template
8998 // shall be in scope at the point of the explicit instantiation of
8999 // the class template or class member template.
9000 //
9001 // This check comes when we actually try to perform the
9002 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00009003 ClassTemplateSpecializationDecl *Def
9004 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009005 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00009006 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00009007 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00009008 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00009009 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00009010 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9011 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009012
Douglas Gregor1d957a32009-10-27 18:42:08 +00009013 // Instantiate the members of this class template specialization.
9014 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009015 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00009016 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00009017 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00009018 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9019 // TSK_ExplicitInstantiationDefinition
9020 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00009021 (TSK == TSK_ExplicitInstantiationDefinition ||
9022 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00009023 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00009024 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00009025
Hans Wennborgc0875502015-06-09 00:39:05 +00009026 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00009027 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9028 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00009029 // In the MS ABI, an explicit instantiation definition can add a dll
9030 // attribute to a template with a previous instantiation declaration.
9031 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00009032 auto *A = cast<InheritableAttr>(
9033 getDLLAttr(Specialization)->clone(getASTContext()));
9034 A->setInherited(true);
9035 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00009036 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00009037 }
9038 }
9039
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00009040 // Fix a TSK_ImplicitInstantiation followed by a
9041 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00009042 bool NewlyDLLExported =
9043 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9044 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00009045 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9046 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9047 // In the MS ABI, an explicit instantiation definition can add a dll
9048 // attribute to a template with a previous implicit instantiation.
9049 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
9050 // avoid potentially strange codegen behavior. For example, if we extend
9051 // this conditional to dllimport, and we have a source file calling a
9052 // method on an implicitly instantiated template class instance and then
9053 // declaring a dllimport explicit instantiation definition for the same
9054 // template class, the codegen for the method call will not respect the
9055 // dllimport, while it will with cl. The Def will already have the DLL
9056 // attribute, since the Def and Specialization will be the same in the
9057 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
9058 // attribute to the Specialization; we just need to make it take effect.
9059 assert(Def == Specialization &&
9060 "Def and Specialization should match for implicit instantiation");
9061 dllExportImportClassTemplateSpecialization(*this, Def);
9062 }
9063
Martin Storsjo5be69bc2019-04-26 08:09:51 +00009064 // In MinGW mode, export the template instantiation if the declaration
9065 // was marked dllexport.
9066 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9067 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9068 PrevDecl->hasAttr<DLLExportAttr>()) {
9069 dllExportImportClassTemplateSpecialization(*this, Def);
9070 }
9071
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00009072 // Set the template specialization kind. Make sure it is set before
9073 // instantiating the members which will trigger ASTConsumer callbacks.
9074 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00009075 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00009076 } else {
9077
9078 // Set the template specialization kind.
9079 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00009080 }
Douglas Gregora1f49972009-05-13 00:25:59 +00009081
John McCall48871652010-08-21 09:40:31 +00009082 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00009083}
9084
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009085// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00009086DeclResult
Erich Keanec480f302018-07-12 21:09:05 +00009087Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
9088 SourceLocation TemplateLoc, unsigned TagSpec,
9089 SourceLocation KWLoc, CXXScopeSpec &SS,
9090 IdentifierInfo *Name, SourceLocation NameLoc,
9091 const ParsedAttributesView &Attr) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009092
Douglas Gregord6ab8742009-05-28 23:31:59 +00009093 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00009094 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00009095 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00009096 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00009097 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009098 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00009099 SourceLocation(), false, TypeResult(),
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00009100 /*IsTypeSpecifier*/false,
9101 /*IsTemplateParamOrArg*/false);
John McCall7f41d982009-09-11 04:59:25 +00009102 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
9103
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009104 if (!TagD)
9105 return true;
9106
John McCall48871652010-08-21 09:40:31 +00009107 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00009108 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009109
Douglas Gregorb8006faf2009-05-27 17:30:49 +00009110 if (Tag->isInvalidDecl())
9111 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009112
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009113 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9114 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
9115 if (!Pattern) {
9116 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9117 << Context.getTypeDeclType(Record);
9118 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
9119 return true;
9120 }
9121
Douglas Gregore47f5a72009-10-14 23:41:34 +00009122 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009123 // If the explicit instantiation is for a class or member class, the
9124 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00009125 // simple-template-id.
9126 //
9127 // C++98 has the same restriction, just worded differently.
9128 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00009129 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009130 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009131
Douglas Gregore47f5a72009-10-14 23:41:34 +00009132 // C++0x [temp.explicit]p2:
9133 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009134 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00009135 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00009136 TemplateSpecializationKind TSK
9137 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9138 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009139
Richard Smith0d923af2019-04-26 01:51:07 +00009140 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009141
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009142 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009143 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00009144 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009145 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00009146 PrevDecl = Record;
9147 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009148 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009149 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009150 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009151 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009152 PrevDecl,
9153 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009154 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009155 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009156 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00009157 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009158 return TagD;
9159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009160
Douglas Gregor12e49d32009-10-15 22:53:21 +00009161 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009162 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00009163 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00009164 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009165 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00009166 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009167 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009168 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00009169 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00009170 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9171 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00009172 Diag(Pattern->getLocation(), diag::note_forward_declaration)
9173 << Pattern;
9174 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009175 } else {
9176 if (InstantiateClass(NameLoc, Record, Def,
9177 getTemplateInstantiationArgs(Record),
9178 TSK))
9179 return true;
9180
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009181 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00009182 if (!RecordDef)
9183 return true;
9184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009185 }
9186
Douglas Gregor1d957a32009-10-27 18:42:08 +00009187 // Instantiate all of the members of the class.
9188 InstantiateClassMembers(NameLoc, RecordDef,
9189 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009190
Douglas Gregor88d292c2010-05-13 16:44:06 +00009191 if (TSK == TSK_ExplicitInstantiationDefinition)
9192 MarkVTableUsed(NameLoc, RecordDef, true);
9193
Mike Stump87c57ac2009-05-16 07:39:55 +00009194 // FIXME: We don't have any representation for explicit instantiations of
9195 // member classes. Such a representation is not needed for compilation, but it
9196 // should be available for clients that want to see all of the declarations in
9197 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009198 return TagD;
9199}
9200
John McCallfaf5fb42010-08-26 23:41:50 +00009201DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9202 SourceLocation ExternLoc,
9203 SourceLocation TemplateLoc,
9204 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009205 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009206 // TODO: check if/when DNInfo should replace Name.
9207 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9208 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00009209 if (!Name) {
9210 if (!D.isInvalidType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009211 Diag(D.getDeclSpec().getBeginLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009212 diag::err_explicit_instantiation_requires_name)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009213 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009214
Douglas Gregor450f00842009-09-25 18:43:00 +00009215 return true;
9216 }
9217
9218 // The scope passed in may not be a decl scope. Zip up the scope tree until
9219 // we find one that is.
9220 while ((S->getFlags() & Scope::DeclScope) == 0 ||
9221 (S->getFlags() & Scope::TemplateParamScope) != 0)
9222 S = S->getParent();
9223
9224 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00009225 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9226 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00009227 if (R.isNull())
9228 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009229
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009230 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00009231 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009232 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00009233 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009234 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9235 << Name;
9236 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009237 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009238 != DeclSpec::SCS_unspecified) {
9239 // Complain about then remove the storage class specifier.
9240 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9241 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009242
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009243 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00009244 }
9245
Douglas Gregor3c74d412009-10-14 20:14:33 +00009246 // C++0x [temp.explicit]p1:
9247 // [...] An explicit instantiation of a function template shall not use the
9248 // inline or constexpr specifiers.
9249 // Presumably, this also applies to member functions of class templates as
9250 // well.
Richard Smith83c19292011-10-18 03:44:03 +00009251 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009252 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009253 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00009254 diag::err_explicit_instantiation_inline :
9255 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00009256 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009257 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00009258 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9259 // not already specified.
9260 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9261 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009262
Richard Smith19a311a2017-02-09 22:47:51 +00009263 // A deduction guide is not on the list of entities that can be explicitly
9264 // instantiated.
9265 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009266 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9267 << /*explicit instantiation*/ 0;
Richard Smith19a311a2017-02-09 22:47:51 +00009268 return true;
9269 }
9270
Douglas Gregore47f5a72009-10-14 23:41:34 +00009271 // C++0x [temp.explicit]p2:
9272 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009273 // definition and an explicit instantiation declaration. An explicit
9274 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00009275 TemplateSpecializationKind TSK
9276 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9277 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009278
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009279 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00009280 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00009281
9282 if (!R->isFunctionType()) {
9283 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009284 // A [...] static data member of a class template can be explicitly
9285 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009286 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009287 // C++1y [temp.explicit]p1:
9288 // A [...] variable [...] template specialization can be explicitly
9289 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00009290 if (Previous.isAmbiguous())
9291 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009292
John McCall67c00872009-12-02 08:25:40 +00009293 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00009294 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009295
Larisse Voufo39a1e502013-08-06 01:03:05 +00009296 if (!PrevTemplate) {
9297 if (!Prev || !Prev->isStaticDataMember()) {
Richard Smitha6b41d72019-05-03 23:51:38 +00009298 // We expect to see a static data member here.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009299 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9300 << Name;
9301 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9302 P != PEnd; ++P)
9303 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9304 return true;
9305 }
9306
9307 if (!Prev->getInstantiatedFromStaticDataMember()) {
9308 // FIXME: Check for explicit specialization?
9309 Diag(D.getIdentifierLoc(),
9310 diag::err_explicit_instantiation_data_member_not_instantiated)
9311 << Prev;
9312 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9313 // FIXME: Can we provide a note showing where this was declared?
9314 return true;
9315 }
9316 } else {
9317 // Explicitly instantiate a variable template.
9318
9319 // C++1y [dcl.spec.auto]p6:
9320 // ... A program that uses auto or decltype(auto) in a context not
9321 // explicitly allowed in this section is ill-formed.
9322 //
9323 // This includes auto-typed variable template instantiations.
9324 if (R->isUndeducedType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009325 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009326 diag::err_auto_not_allowed_var_inst);
9327 return true;
9328 }
9329
Faisal Vali2ab8c152017-12-30 04:15:27 +00009330 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Richard Smithef985ac2013-09-18 02:10:12 +00009331 // C++1y [temp.explicit]p3:
9332 // If the explicit instantiation is for a variable, the unqualified-id
9333 // in the declaration shall be a template-id.
9334 Diag(D.getIdentifierLoc(),
9335 diag::err_explicit_instantiation_without_template_id)
9336 << PrevTemplate;
9337 Diag(PrevTemplate->getLocation(),
9338 diag::note_explicit_instantiation_here);
9339 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00009340 }
9341
Richard Smithef985ac2013-09-18 02:10:12 +00009342 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00009343 TemplateArgumentListInfo TemplateArgs =
9344 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00009345
Larisse Voufo39a1e502013-08-06 01:03:05 +00009346 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9347 D.getIdentifierLoc(), TemplateArgs);
9348 if (Res.isInvalid())
9349 return true;
9350
9351 // Ignore access control bits, we don't need them for redeclaration
9352 // checking.
9353 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00009354 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009355
Douglas Gregore47f5a72009-10-14 23:41:34 +00009356 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009357 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009358 // or a static data member of a class template specialization, the name of
9359 // the class template specialization in the qualified-id for the member
9360 // name shall be a simple-template-id.
9361 //
9362 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009363 //
Richard Smith5977d872013-09-18 21:55:14 +00009364 // This does not apply to variable template specializations, where the
9365 // template-id is in the unqualified-id instead.
9366 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009367 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009368 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009369 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009370
Richard Smith0d923af2019-04-26 01:51:07 +00009371 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009372
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009373 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00009374 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9375 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009376 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009377 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00009378 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009379 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009380
Larisse Voufo39a1e502013-08-06 01:03:05 +00009381 if (!HasNoEffect) {
9382 // Instantiate static data member or variable template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009383 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Louis Dionnee6e81752018-10-10 15:32:29 +00009384 // Merge attributes.
9385 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009386 if (TSK == TSK_ExplicitInstantiationDefinition)
9387 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9388 }
9389
9390 // Check the new variable specialization against the parsed input.
9391 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009392 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009393 diag::err_invalid_var_template_spec_type)
9394 << 0 << PrevTemplate << R << Prev->getType();
9395 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9396 << 2 << PrevTemplate->getDeclName();
9397 return true;
9398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009399
Douglas Gregor450f00842009-09-25 18:43:00 +00009400 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00009401 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009403
9404 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00009405 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00009406 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00009407 TemplateArgumentListInfo TemplateArgs;
Faisal Vali2ab8c152017-12-30 04:15:27 +00009408 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00009409 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00009410 HasExplicitTemplateArgs = true;
9411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009412
Douglas Gregor450f00842009-09-25 18:43:00 +00009413 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009414 // A [...] function [...] can be explicitly instantiated from its template.
9415 // A member function [...] of a class template can be explicitly
9416 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009417 // template.
John McCall27c11dd2017-06-07 23:00:05 +00009418 UnresolvedSet<8> TemplateMatches;
9419 FunctionDecl *NonTemplateMatch = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009420 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00009421 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9422 P != PEnd; ++P) {
9423 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00009424 if (!HasExplicitTemplateArgs) {
9425 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00009426 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9427 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00009428 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
John McCall27c11dd2017-06-07 23:00:05 +00009429 if (Method->getPrimaryTemplate()) {
9430 TemplateMatches.addDecl(Method, P.getAccess());
9431 } else {
9432 // FIXME: Can this assert ever happen? Needs a test.
9433 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9434 NonTemplateMatch = Method;
9435 }
Douglas Gregord90fd522009-09-25 21:45:23 +00009436 }
Douglas Gregor450f00842009-09-25 18:43:00 +00009437 }
9438 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009439
Douglas Gregor450f00842009-09-25 18:43:00 +00009440 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9441 if (!FunTmpl)
9442 continue;
9443
Larisse Voufo98b20f12013-07-19 23:00:19 +00009444 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00009445 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009446 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009447 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00009448 (HasExplicitTemplateArgs ? &TemplateArgs
9449 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00009450 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009451 // Keep track of almost-matches.
9452 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00009453 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009454 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00009455 (void)TDK;
9456 continue;
9457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009458
Artem Belevich64135c32016-12-08 19:38:13 +00009459 // Target attributes are part of the cuda function signature, so
9460 // the cuda target of the instantiated function must match that of its
9461 // template. Given that C++ template deduction does not take
9462 // target attributes into account, we reject candidates here that
9463 // have a different target.
9464 if (LangOpts.CUDA &&
9465 IdentifyCUDATarget(Specialization,
9466 /* IgnoreImplicitHDAttributes = */ true) !=
Erich Keanec480f302018-07-12 21:09:05 +00009467 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
Artem Belevich64135c32016-12-08 19:38:13 +00009468 FailedCandidates.addCandidate().set(
9469 P.getPair(), FunTmpl->getTemplatedDecl(),
9470 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9471 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009472 }
9473
John McCall27c11dd2017-06-07 23:00:05 +00009474 TemplateMatches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00009475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009476
John McCall27c11dd2017-06-07 23:00:05 +00009477 FunctionDecl *Specialization = NonTemplateMatch;
9478 if (!Specialization) {
9479 // Find the most specialized function template specialization.
9480 UnresolvedSetIterator Result = getMostSpecialized(
9481 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9482 D.getIdentifierLoc(),
9483 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9484 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9485 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00009486
John McCall27c11dd2017-06-07 23:00:05 +00009487 if (Result == TemplateMatches.end())
9488 return true;
John McCall58cc69d2010-01-27 01:50:18 +00009489
John McCall27c11dd2017-06-07 23:00:05 +00009490 // Ignore access control bits, we don't need them for redeclaration checking.
9491 Specialization = cast<FunctionDecl>(*Result);
9492 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009493
Alexey Bataev73983912014-11-06 10:10:50 +00009494 // C++11 [except.spec]p4
9495 // In an explicit instantiation an exception-specification may be specified,
9496 // but is not required.
9497 // If an exception-specification is specified in an explicit instantiation
9498 // directive, it shall be compatible with the exception-specifications of
9499 // other declarations of that function.
9500 if (auto *FPT = R->getAs<FunctionProtoType>())
9501 if (FPT->hasExceptionSpec()) {
9502 unsigned DiagID =
9503 diag::err_mismatched_exception_spec_explicit_instantiation;
9504 if (getLangOpts().MicrosoftExt)
9505 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9506 bool Result = CheckEquivalentExceptionSpec(
9507 PDiag(DiagID) << Specialization->getType(),
9508 PDiag(diag::note_explicit_instantiation_here),
9509 Specialization->getType()->getAs<FunctionProtoType>(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009510 Specialization->getLocation(), FPT, D.getBeginLoc());
Alexey Bataev73983912014-11-06 10:10:50 +00009511 // In Microsoft mode, mismatching exception specifications just cause a
9512 // warning.
9513 if (!getLangOpts().MicrosoftExt && Result)
9514 return true;
9515 }
9516
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009517 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009518 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009519 diag::err_explicit_instantiation_member_function_not_instantiated)
9520 << Specialization
9521 << (Specialization->getTemplateSpecializationKind() ==
9522 TSK_ExplicitSpecialization);
9523 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9524 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009525 }
9526
Douglas Gregorec9fd132012-01-14 16:38:05 +00009527 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00009528 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9529 PrevDecl = Specialization;
9530
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009531 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00009532 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009533 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009534 PrevDecl,
9535 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009536 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009537 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009538 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009539
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009540 // FIXME: We may still want to build some representation of this
9541 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00009542 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00009543 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009544 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00009545
Richard Smith0d923af2019-04-26 01:51:07 +00009546 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
9547 // functions
9548 // valarray<size_t>::valarray(size_t) and
9549 // valarray<size_t>::~valarray()
9550 // that it declared to have internal linkage with the internal_linkage
9551 // attribute. Ignore the explicit instantiation declaration in this case.
9552 if (Specialization->hasAttr<InternalLinkageAttr>() &&
9553 TSK == TSK_ExplicitInstantiationDeclaration) {
9554 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
9555 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
9556 RD->isInStdNamespace())
9557 return (Decl*) nullptr;
9558 }
9559
Erich Keanec480f302018-07-12 21:09:05 +00009560 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009561
Hans Wennborgb8304a62017-11-29 23:44:11 +00009562 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9563 // instantiation declarations.
9564 if (TSK == TSK_ExplicitInstantiationDefinition &&
9565 Specialization->hasAttr<DLLImportAttr>() &&
9566 Context.getTargetInfo().getCXXABI().isMicrosoft())
9567 TSK = TSK_ExplicitInstantiationDeclaration;
9568
9569 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9570
Richard Smitheb36ddf2014-04-24 22:45:46 +00009571 if (Specialization->isDefined()) {
9572 // Let the ASTConsumer know that this function has been explicitly
9573 // instantiated now, and its linkage might have changed.
9574 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9575 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00009576 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009577
Douglas Gregore47f5a72009-10-14 23:41:34 +00009578 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009579 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009580 // or a static data member of a class template specialization, the name of
9581 // the class template specialization in the qualified-id for the member
9582 // name shall be a simple-template-id.
9583 //
9584 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009585 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Faisal Vali2ab8c152017-12-30 04:15:27 +00009586 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009587 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00009588 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009589 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009590 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009591 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009592
Richard Smith0d923af2019-04-26 01:51:07 +00009593 CheckExplicitInstantiation(
9594 *this,
9595 FunTmpl ? (NamedDecl *)FunTmpl
9596 : Specialization->getInstantiatedFromMemberFunction(),
9597 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009598
Douglas Gregor450f00842009-09-25 18:43:00 +00009599 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00009600 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009601}
9602
John McCallfaf5fb42010-08-26 23:41:50 +00009603TypeResult
Faisal Vali090da2d2018-01-01 18:23:28 +00009604Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
John McCall7f41d982009-09-11 04:59:25 +00009605 const CXXScopeSpec &SS, IdentifierInfo *Name,
9606 SourceLocation TagLoc, SourceLocation NameLoc) {
9607 // This has to hold, because SS is expected to be defined.
9608 assert(Name && "Expected a name in a dependent tag");
9609
Aaron Ballman4a979672014-01-03 13:56:08 +00009610 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009611 if (!NNS)
9612 return true;
9613
Abramo Bagnara6150c882010-05-11 21:36:43 +00009614 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009615
Douglas Gregorba41d012010-04-24 16:38:41 +00009616 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9617 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009618 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009619 return true;
9620 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009621
Douglas Gregore7c20652011-03-02 00:47:37 +00009622 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009623 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009624 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009625
Douglas Gregore7c20652011-03-02 00:47:37 +00009626 // Create type-source location information for this type.
9627 TypeLocBuilder TLB;
9628 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009629 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009630 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9631 TL.setNameLoc(NameLoc);
9632 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009633}
9634
John McCallfaf5fb42010-08-26 23:41:50 +00009635TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009636Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9637 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009638 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009639 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009640 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009641
Richard Smith0bf8a4922011-10-18 20:49:44 +00009642 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9643 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009644 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009645 diag::warn_cxx98_compat_typename_outside_of_template :
9646 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009647 << FixItHint::CreateRemoval(TypenameLoc);
9648
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009649 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009650 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9651 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009652 if (T.isNull())
9653 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009654
9655 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9656 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009657 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009658 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009659 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009660 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009661 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009662 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009663 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009664 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009665 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009667
John McCallba7bf592010-08-24 05:47:05 +00009668 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009669}
9670
John McCallfaf5fb42010-08-26 23:41:50 +00009671TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009672Sema::ActOnTypenameType(Scope *S,
9673 SourceLocation TypenameLoc,
9674 const CXXScopeSpec &SS,
9675 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009676 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009677 IdentifierInfo *TemplateII,
9678 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009679 SourceLocation LAngleLoc,
9680 ASTTemplateArgsPtr TemplateArgsIn,
9681 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009682 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9683 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009684 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009685 diag::warn_cxx98_compat_typename_outside_of_template :
9686 diag::ext_typename_outside_of_template)
9687 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009688
Richard Smith74f02342017-01-19 21:00:13 +00009689 // Strangely, non-type results are not ignored by this lookup, so the
9690 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009691 if (TypenameLoc.isValid()) {
9692 auto *LookupRD =
9693 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9694 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9695 Diag(TemplateIILoc,
9696 diag::ext_out_of_line_qualified_id_type_names_constructor)
9697 << TemplateII << 0 /*injected-class-name used as template name*/
9698 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9699 }
Richard Smith74f02342017-01-19 21:00:13 +00009700 }
9701
Douglas Gregorb09518c2011-02-27 22:46:49 +00009702 // Translate the parser's template argument list in our AST format.
9703 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9704 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009705
Douglas Gregorb09518c2011-02-27 22:46:49 +00009706 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009707 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9708 // Construct a dependent template specialization type.
9709 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009710 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009711 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9712 DTN->getQualifier(),
9713 DTN->getIdentifier(),
9714 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009715
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009716 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009717 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009718 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009719 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009720 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9721 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009722 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009723 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009724 SpecTL.setLAngleLoc(LAngleLoc);
9725 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009726 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9727 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009728 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009729 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009730
Richard Smith74f02342017-01-19 21:00:13 +00009731 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009732 if (T.isNull())
9733 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009734
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009735 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009736 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009737 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009738 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009739 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009740 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009741 SpecTL.setLAngleLoc(LAngleLoc);
9742 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009743 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9744 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009745
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009746 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9747 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009748 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009749 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009750
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009751 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9752 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009753}
9754
Douglas Gregorb09518c2011-02-27 22:46:49 +00009755
Richard Smith6f8d2c62012-05-09 05:17:00 +00009756/// Determine whether this failed name lookup should be treated as being
9757/// disabled by a usage of std::enable_if.
9758static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009759 SourceRange &CondRange, Expr *&Cond) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009760 // We must be looking for a ::type...
9761 if (!II.isStr("type"))
9762 return false;
9763
9764 // ... within an explicitly-written template specialization...
9765 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9766 return false;
9767 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009768 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9769 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9770 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009771 return false;
George Burgess IV00f70bd2018-03-01 05:43:23 +00009772 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009773
9774 // ... which names a complete class template declaration...
9775 const TemplateDecl *EnableIfDecl =
9776 EnableIfTST->getTemplateName().getAsTemplateDecl();
9777 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9778 return false;
9779
9780 // ... called "enable_if".
9781 const IdentifierInfo *EnableIfII =
9782 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9783 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9784 return false;
9785
9786 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009787 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009788
9789 // Dig out the condition.
9790 Cond = nullptr;
9791 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9792 != TemplateArgument::Expression)
9793 return true;
9794
9795 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9796
9797 // Ignore Boolean literals; they add no value.
9798 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9799 Cond = nullptr;
9800
Richard Smith6f8d2c62012-05-09 05:17:00 +00009801 return true;
9802}
9803
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009804/// Build the type that describes a C++ typename specifier,
Douglas Gregor333489b2009-03-27 23:10:48 +00009805/// e.g., "typename T::type".
9806QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009807Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009808 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009809 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009810 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009811 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009812 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009813 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009814
John McCall0b66eb32010-05-01 00:40:08 +00009815 DeclContext *Ctx = computeDeclContext(SS);
9816 if (!Ctx) {
9817 // If the nested-name-specifier is dependent and couldn't be
9818 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009819 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009820 return Context.getDependentNameType(Keyword,
9821 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009822 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009823 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009824
John McCall0b66eb32010-05-01 00:40:08 +00009825 // If the nested-name-specifier refers to the current instantiation,
9826 // the "typename" keyword itself is superfluous. In C++03, the
9827 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9828 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009829 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009830
John McCall0b66eb32010-05-01 00:40:08 +00009831 if (RequireCompleteDeclContext(SS, Ctx))
9832 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009833
9834 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009835 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009836 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009837 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009838 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009839 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009840 case LookupResult::NotFound: {
9841 // If we're looking up 'type' within a template named 'enable_if', produce
9842 // a more specific diagnostic.
9843 SourceRange CondRange;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009844 Expr *Cond = nullptr;
9845 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9846 // If we have a condition, narrow it down to the specific failed
9847 // condition.
9848 if (Cond) {
9849 Expr *FailedCond;
9850 std::string FailedDescription;
9851 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00009852 findFailedBooleanCondition(Cond);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009853
9854 Diag(FailedCond->getExprLoc(),
9855 diag::err_typename_nested_not_found_requirement)
9856 << FailedDescription
9857 << FailedCond->getSourceRange();
9858 return QualType();
9859 }
9860
Richard Smith6f8d2c62012-05-09 05:17:00 +00009861 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009862 << Ctx << CondRange;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009863 return QualType();
9864 }
9865
Douglas Gregore40876a2009-10-13 21:16:44 +00009866 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009867 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009868 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009869
9870 case LookupResult::FoundUnresolvedValue: {
9871 // We found a using declaration that is a value. Most likely, the using
9872 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009873 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009874 IILoc);
9875 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9876 << Name << Ctx << FullRange;
9877 if (UnresolvedUsingValueDecl *Using
9878 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009879 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009880 Diag(Loc, diag::note_using_value_decl_missing_typename)
9881 << FixItHint::CreateInsertion(Loc, "typename ");
9882 }
9883 }
9884 // Fall through to create a dependent typename type, from which we can recover
9885 // better.
Galina Kistanova3779cb32017-06-07 06:25:05 +00009886 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009887
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009888 case LookupResult::NotFoundInCurrentInstantiation:
9889 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009890 return Context.getDependentNameType(Keyword,
9891 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009892 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009893
9894 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009895 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009896 // C++ [class.qual]p2:
9897 // In a lookup in which function names are not ignored and the
9898 // nested-name-specifier nominates a class C, if the name specified
9899 // after the nested-name-specifier, when looked up in C, is the
9900 // injected-class-name of C [...] then the name is instead considered
9901 // to name the constructor of class C.
9902 //
9903 // Unlike in an elaborated-type-specifier, function names are not ignored
9904 // in typename-specifier lookup. However, they are ignored in all the
9905 // contexts where we form a typename type with no keyword (that is, in
9906 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9907 //
9908 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9909 // ignore functions, but that appears to be an oversight.
9910 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9911 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9912 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9913 FoundRD->isInjectedClassName() &&
9914 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9915 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9916 << &II << 1 << 0 /*'typename' keyword used*/;
9917
Abramo Bagnara6150c882010-05-11 21:36:43 +00009918 // We found a type. Build an ElaboratedType, since the
9919 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009920 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009921 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009922 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009923 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009924 }
9925
Richard Smithee579842017-01-30 20:39:26 +00009926 // C++ [dcl.type.simple]p2:
9927 // A type-specifier of the form
9928 // typename[opt] nested-name-specifier[opt] template-name
9929 // is a placeholder for a deduced class type [...].
Aaron Ballmanc351fba2017-12-04 20:27:34 +00009930 if (getLangOpts().CPlusPlus17) {
Richard Smithee579842017-01-30 20:39:26 +00009931 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9932 return Context.getElaboratedType(
9933 Keyword, QualifierLoc.getNestedNameSpecifier(),
9934 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9935 QualType(), false));
9936 }
9937 }
Richard Smith600b5262017-01-26 20:40:47 +00009938
Douglas Gregor333489b2009-03-27 23:10:48 +00009939 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009940 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009941 break;
9942
9943 case LookupResult::FoundOverloaded:
9944 DiagID = diag::err_typename_nested_not_type;
9945 Referenced = *Result.begin();
9946 break;
9947
John McCall6538c932009-10-10 05:48:19 +00009948 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009949 return QualType();
9950 }
9951
9952 // If we get here, it's because name lookup did not find a
9953 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009954 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009955 IILoc);
9956 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009957 if (Referenced)
9958 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9959 << Name;
9960 return QualType();
9961}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009962
9963namespace {
9964 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009965 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009966 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009967 SourceLocation Loc;
9968 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009969
Douglas Gregor15acfb92009-08-06 16:20:37 +00009970 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009971 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009972
Mike Stump11289f42009-09-09 15:08:12 +00009973 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009974 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009975 DeclarationName Entity)
9976 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009977 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009978
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009979 /// Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009980 /// transformed.
9981 ///
9982 /// For the purposes of type reconstruction, a type has already been
9983 /// transformed if it is NULL or if it is not dependent.
9984 bool AlreadyTransformed(QualType T) {
9985 return T.isNull() || !T->isDependentType();
9986 }
Mike Stump11289f42009-09-09 15:08:12 +00009987
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009988 /// Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009989 /// rebuilt.
9990 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009991
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009992 /// Returns the name of the entity whose type is being rebuilt.
Douglas Gregor15acfb92009-08-06 16:20:37 +00009993 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009994
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009995 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +00009996 /// information is known based on another transformation.
9997 void setBase(SourceLocation Loc, DeclarationName Entity) {
9998 this->Loc = Loc;
9999 this->Entity = Entity;
10000 }
Simon Pilgrim6905d222016-12-30 22:55:33 +000010001
Douglas Gregor0c46b2b2012-02-13 22:00:16 +000010002 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10003 // Lambdas never need to be transformed.
10004 return E;
10005 }
Douglas Gregor15acfb92009-08-06 16:20:37 +000010006 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010007} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +000010008
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010009/// Rebuilds a type within the context of the current instantiation.
Douglas Gregor15acfb92009-08-06 16:20:37 +000010010///
Mike Stump11289f42009-09-09 15:08:12 +000010011/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +000010012/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +000010013/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +000010014/// partial specialization thereof). This routine will rebuild that type now
10015/// that we have entered the declarator's scope, which may produce different
10016/// canonical types, e.g.,
10017///
10018/// \code
10019/// template<typename T>
10020/// struct X {
10021/// typedef T* pointer;
10022/// pointer data();
10023/// };
10024///
10025/// template<typename T>
10026/// typename X<T>::pointer X<T>::data() { ... }
10027/// \endcode
10028///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +000010029/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +000010030/// since we do not know that we can look into X<T> when we parsed the type.
10031/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +000010032/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +000010033/// as the canonical type of T*, allowing the return types of the out-of-line
10034/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +000010035TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
10036 SourceLocation Loc,
10037 DeclarationName Name) {
10038 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +000010039 return T;
Mike Stump11289f42009-09-09 15:08:12 +000010040
Douglas Gregor15acfb92009-08-06 16:20:37 +000010041 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
10042 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +000010043}
Douglas Gregorbe999392009-09-15 16:23:51 +000010044
John McCalldadc5752010-08-24 06:29:42 +000010045ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +000010046 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
10047 DeclarationName());
10048 return Rebuilder.TransformExpr(E);
10049}
10050
John McCall99b2fe52010-04-29 23:50:39 +000010051bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +000010052 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +000010053 return true;
John McCall2408e322010-04-27 00:57:59 +000010054
Douglas Gregor10176412011-02-25 16:07:42 +000010055 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +000010056 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
10057 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +000010058 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +000010059 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +000010060 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +000010061 return true;
John McCall99b2fe52010-04-29 23:50:39 +000010062
Douglas Gregor10176412011-02-25 16:07:42 +000010063 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +000010064 return false;
John McCall2408e322010-04-27 00:57:59 +000010065}
10066
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010067/// Rebuild the template parameters now that we know we're in a current
Douglas Gregor041b0842011-10-14 15:31:12 +000010068/// instantiation.
10069bool Sema::RebuildTemplateParamsInCurrentInstantiation(
10070 TemplateParameterList *Params) {
10071 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10072 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +000010073
Douglas Gregor041b0842011-10-14 15:31:12 +000010074 // There is nothing to rebuild in a type parameter.
10075 if (isa<TemplateTypeParmDecl>(Param))
10076 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +000010077
Douglas Gregor041b0842011-10-14 15:31:12 +000010078 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +000010079 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +000010080 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
10081 if (RebuildTemplateParamsInCurrentInstantiation(
10082 TTP->getTemplateParameters()))
10083 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +000010084
Douglas Gregor041b0842011-10-14 15:31:12 +000010085 continue;
10086 }
Simon Pilgrim6905d222016-12-30 22:55:33 +000010087
Douglas Gregor041b0842011-10-14 15:31:12 +000010088 // Rebuild the type of a non-type template parameter.
10089 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +000010090 TypeSourceInfo *NewTSI
10091 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
10092 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +000010093 NTTP->getDeclName());
10094 if (!NewTSI)
10095 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +000010096
Erik Pilkington9f9462a2018-08-07 22:59:02 +000010097 if (NewTSI->getType()->isUndeducedType()) {
10098 // C++17 [temp.dep.expr]p3:
10099 // An id-expression is type-dependent if it contains
10100 // - an identifier associated by name lookup with a non-type
10101 // template-parameter declared with a type that contains a
10102 // placeholder type (7.1.7.4),
10103 NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
10104 }
10105
Douglas Gregor041b0842011-10-14 15:31:12 +000010106 if (NewTSI != NTTP->getTypeSourceInfo()) {
10107 NTTP->setTypeSourceInfo(NewTSI);
10108 NTTP->setType(NewTSI->getType());
10109 }
10110 }
Simon Pilgrim6905d222016-12-30 22:55:33 +000010111
Douglas Gregor041b0842011-10-14 15:31:12 +000010112 return false;
10113}
10114
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010115/// Produces a formatted string that describes the binding of
Douglas Gregorbe999392009-09-15 16:23:51 +000010116/// template parameters to template arguments.
10117std::string
10118Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10119 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010120 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +000010121}
10122
10123std::string
10124Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10125 const TemplateArgument *Args,
10126 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000010127 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +000010128 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +000010129
Douglas Gregore62e6a02009-11-11 19:13:48 +000010130 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +000010131 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010132
Douglas Gregorbe999392009-09-15 16:23:51 +000010133 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +000010134 if (I >= NumArgs)
10135 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010136
Douglas Gregorbe999392009-09-15 16:23:51 +000010137 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +000010138 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +000010139 else
Douglas Gregor0192c232010-12-20 16:52:59 +000010140 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010141
Douglas Gregorbe999392009-09-15 16:23:51 +000010142 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +000010143 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +000010144 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +000010145 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +000010146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010147
Douglas Gregor0192c232010-12-20 16:52:59 +000010148 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +000010149 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +000010150 }
Douglas Gregor0192c232010-12-20 16:52:59 +000010151
10152 Out << ']';
10153 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +000010154}
Francois Pichet1c229c02011-04-22 22:18:13 +000010155
Richard Smithe40f2ba2013-08-07 21:41:30 +000010156void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
10157 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +000010158 if (!FD)
10159 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +000010160
Justin Lebar28f09c52016-10-10 16:26:08 +000010161 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +000010162
10163 // Take tokens to avoid allocations
10164 LPT->Toks.swap(Toks);
10165 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +000010166 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +000010167
10168 FD->setLateTemplateParsed(true);
10169}
10170
10171void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
10172 if (!FD)
10173 return;
10174 FD->setLateTemplateParsed(false);
10175}
Francois Pichet1c229c02011-04-22 22:18:13 +000010176
10177bool Sema::IsInsideALocalClassWithinATemplateFunction() {
10178 DeclContext *DC = CurContext;
10179
10180 while (DC) {
10181 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10182 const FunctionDecl *FD = RD->isLocalClass();
10183 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10184 } else if (DC->isTranslationUnit() || DC->isNamespace())
10185 return false;
10186
10187 DC = DC->getParent();
10188 }
10189 return false;
10190}
Richard Smith6739a102016-05-05 00:56:12 +000010191
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010192namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010193/// Walk the path from which a declaration was instantiated, and check
Richard Smith6739a102016-05-05 00:56:12 +000010194/// that every explicit specialization along that path is visible. This enforces
10195/// C++ [temp.expl.spec]/6:
10196///
10197/// If a template, a member template or a member of a class template is
10198/// explicitly specialized then that specialization shall be declared before
10199/// the first use of that specialization that would cause an implicit
10200/// instantiation to take place, in every translation unit in which such a
10201/// use occurs; no diagnostic is required.
10202///
10203/// and also C++ [temp.class.spec]/1:
10204///
10205/// A partial specialization shall be declared before the first use of a
10206/// class template specialization that would make use of the partial
10207/// specialization as the result of an implicit or explicit instantiation
10208/// in every translation unit in which such a use occurs; no diagnostic is
10209/// required.
10210class ExplicitSpecializationVisibilityChecker {
10211 Sema &S;
10212 SourceLocation Loc;
10213 llvm::SmallVector<Module *, 8> Modules;
10214
10215public:
10216 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10217 : S(S), Loc(Loc) {}
10218
10219 void check(NamedDecl *ND) {
10220 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10221 return checkImpl(FD);
10222 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10223 return checkImpl(RD);
10224 if (auto *VD = dyn_cast<VarDecl>(ND))
10225 return checkImpl(VD);
10226 if (auto *ED = dyn_cast<EnumDecl>(ND))
10227 return checkImpl(ED);
10228 }
10229
10230private:
10231 void diagnose(NamedDecl *D, bool IsPartialSpec) {
10232 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10233 : Sema::MissingImportKind::ExplicitSpecialization;
10234 const bool Recover = true;
10235
10236 // If we got a custom set of modules (because only a subset of the
10237 // declarations are interesting), use them, otherwise let
10238 // diagnoseMissingImport intelligently pick some.
10239 if (Modules.empty())
10240 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10241 else
10242 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10243 }
10244
10245 // Check a specific declaration. There are three problematic cases:
10246 //
10247 // 1) The declaration is an explicit specialization of a template
10248 // specialization.
10249 // 2) The declaration is an explicit specialization of a member of an
10250 // templated class.
10251 // 3) The declaration is an instantiation of a template, and that template
10252 // is an explicit specialization of a member of a templated class.
10253 //
10254 // We don't need to go any deeper than that, as the instantiation of the
10255 // surrounding class / etc is not triggered by whatever triggered this
10256 // instantiation, and thus should be checked elsewhere.
10257 template<typename SpecDecl>
10258 void checkImpl(SpecDecl *Spec) {
10259 bool IsHiddenExplicitSpecialization = false;
10260 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10261 IsHiddenExplicitSpecialization =
10262 Spec->getMemberSpecializationInfo()
10263 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
Richard Smith54f04402017-05-18 02:29:20 +000010264 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
Richard Smith6739a102016-05-05 00:56:12 +000010265 } else {
10266 checkInstantiated(Spec);
10267 }
10268
10269 if (IsHiddenExplicitSpecialization)
10270 diagnose(Spec->getMostRecentDecl(), false);
10271 }
10272
10273 void checkInstantiated(FunctionDecl *FD) {
10274 if (auto *TD = FD->getPrimaryTemplate())
10275 checkTemplate(TD);
10276 }
10277
10278 void checkInstantiated(CXXRecordDecl *RD) {
10279 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10280 if (!SD)
10281 return;
10282
10283 auto From = SD->getSpecializedTemplateOrPartial();
10284 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10285 checkTemplate(TD);
10286 else if (auto *TD =
10287 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10288 if (!S.hasVisibleDeclaration(TD))
10289 diagnose(TD, true);
10290 checkTemplate(TD);
10291 }
10292 }
10293
10294 void checkInstantiated(VarDecl *RD) {
10295 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10296 if (!SD)
10297 return;
10298
10299 auto From = SD->getSpecializedTemplateOrPartial();
10300 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10301 checkTemplate(TD);
10302 else if (auto *TD =
10303 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10304 if (!S.hasVisibleDeclaration(TD))
10305 diagnose(TD, true);
10306 checkTemplate(TD);
10307 }
10308 }
10309
10310 void checkInstantiated(EnumDecl *FD) {}
10311
10312 template<typename TemplDecl>
10313 void checkTemplate(TemplDecl *TD) {
10314 if (TD->isMemberSpecialization()) {
10315 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10316 diagnose(TD->getMostRecentDecl(), false);
10317 }
10318 }
10319};
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010320} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +000010321
10322void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10323 if (!getLangOpts().Modules)
10324 return;
10325
10326 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10327}
10328
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010329/// Check whether a template partial specialization that we've discovered
Richard Smith6739a102016-05-05 00:56:12 +000010330/// is hidden, and produce suitable diagnostics if so.
10331void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10332 NamedDecl *Spec) {
10333 llvm::SmallVector<Module *, 8> Modules;
10334 if (!hasVisibleDeclaration(Spec, &Modules))
10335 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10336 MissingImportKind::PartialSpecialization,
10337 /*Recover*/true);
10338}