blob: f31f0d4957ad3997b8ab3f9a6239cb8e9edf10a0 [file] [log] [blame]
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +000011
Douglas Gregor15acfb92009-08-06 16:20:37 +000012#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000013#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000015#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000019#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000020#include "clang/AST/TypeVisitor.h"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000021#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedTemplate.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000032#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000034#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000035
Eric Fiselier6ad68552016-07-01 01:24:09 +000036#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000037using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000039
John McCall9b72f892010-11-10 02:40:36 +000040// Exported for use by Parser.
41SourceRange
42clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 unsigned N) {
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46}
47
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000048namespace clang {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000049/// [temp.constr.decl]p2: A template's associated constraints are
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000050/// defined as a single constraint-expression derived from the introduced
51/// constraint-expressions [ ... ].
52///
53/// \param Params The template parameter list and optional requires-clause.
54///
55/// \param FD The underlying templated function declaration for a function
56/// template.
57static Expr *formAssociatedConstraints(TemplateParameterList *Params,
58 FunctionDecl *FD);
59}
60
61static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
62 FunctionDecl *FD) {
63 // FIXME: Concepts: collect additional introduced constraint-expressions
64 assert(!FD && "Cannot collect constraints from function declaration yet.");
65 return Params->getRequiresClause();
66}
67
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000068/// Determine whether the declaration found is acceptable as the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +000069/// of a template and, if so, return that template declaration. Otherwise,
70/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000071static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000072 NamedDecl *Orig,
73 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000074 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000076 if (isa<TemplateDecl>(D)) {
77 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000078 return nullptr;
79
John McCalle9cccd82010-06-16 08:42:20 +000080 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000081 }
Mike Stump11289f42009-09-09 15:08:12 +000082
Douglas Gregorb7bfe792009-09-02 22:59:36 +000083 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
84 // C++ [temp.local]p1:
85 // Like normal (non-template) classes, class templates have an
86 // injected-class-name (Clause 9). The injected-class-name
87 // can be used with or without a template-argument-list. When
88 // it is used without a template-argument-list, it is
89 // equivalent to the injected-class-name followed by the
90 // template-parameters of the class template enclosed in
91 // <>. When it is used with a template-argument-list, it
92 // refers to the specified class template specialization,
93 // which could be the current specialization or another
94 // specialization.
95 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000096 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000097 if (Record->getDescribedClassTemplate())
98 return Record->getDescribedClassTemplate();
99
100 if (ClassTemplateSpecializationDecl *Spec
101 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
102 return Spec->getSpecializedTemplate();
103 }
Mike Stump11289f42009-09-09 15:08:12 +0000104
Craig Topperc3ec1492014-05-26 06:22:03 +0000105 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106 }
Mike Stump11289f42009-09-09 15:08:12 +0000107
Richard Smithcbebd622018-05-14 20:52:48 +0000108 // 'using Dependent::foo;' can resolve to a template name.
109 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
110 // injected-class-name).
111 if (isa<UnresolvedUsingValueDecl>(D))
112 return D;
113
Craig Topperc3ec1492014-05-26 06:22:03 +0000114 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000115}
116
Simon Pilgrim6905d222016-12-30 22:55:33 +0000117void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000118 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000119 // The set of class templates we've already seen.
120 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +0000121 LookupResult::Filter filter = R.makeFilter();
122 while (filter.hasNext()) {
123 NamedDecl *Orig = filter.next();
Simon Pilgrim6905d222016-12-30 22:55:33 +0000124 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000125 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +0000126 if (!Repl)
127 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000128 else if (Repl != Orig) {
129
130 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000131 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000132 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000133 // one base class). If all of the injected-class-names that are found
134 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000135 // is used as a template-name, the reference refers to the class
136 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000137 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000138 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000139 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000140 filter.erase();
141 continue;
142 }
John McCallbd8062d2010-08-13 07:02:08 +0000143
144 // FIXME: we promote access to public here as a workaround to
145 // the fact that LookupResult doesn't let us remember that we
146 // found this template through a particular injected class name,
147 // which means we end up doing nasty things to the invariants.
148 // Pretending that access is public is *much* safer.
149 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000150 }
John McCalle66edc12009-11-24 19:00:30 +0000151 }
152 filter.done();
153}
154
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000155bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
156 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000157 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000158 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000159 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +0000160
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000161 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000162}
163
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000164TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000165 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000166 bool hasTemplateKeyword,
Richard Smithc08b6932018-04-27 02:00:13 +0000167 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000168 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000169 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000170 TemplateTy &TemplateResult,
171 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000172 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000173
Douglas Gregor3cf81312009-11-03 23:16:33 +0000174 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000175 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176
Douglas Gregor3cf81312009-11-03 23:16:33 +0000177 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000178 case UnqualifiedIdKind::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000179 TName = DeclarationName(Name.Identifier);
180 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000181
Faisal Vali2ab8c152017-12-30 04:15:27 +0000182 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000183 TName = Context.DeclarationNames.getCXXOperatorName(
184 Name.OperatorFunctionId.Operator);
185 break;
186
Faisal Vali2ab8c152017-12-30 04:15:27 +0000187 case UnqualifiedIdKind::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000188 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
189 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000190
Douglas Gregor3cf81312009-11-03 23:16:33 +0000191 default:
192 return TNK_Non_template;
193 }
Mike Stump11289f42009-09-09 15:08:12 +0000194
John McCallba7bf592010-08-24 05:47:05 +0000195 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000196
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000197 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000198 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
199 MemberOfUnknownSpecialization))
200 return TNK_Non_template;
John McCallfb3f9ba2010-08-28 20:17:00 +0000201 if (R.empty()) return TNK_Non_template;
202 if (R.isAmbiguous()) {
203 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000204 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000205
206 // FIXME: we might have ambiguous templates, in which case we
207 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000208 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000209 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000210
John McCalld28ae272009-12-02 08:04:21 +0000211 TemplateName Template;
212 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000213
John McCalld28ae272009-12-02 08:04:21 +0000214 unsigned ResultCount = R.end() - R.begin();
215 if (ResultCount > 1) {
216 // We assume that we'll preserve the qualifier from a function
217 // template name in other ways.
218 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
219 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000220
221 // We'll do this lookup again later.
222 R.suppressDiagnostics();
Richard Smithcbebd622018-05-14 20:52:48 +0000223 } else if (isa<UnresolvedUsingValueDecl>((*R.begin())->getUnderlyingDecl())) {
224 // We don't yet know whether this is a template-name or not.
225 MemberOfUnknownSpecialization = true;
226 return TNK_Non_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000227 } else {
John McCalld28ae272009-12-02 08:04:21 +0000228 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
229
230 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000231 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000232 Template = Context.getQualifiedTemplateName(Qualifier,
233 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000234 } else {
235 Template = TemplateName(TD);
236 }
237
John McCalldcc71402010-08-13 02:23:42 +0000238 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000239 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000240
241 // We'll do this lookup again later.
242 R.suppressDiagnostics();
243 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000244 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000245 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
Faisal Valia534f072018-04-26 00:42:40 +0000246 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000247 TemplateKind =
Faisal Valia534f072018-04-26 00:42:40 +0000248 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000249 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000250 }
Mike Stump11289f42009-09-09 15:08:12 +0000251
John McCalld28ae272009-12-02 08:04:21 +0000252 TemplateResult = TemplateTy::make(Template);
253 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000254}
255
Richard Smith278890f2017-02-10 20:39:58 +0000256bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
257 SourceLocation NameLoc,
258 ParsedTemplateTy *Template) {
259 CXXScopeSpec SS;
260 bool MemberOfUnknownSpecialization = false;
261
262 // We could use redeclaration lookup here, but we don't need to: the
263 // syntactic form of a deduction guide is enough to identify it even
264 // if we can't look up the template name at all.
265 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000266 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
267 /*EnteringContext*/ false,
268 MemberOfUnknownSpecialization))
269 return false;
Richard Smith278890f2017-02-10 20:39:58 +0000270
271 if (R.empty()) return false;
272 if (R.isAmbiguous()) {
273 // FIXME: Diagnose an ambiguity if we find at least one template.
274 R.suppressDiagnostics();
275 return false;
276 }
277
278 // We only treat template-names that name type templates as valid deduction
279 // guide names.
280 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
281 if (!TD || !getAsTypeTemplateDecl(TD))
282 return false;
283
284 if (Template)
285 *Template = TemplateTy::make(TemplateName(TD));
286 return true;
287}
288
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000289bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000290 SourceLocation IILoc,
291 Scope *S,
292 const CXXScopeSpec *SS,
293 TemplateTy &SuggestedTemplate,
294 TemplateNameKind &SuggestedKind) {
295 // We can't recover unless there's a dependent scope specifier preceding the
296 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000297 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000298 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
299 computeDeclContext(*SS))
300 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000301
Douglas Gregor18473f32010-01-12 21:28:44 +0000302 // The code is missing a 'template' keyword prior to the dependent template
303 // name.
304 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
305 Diag(IILoc, diag::err_template_kw_missing)
306 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000307 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000308 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000309 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
310 SuggestedKind = TNK_Dependent_template_name;
311 return true;
312}
313
Richard Smith79810042018-05-11 02:43:08 +0000314bool Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000315 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000316 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000317 bool EnteringContext,
Richard Smith79810042018-05-11 02:43:08 +0000318 bool &MemberOfUnknownSpecialization,
319 SourceLocation TemplateKWLoc) {
John McCalle66edc12009-11-24 19:00:30 +0000320 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000321 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000322 DeclContext *LookupCtx = nullptr;
Richard Smith79810042018-05-11 02:43:08 +0000323 bool IsDependent = false;
John McCalle66edc12009-11-24 19:00:30 +0000324 if (!ObjectType.isNull()) {
325 // This nested-name-specifier occurs in a member access expression, e.g.,
326 // x->B::f, and we are looking into the type of the object.
327 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
328 LookupCtx = computeDeclContext(ObjectType);
Richard Smith79810042018-05-11 02:43:08 +0000329 IsDependent = !LookupCtx;
330 assert((IsDependent || !ObjectType->isIncompleteType() ||
Richard Smith5ed79562013-06-07 20:03:01 +0000331 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000332 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000333
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000334 // Template names cannot appear inside an Objective-C class or object type.
335 if (ObjectType->isObjCObjectOrInterfaceType()) {
336 Found.clear();
Richard Smith79810042018-05-11 02:43:08 +0000337 return false;
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000338 }
John McCalle66edc12009-11-24 19:00:30 +0000339 } else if (SS.isSet()) {
340 // This nested-name-specifier occurs after another nested-name-specifier,
341 // so long into the context associated with the prior nested-name-specifier.
342 LookupCtx = computeDeclContext(SS, EnteringContext);
Richard Smith79810042018-05-11 02:43:08 +0000343 IsDependent = !LookupCtx;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344
John McCalle66edc12009-11-24 19:00:30 +0000345 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000346 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
Richard Smith79810042018-05-11 02:43:08 +0000347 return true;
John McCalle66edc12009-11-24 19:00:30 +0000348 }
349
350 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000351 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000352 if (LookupCtx) {
353 // Perform "qualified" name lookup into the declaration context we
354 // computed, which is either the type of the base of a member access
355 // expression or the declaration context associated with a prior
356 // nested-name-specifier.
357 LookupQualifiedName(Found, LookupCtx);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000358
Richard Smith79810042018-05-11 02:43:08 +0000359 // FIXME: The C++ standard does not clearly specify what happens in the
360 // case where the object type is dependent, and implementations vary. In
361 // Clang, we treat a name after a . or -> as a template-name if lookup
362 // finds a non-dependent member or member of the current instantiation that
363 // is a type template, or finds no such members and lookup in the context
364 // of the postfix-expression finds a type template. In the latter case, the
365 // name is nonetheless dependent, and we may resolve it to a member of an
366 // unknown specialization when we come to instantiate the template.
367 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
John McCalle66edc12009-11-24 19:00:30 +0000368 }
369
Richard Smith79810042018-05-11 02:43:08 +0000370 if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
371 // C++ [basic.lookup.classref]p1:
372 // In a class member access expression (5.2.5), if the . or -> token is
373 // immediately followed by an identifier followed by a <, the
374 // identifier must be looked up to determine whether the < is the
375 // beginning of a template argument list (14.2) or a less-than operator.
376 // The identifier is first looked up in the class of the object
377 // expression. If the identifier is not found, it is then looked up in
378 // the context of the entire postfix-expression and shall name a class
379 // template.
380 if (S)
381 LookupName(Found, S);
382
383 if (!ObjectType.isNull()) {
384 // FIXME: We should filter out all non-type templates here, particularly
385 // variable templates and concepts. But the exclusion of alias templates
386 // and template template parameters is a wording defect.
387 AllowFunctionTemplatesInLookup = false;
388 ObjectTypeSearchedInScope = true;
389 }
390
391 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
392 }
393
394 if (Found.empty() && !IsDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000395 // If we did not find any names, attempt to correct any typos.
396 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000397 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000398 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000399 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
400 FilterCCC->WantTypeSpecifiers = false;
401 FilterCCC->WantExpressionKeywords = false;
402 FilterCCC->WantRemainingKeywords = false;
403 FilterCCC->WantCXXNamedCasts = true;
404 if (TypoCorrection Corrected = CorrectTypo(
405 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
406 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000407 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000408 if (auto *ND = Corrected.getFoundDecl())
409 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000410 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000411 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000412 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000413 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
414 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000415 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000416 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
417 << Name << LookupCtx << DroppedSpecifier
418 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000419 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000420 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000421 }
John McCalle9cccd82010-06-16 08:42:20 +0000422 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000423 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000424 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000425 }
426 }
427
Richard Smith79810042018-05-11 02:43:08 +0000428 NamedDecl *ExampleLookupResult =
429 Found.empty() ? nullptr : Found.getRepresentativeDecl();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000430 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000431 if (Found.empty()) {
Richard Smith79810042018-05-11 02:43:08 +0000432 if (IsDependent) {
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000433 MemberOfUnknownSpecialization = true;
Richard Smith79810042018-05-11 02:43:08 +0000434 return false;
435 }
436
437 // If a 'template' keyword was used, a lookup that finds only non-template
438 // names is an error.
439 if (ExampleLookupResult && TemplateKWLoc.isValid()) {
440 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
441 << Found.getLookupName() << SS.getRange();
Richard Smithcbebd622018-05-14 20:52:48 +0000442 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
Richard Smith79810042018-05-11 02:43:08 +0000443 diag::note_template_kw_refers_to_non_template)
444 << Found.getLookupName();
445 return true;
446 }
447
448 return false;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000449 }
John McCalle66edc12009-11-24 19:00:30 +0000450
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000451 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000452 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000453 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000454 // [...] If the lookup in the class of the object expression finds a
455 // template, the name is also looked up in the context of the entire
456 // postfix-expression and [...]
457 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000458 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000459 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
460 LookupOrdinaryName);
461 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000462 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000463
John McCalle66edc12009-11-24 19:00:30 +0000464 if (FoundOuter.empty()) {
465 // - if the name is not found, the name found in the class of the
466 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000467 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
468 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000469 // - if the name is found in the context of the entire
470 // postfix-expression and does not name a class template, the name
471 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000472 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000473 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000474 // - if the name found is a class template, it must refer to the same
475 // entity as the one found in the class of the object expression,
476 // otherwise the program is ill-formed.
477 if (!Found.isSingleResult() ||
478 Found.getFoundDecl()->getCanonicalDecl()
479 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000480 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000481 diag::ext_nested_name_member_ref_lookup_ambiguous)
482 << Found.getLookupName()
483 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000484 Diag(Found.getRepresentativeDecl()->getLocation(),
485 diag::note_ambig_member_ref_object_type)
486 << ObjectType;
487 Diag(FoundOuter.getFoundDecl()->getLocation(),
488 diag::note_ambig_member_ref_scope);
489
490 // Recover by taking the template that we found in the object
491 // expression's type.
492 }
493 }
494 }
Richard Smith79810042018-05-11 02:43:08 +0000495
496 return false;
John McCalle66edc12009-11-24 19:00:30 +0000497}
498
Richard Smith42bc73a2017-05-10 02:30:28 +0000499void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
500 SourceLocation Less,
501 SourceLocation Greater) {
502 if (TemplateName.isInvalid())
503 return;
504
505 DeclarationNameInfo NameInfo;
506 CXXScopeSpec SS;
507 LookupNameKind LookupKind;
508
509 DeclContext *LookupCtx = nullptr;
510 NamedDecl *Found = nullptr;
Richard Smithbf5bcf22018-06-26 23:20:26 +0000511 bool MissingTemplateKeyword = false;
Richard Smith42bc73a2017-05-10 02:30:28 +0000512
513 // Figure out what name we looked up.
Richard Smithbf5bcf22018-06-26 23:20:26 +0000514 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
515 NameInfo = DRE->getNameInfo();
516 SS.Adopt(DRE->getQualifierLoc());
517 LookupKind = LookupOrdinaryName;
518 Found = DRE->getFoundDecl();
519 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000520 NameInfo = ME->getMemberNameInfo();
521 SS.Adopt(ME->getQualifierLoc());
522 LookupKind = LookupMemberName;
523 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
524 Found = ME->getMemberDecl();
Richard Smithbf5bcf22018-06-26 23:20:26 +0000525 } else if (auto *DSDRE =
526 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
527 NameInfo = DSDRE->getNameInfo();
528 SS.Adopt(DSDRE->getQualifierLoc());
529 MissingTemplateKeyword = true;
530 } else if (auto *DSME =
531 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
532 NameInfo = DSME->getMemberNameInfo();
533 SS.Adopt(DSME->getQualifierLoc());
534 MissingTemplateKeyword = true;
Richard Smith42bc73a2017-05-10 02:30:28 +0000535 } else {
Richard Smithbf5bcf22018-06-26 23:20:26 +0000536 llvm_unreachable("unexpected kind of potential template name");
537 }
538
539 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
540 // was missing.
541 if (MissingTemplateKeyword) {
542 Diag(NameInfo.getLocStart(), diag::err_template_kw_missing)
543 << "" << NameInfo.getName().getAsString()
544 << SourceRange(Less, Greater);
545 return;
Richard Smith42bc73a2017-05-10 02:30:28 +0000546 }
547
548 // Try to correct the name by looking for templates and C++ named casts.
549 struct TemplateCandidateFilter : CorrectionCandidateCallback {
550 TemplateCandidateFilter() {
551 WantTypeSpecifiers = false;
552 WantExpressionKeywords = false;
553 WantRemainingKeywords = false;
554 WantCXXNamedCasts = true;
555 };
556 bool ValidateCandidate(const TypoCorrection &Candidate) override {
557 if (auto *ND = Candidate.getCorrectionDecl())
558 return isAcceptableTemplateName(ND->getASTContext(), ND, true);
559 return Candidate.isKeyword();
560 }
561 };
562
563 DeclarationName Name = NameInfo.getName();
564 if (TypoCorrection Corrected =
565 CorrectTypo(NameInfo, LookupKind, S, &SS,
566 llvm::make_unique<TemplateCandidateFilter>(),
567 CTK_ErrorRecovery, LookupCtx)) {
568 auto *ND = Corrected.getFoundDecl();
569 if (ND)
570 ND = isAcceptableTemplateName(Context, ND,
571 /*AllowFunctionTemplates*/ true);
572 if (ND || Corrected.isKeyword()) {
573 if (LookupCtx) {
574 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
575 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
576 Name.getAsString() == CorrectedStr;
577 diagnoseTypo(Corrected,
578 PDiag(diag::err_non_template_in_member_template_id_suggest)
579 << Name << LookupCtx << DroppedSpecifier
Richard Smith52f8d192017-05-10 21:32:16 +0000580 << SS.getRange(), false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000581 } else {
582 diagnoseTypo(Corrected,
583 PDiag(diag::err_non_template_in_template_id_suggest)
Richard Smith52f8d192017-05-10 21:32:16 +0000584 << Name, false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000585 }
586 if (Found)
587 Diag(Found->getLocation(),
588 diag::note_non_template_in_template_id_found);
589 return;
590 }
591 }
592
593 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
594 << Name << SourceRange(Less, Greater);
595 if (Found)
596 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
597}
598
John McCallcd4b4772009-12-02 03:53:29 +0000599/// ActOnDependentIdExpression - Handle a dependent id-expression that
600/// was just parsed. This is only possible with an explicit scope
601/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000602ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000603Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000604 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000605 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000606 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000607 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000608 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Reid Kleckner1af391df2016-03-11 18:59:12 +0000610 // C++11 [expr.prim.general]p12:
611 // An id-expression that denotes a non-static data member or non-static
612 // member function of a class can only be used:
613 // (...)
614 // - if that id-expression denotes a non-static data member and it
615 // appears in an unevaluated operand.
616 //
617 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
618 // CXXDependentScopeMemberExpr. The former can instantiate to either
619 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
620 // always a MemberExpr.
621 bool MightBeCxx11UnevalField =
622 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
623
Akira Hatanakad644e022016-12-16 03:19:41 +0000624 // Check if the nested name specifier is an enum type.
625 bool IsEnum = false;
626 if (NestedNameSpecifier *NNS = SS.getScopeRep())
627 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
628
629 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000630 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000631 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632
John McCalle66edc12009-11-24 19:00:30 +0000633 // Since the 'this' expression is synthesized, we don't need to
634 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000635 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000636
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000637 return CXXDependentScopeMemberExpr::Create(
638 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
639 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
640 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000641 }
642
Abramo Bagnara7945c982012-01-27 09:46:47 +0000643 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000644}
645
John McCalldadc5752010-08-24 06:29:42 +0000646ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000647Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000648 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000649 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000650 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000651 return DependentScopeDeclRefExpr::Create(
652 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
653 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000654}
655
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000656
657/// Determine whether we would be unable to instantiate this template (because
658/// it either has no definition, or is in the process of being instantiated).
659bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
660 NamedDecl *Instantiation,
661 bool InstantiatedFromMember,
662 const NamedDecl *Pattern,
663 const NamedDecl *PatternDef,
664 TemplateSpecializationKind TSK,
665 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000666 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
667 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000668
Richard Smithedbc6e92016-10-14 21:41:24 +0000669 bool IsEntityBeingDefined = false;
670 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
671 IsEntityBeingDefined = TD->isBeingDefined();
672
673 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000674 NamedDecl *SuggestedDef = nullptr;
675 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
676 /*OnlyNeedComplete*/false)) {
677 // If we're allowed to diagnose this and recover, do so.
678 bool Recover = Complain && !isSFINAEContext();
679 if (Complain)
680 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
681 Sema::MissingImportKind::Definition, Recover);
682 return !Recover;
683 }
684 return false;
685 }
686
Richard Smith6f4e2e02016-08-23 19:41:39 +0000687 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
688 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000689
Richard Smithedbc6e92016-10-14 21:41:24 +0000690 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000691 QualType InstantiationTy;
692 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
693 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000694 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000695 Diag(PointOfInstantiation,
696 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000697 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000698 << InstantiationTy;
699 // Not much point in noting the template declaration here, since
700 // we're lexically inside it.
701 Instantiation->setInvalidDecl();
702 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000703 if (isa<FunctionDecl>(Instantiation)) {
704 Diag(PointOfInstantiation,
705 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000706 << /*member function*/ 1 << Instantiation->getDeclName()
707 << Instantiation->getDeclContext();
708 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000709 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000710 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000711 Diag(PointOfInstantiation,
712 diag::err_implicit_instantiate_member_undefined)
713 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000714 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000715 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000716 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000717 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000718 Diag(PointOfInstantiation,
719 diag::err_explicit_instantiation_undefined_func_template)
720 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000721 Note = diag::note_explicit_instantiation_here;
722 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000723 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
724 << (TSK != TSK_ImplicitInstantiation)
725 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000726 Note = diag::note_template_decl_here;
727 } else {
728 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
729 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
730 Diag(PointOfInstantiation,
731 diag::err_explicit_instantiation_undefined_var_template)
732 << Instantiation;
733 Instantiation->setInvalidDecl();
734 } else
735 Diag(PointOfInstantiation,
736 diag::err_explicit_instantiation_undefined_member)
737 << /*static data member*/ 2 << Instantiation->getDeclName()
738 << Instantiation->getDeclContext();
739 Note = diag::note_explicit_instantiation_here;
740 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000741 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000742 if (Note) // Diagnostics were emitted.
743 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000744
745 // In general, Instantiation isn't marked invalid to get more than one
746 // error for multiple undefined instantiations. But the code that does
747 // explicit declaration -> explicit definition conversion can't handle
748 // invalid declarations, so mark as invalid in that case.
749 if (TSK == TSK_ExplicitInstantiationDeclaration)
750 Instantiation->setInvalidDecl();
751 return true;
752}
753
Douglas Gregor5101c242008-12-05 18:15:24 +0000754/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
755/// that the template parameter 'PrevDecl' is being shadowed by a new
756/// declaration at location Loc. Returns true to indicate that this is
757/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000758void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000759 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000760
761 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000762 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000763 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000764
765 // C++ [temp.local]p4:
766 // A template-parameter shall not be redeclared within its
767 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000768 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000769 << cast<NamedDecl>(PrevDecl)->getDeclName();
770 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000771}
772
Douglas Gregor463421d2009-03-03 04:44:36 +0000773/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000774/// the parameter D to reference the templated declaration and return a pointer
775/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000776TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
777 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
778 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000779 return Temp;
780 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000781 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000782}
783
Douglas Gregoreb29d182011-01-05 17:40:24 +0000784ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
785 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000786 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000787 "Only template template arguments can be pack expansions here");
788 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
789 "Template template argument pack expansion without packs");
790 ParsedTemplateArgument Result(*this);
791 Result.EllipsisLoc = EllipsisLoc;
792 return Result;
793}
794
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000795static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
796 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000798 switch (Arg.getKind()) {
799 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000800 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000801 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000802 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000803 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000804 return TemplateArgumentLoc(TemplateArgument(T), DI);
805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000806
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000807 case ParsedTemplateArgument::NonType: {
808 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
809 return TemplateArgumentLoc(TemplateArgument(E), E);
810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000812 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000813 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000814 TemplateArgument TArg;
815 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000816 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000817 else
818 TArg = Template;
819 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000820 Arg.getScopeSpec().getWithLocInContext(
821 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000822 Arg.getLocation(),
823 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000824 }
825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000826
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000827 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000828}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000829
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000830/// Translates template arguments as provided by the parser
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000831/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000832void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
833 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000834 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000835 TemplateArgs.addArgument(translateTemplateArgument(*this,
836 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000837}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000838
Richard Smithb80d5402013-06-25 22:21:36 +0000839static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
840 SourceLocation Loc,
841 IdentifierInfo *Name) {
842 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
Richard Smithbecb92d2017-10-10 22:33:17 +0000843 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
Richard Smithb80d5402013-06-25 22:21:36 +0000844 if (PrevDecl && PrevDecl->isTemplateParameter())
845 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
846}
847
Richard Smith77a9c602018-02-28 03:02:23 +0000848/// Convert a parsed type into a parsed template argument. This is mostly
849/// trivial, except that we may have parsed a C++17 deduced class template
850/// specialization type, in which case we should form a template template
851/// argument instead of a type template argument.
852ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
853 TypeSourceInfo *TInfo;
854 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
855 if (T.isNull())
856 return ParsedTemplateArgument();
857 assert(TInfo && "template argument with no location");
858
859 // If we might have formed a deduced template specialization type, convert
860 // it to a template template argument.
861 if (getLangOpts().CPlusPlus17) {
862 TypeLoc TL = TInfo->getTypeLoc();
863 SourceLocation EllipsisLoc;
864 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
865 EllipsisLoc = PET.getEllipsisLoc();
866 TL = PET.getPatternLoc();
867 }
868
869 CXXScopeSpec SS;
870 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
871 SS.Adopt(ET.getQualifierLoc());
872 TL = ET.getNamedTypeLoc();
873 }
874
875 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
876 TemplateName Name = DTST.getTypePtr()->getTemplateName();
877 if (SS.isSet())
878 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
879 /*HasTemplateKeyword*/ false,
880 Name.getAsTemplateDecl());
881 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
882 DTST.getTemplateNameLoc());
883 if (EllipsisLoc.isValid())
884 Result = Result.getTemplatePackExpansion(EllipsisLoc);
885 return Result;
886 }
887 }
888
889 // This is a normal type template argument. Note, if the type template
890 // argument is an injected-class-name for a template, it has a dual nature
Fangrui Song6907ce22018-07-30 19:24:48 +0000891 // and can be used as either a type or a template. We handle that in
Richard Smith77a9c602018-02-28 03:02:23 +0000892 // convertTypeTemplateArgumentToTemplate.
893 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
894 ParsedType.get().getAsOpaquePtr(),
895 TInfo->getTypeLoc().getLocStart());
896}
897
Douglas Gregor5101c242008-12-05 18:15:24 +0000898/// ActOnTypeParameter - Called when a C++ template type parameter
899/// (e.g., "typename T") has been parsed. Typename specifies whether
900/// the keyword "typename" was used to declare the type parameter
901/// (otherwise, "class" was used), and KeyLoc is the location of the
902/// "class" or "typename" keyword. ParamName is the name of the
903/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000904/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000905/// If the type parameter has a default argument, it will be added
906/// later via ActOnTypeParameterDefault.
Faisal Valibe294032017-12-23 18:56:34 +0000907NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000908 SourceLocation EllipsisLoc,
909 SourceLocation KeyLoc,
910 IdentifierInfo *ParamName,
911 SourceLocation ParamNameLoc,
912 unsigned Depth, unsigned Position,
913 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000914 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000915 assert(S->isTemplateParamScope() &&
916 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000917
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000918 SourceLocation Loc = ParamNameLoc;
919 if (!ParamName)
920 Loc = KeyLoc;
921
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000922 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000923 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000924 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000925 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000926 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000927 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000928
929 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000930 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
931
Douglas Gregor5101c242008-12-05 18:15:24 +0000932 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000933 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000934 IdResolver.AddDecl(Param);
935 }
936
Douglas Gregorf5500772011-01-05 15:48:55 +0000937 // C++0x [temp.param]p9:
938 // A default template-argument may be specified for any kind of
939 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000940 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000941 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000942 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000943 }
944
Douglas Gregordc13ded2010-07-01 00:00:45 +0000945 // Handle the default argument, if provided.
946 if (DefaultArg) {
947 TypeSourceInfo *DefaultTInfo;
948 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000949
Douglas Gregordc13ded2010-07-01 00:00:45 +0000950 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000951
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000952 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000953 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000954 UPPC_DefaultArgument))
955 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000956
Douglas Gregordc13ded2010-07-01 00:00:45 +0000957 // Check the template argument itself.
958 if (CheckTemplateArgument(Param, DefaultTInfo)) {
959 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000960 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000961 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000962
Richard Smith1469b912015-06-10 00:29:03 +0000963 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000965
John McCall48871652010-08-21 09:40:31 +0000966 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000967}
968
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000969/// Check that the type of a non-type template parameter is
Douglas Gregor463421d2009-03-03 04:44:36 +0000970/// well-formed.
971///
972/// \returns the (possibly-promoted) parameter type if valid;
973/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000974QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
975 SourceLocation Loc) {
976 if (TSI->getType()->isUndeducedType()) {
Erik Pilkington9f9462a2018-08-07 22:59:02 +0000977 // C++17 [temp.dep.expr]p3:
Richard Smith15361a22016-12-28 06:27:18 +0000978 // An id-expression is type-dependent if it contains
979 // - an identifier associated by name lookup with a non-type
980 // template-parameter declared with a type that contains a
981 // placeholder type (7.1.7.4),
982 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
983 }
984
985 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
986}
987
988QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
989 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000990 // We don't allow variably-modified types as the type of non-type template
991 // parameters.
992 if (T->isVariablyModifiedType()) {
993 Diag(Loc, diag::err_variably_modified_nontype_template_param)
994 << T;
995 return QualType();
996 }
997
Douglas Gregor463421d2009-03-03 04:44:36 +0000998 // C++ [temp.param]p4:
999 //
1000 // A non-type template-parameter shall have one of the following
1001 // (optionally cv-qualified) types:
1002 //
1003 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +00001004 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001005 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +00001006 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001007 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +00001008 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001009 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +00001010 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001011 // -- std::nullptr_t.
1012 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +00001013 // If T is a dependent type, we can't do the check now, so we
1014 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +00001015 T->isDependentType() ||
1016 // Allow use of auto in template parameter declarations.
1017 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +00001018 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1019 // are ignored when determining its type.
1020 return T.getUnqualifiedType();
1021 }
1022
Douglas Gregor463421d2009-03-03 04:44:36 +00001023 // C++ [temp.param]p8:
1024 //
1025 // A non-type template-parameter of type "array of T" or
1026 // "function returning T" is adjusted to be of type "pointer to
1027 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +00001028 else if (T->isArrayType() || T->isFunctionType())
1029 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001030
Douglas Gregor463421d2009-03-03 04:44:36 +00001031 Diag(Loc, diag::err_template_nontype_parm_bad_type)
1032 << T;
1033
1034 return QualType();
1035}
1036
Faisal Valibe294032017-12-23 18:56:34 +00001037NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
John McCall48871652010-08-21 09:40:31 +00001038 unsigned Depth,
1039 unsigned Position,
1040 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +00001041 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +00001042 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +00001043
Faisal Valia223d1c2017-12-22 03:50:55 +00001044 // Check that we have valid decl-specifiers specified.
1045 auto CheckValidDeclSpecifiers = [this, &D] {
1046 // C++ [temp.param]
Fangrui Song6907ce22018-07-30 19:24:48 +00001047 // p1
Malcolm Parsonsfab36802018-04-16 08:31:08 +00001048 // template-parameter:
1049 // ...
1050 // parameter-declaration
Fangrui Song6907ce22018-07-30 19:24:48 +00001051 // p2
Faisal Valia223d1c2017-12-22 03:50:55 +00001052 // ... A storage class shall not be specified in a template-parameter
1053 // declaration.
Fangrui Song6907ce22018-07-30 19:24:48 +00001054 // [dcl.typedef]p1:
Faisal Valia223d1c2017-12-22 03:50:55 +00001055 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1056 // of a parameter-declaration
1057 const DeclSpec &DS = D.getDeclSpec();
1058 auto EmitDiag = [this](SourceLocation Loc) {
1059 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1060 << FixItHint::CreateRemoval(Loc);
1061 };
1062 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1063 EmitDiag(DS.getStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001064
Sam McCall1371cba2017-12-22 07:09:51 +00001065 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
Faisal Valia223d1c2017-12-22 03:50:55 +00001066 EmitDiag(DS.getThreadStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001067
1068 // [dcl.inline]p1:
1069 // The inline specifier can be applied only to the declaration or
Faisal Valia223d1c2017-12-22 03:50:55 +00001070 // definition of a variable or function.
Fangrui Song6907ce22018-07-30 19:24:48 +00001071
Faisal Valia223d1c2017-12-22 03:50:55 +00001072 if (DS.isInlineSpecified())
1073 EmitDiag(DS.getInlineSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001074
Faisal Valia223d1c2017-12-22 03:50:55 +00001075 // [dcl.constexpr]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00001076 // The constexpr specifier shall be applied only to the definition of a
1077 // variable or variable template or the declaration of a function or
Faisal Valia223d1c2017-12-22 03:50:55 +00001078 // function template.
Fangrui Song6907ce22018-07-30 19:24:48 +00001079
Faisal Valia223d1c2017-12-22 03:50:55 +00001080 if (DS.isConstexprSpecified())
1081 EmitDiag(DS.getConstexprSpecLoc());
1082
1083 // [dcl.fct.spec]p1:
1084 // Function-specifiers can be used only in function declarations.
1085
1086 if (DS.isVirtualSpecified())
1087 EmitDiag(DS.getVirtualSpecLoc());
1088
1089 if (DS.isExplicitSpecified())
1090 EmitDiag(DS.getExplicitSpecLoc());
1091
1092 if (DS.isNoreturnSpecified())
1093 EmitDiag(DS.getNoreturnSpecLoc());
1094 };
1095
1096 CheckValidDeclSpecifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00001097
Richard Smith15361a22016-12-28 06:27:18 +00001098 if (TInfo->getType()->isUndeducedType()) {
1099 Diag(D.getIdentifierLoc(),
1100 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1101 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1102 }
Douglas Gregor5101c242008-12-05 18:15:24 +00001103
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001104 assert(S->isTemplateParamScope() &&
1105 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +00001106 bool Invalid = false;
1107
Richard Smith15361a22016-12-28 06:27:18 +00001108 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001109 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001110 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +00001111 Invalid = true;
1112 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001113
Richard Smithb80d5402013-06-25 22:21:36 +00001114 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001115 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +00001116 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +00001117 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001118 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +00001119 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001121 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001122 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +00001123
Douglas Gregor5101c242008-12-05 18:15:24 +00001124 if (Invalid)
1125 Param->setInvalidDecl();
1126
Richard Smithb80d5402013-06-25 22:21:36 +00001127 if (ParamName) {
1128 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1129 ParamName);
1130
Douglas Gregor5101c242008-12-05 18:15:24 +00001131 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +00001132 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +00001133 IdResolver.AddDecl(Param);
1134 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001135
Douglas Gregorf5500772011-01-05 15:48:55 +00001136 // C++0x [temp.param]p9:
1137 // A default template-argument may be specified for any kind of
1138 // template-parameter that is not a template parameter pack.
1139 if (Default && IsParameterPack) {
1140 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +00001141 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +00001142 }
1143
Douglas Gregordc13ded2010-07-01 00:00:45 +00001144 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001145 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001146 // Check for unexpanded parameter packs.
1147 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1148 return Param;
1149
Douglas Gregordc13ded2010-07-01 00:00:45 +00001150 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +00001151 ExprResult DefaultRes =
1152 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +00001153 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +00001154 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00001155 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001156 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001157 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001158
Richard Smith1469b912015-06-10 00:29:03 +00001159 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +00001160 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001161
John McCall48871652010-08-21 09:40:31 +00001162 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +00001163}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001164
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001165/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +00001166/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001167/// has been parsed. S is the current scope.
Faisal Valibe294032017-12-23 18:56:34 +00001168NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
John McCall48871652010-08-21 09:40:31 +00001169 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00001170 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +00001171 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +00001172 IdentifierInfo *Name,
1173 SourceLocation NameLoc,
1174 unsigned Depth,
1175 unsigned Position,
1176 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +00001177 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001178 assert(S->isTemplateParamScope() &&
1179 "Template template parameter not in template parameter scope!");
1180
1181 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +00001182 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001183 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +00001184 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001185 NameLoc.isInvalid()? TmpLoc : NameLoc,
1186 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +00001187 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001188 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001189
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001190 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +00001191 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001192 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +00001193 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1194
John McCall48871652010-08-21 09:40:31 +00001195 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001196 IdResolver.AddDecl(Param);
1197 }
1198
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001199 if (Params->size() == 0) {
1200 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1201 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1202 Param->setInvalidDecl();
1203 }
1204
Douglas Gregorf5500772011-01-05 15:48:55 +00001205 // C++0x [temp.param]p9:
1206 // A default template-argument may be specified for any kind of
1207 // template-parameter that is not a template parameter pack.
1208 if (IsParameterPack && !Default.isInvalid()) {
1209 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1210 Default = ParsedTemplateArgument();
1211 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001212
Douglas Gregordc13ded2010-07-01 00:00:45 +00001213 if (!Default.isInvalid()) {
1214 // Check only that we have a template template argument. We don't want to
1215 // try to check well-formedness now, because our template template parameter
1216 // might have dependent types in its template parameters, which we wouldn't
1217 // be able to match now.
1218 //
1219 // If none of the template template parameter's template arguments mention
1220 // other template parameters, we could actually perform more checking here.
1221 // However, it isn't worth doing.
1222 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1223 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +00001224 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +00001225 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00001226 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001227 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001228
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001229 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001230 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001231 DefaultArg.getArgument().getAsTemplate(),
1232 UPPC_DefaultArgument))
1233 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001234
Richard Smith1469b912015-06-10 00:29:03 +00001235 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +00001236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001237
John McCall48871652010-08-21 09:40:31 +00001238 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +00001239}
1240
Hubert Tongf608c052016-04-29 18:05:37 +00001241/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1242/// constrained by RequiresClause, that contains the template parameters in
1243/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +00001244TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001245Sema::ActOnTemplateParameterList(unsigned Depth,
1246 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001247 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001248 SourceLocation LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001249 ArrayRef<NamedDecl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001250 SourceLocation RAngleLoc,
1251 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001252 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001253 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001254
David Majnemer902f8c62015-12-27 07:16:27 +00001255 return TemplateParameterList::Create(
1256 Context, TemplateLoc, LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001257 llvm::makeArrayRef(Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001258 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001259}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001260
John McCall3e11ebe2010-03-15 10:12:16 +00001261static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1262 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +00001263 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00001264}
1265
Erich Keanec480f302018-07-12 21:09:05 +00001266DeclResult Sema::CheckClassTemplate(
1267 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1268 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1269 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1270 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1271 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1272 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001273 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001274 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001275 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001276 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001277
1278 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001279 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001280 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001281
Abramo Bagnara6150c882010-05-11 21:36:43 +00001282 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1283 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001284
1285 // There is no such thing as an unnamed class template.
1286 if (!Name) {
1287 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001288 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001289 }
1290
Richard Smith6483d222012-04-21 01:27:54 +00001291 // Find any previous declaration with this name. For a friend with no
1292 // scope explicitly specified, we only look for tag declarations (per
1293 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001294 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001295 LookupResult Previous(*this, Name, NameLoc,
1296 (SS.isEmpty() && TUK == TUK_Friend)
1297 ? LookupTagName : LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001298 forRedeclarationInCurContext());
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001299 if (SS.isNotEmpty() && !SS.isInvalid()) {
1300 SemanticContext = computeDeclContext(SS, true);
1301 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001302 // FIXME: Horrible, horrible hack! We can't currently represent this
1303 // in the AST, and historically we have just ignored such friend
1304 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001305 Diag(NameLoc, TUK == TUK_Friend
1306 ? diag::warn_template_qualified_friend_ignored
1307 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001308 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001309 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001310 }
Mike Stump11289f42009-09-09 15:08:12 +00001311
John McCall0b66eb32010-05-01 00:40:08 +00001312 if (RequireCompleteDeclContext(SS, SemanticContext))
1313 return true;
1314
Simon Pilgrim6905d222016-12-30 22:55:33 +00001315 // If we're adding a template to a dependent context, we may need to
1316 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001317 // now that we know what the current instantiation is.
1318 if (SemanticContext->isDependentContext()) {
1319 ContextRAII SavedContext(*this, SemanticContext);
1320 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1321 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001322 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
Richard Smithc660c8f2018-03-16 13:36:56 +00001323 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
Richard Smith6483d222012-04-21 01:27:54 +00001324
John McCall27b18f82009-11-17 02:14:36 +00001325 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001326 } else {
1327 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001328
1329 // C++14 [class.mem]p14:
1330 // If T is the name of a class, then each of the following shall have a
1331 // name different from T:
1332 // -- every member template of class T
1333 if (TUK != TUK_Friend &&
1334 DiagnoseClassNameShadow(SemanticContext,
1335 DeclarationNameInfo(Name, NameLoc)))
1336 return true;
1337
John McCall27b18f82009-11-17 02:14:36 +00001338 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001339 }
Mike Stump11289f42009-09-09 15:08:12 +00001340
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001341 if (Previous.isAmbiguous())
1342 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001343
Craig Topperc3ec1492014-05-26 06:22:03 +00001344 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001345 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001346 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001347
Serge Pavlove50bf752016-06-10 04:39:07 +00001348 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1349 // Maybe we will complain about the shadowed template parameter.
1350 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1351 // Just pretend that we didn't see the previous declaration.
1352 PrevDecl = nullptr;
1353 }
1354
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001355 // If there is a previous declaration with the same name, check
1356 // whether this is a valid redeclaration.
Richard Smithbecb92d2017-10-10 22:33:17 +00001357 ClassTemplateDecl *PrevClassTemplate =
1358 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001359
1360 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001361 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001362 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001364 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1365 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001366 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001367 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1368 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1369 PrevClassTemplate
1370 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1371 ->getSpecializedTemplate();
1372 }
1373 }
1374
John McCalld43784f2009-12-18 11:25:59 +00001375 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001376 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001377 // [...] When looking for a prior declaration of a class or a function
1378 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001379 // function is neither a qualified name nor a template-id, scopes outside
1380 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001381 if (!SS.isSet()) {
1382 DeclContext *OutermostContext = CurContext;
1383 while (!OutermostContext->isFileContext())
1384 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001385
Richard Smith61e582f2012-04-20 07:12:26 +00001386 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001387 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1388 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1389 SemanticContext = PrevDecl->getDeclContext();
1390 } else {
1391 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001392 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001393 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001394 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001395 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001396
1397 // Check that the chosen semantic context doesn't already contain a
1398 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001399 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001400 DeclContext *LookupContext = SemanticContext;
1401 while (LookupContext->isTransparentContext())
1402 LookupContext = LookupContext->getLookupParent();
1403 LookupQualifiedName(Previous, LookupContext);
1404
1405 if (Previous.isAmbiguous())
1406 return true;
1407
1408 if (Previous.begin() != Previous.end())
1409 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001410 }
John McCall90d3bb92009-12-17 23:21:11 +00001411 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001412 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001413 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1414 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001415 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001416
Richard Smithfc805ca2015-07-06 04:43:58 +00001417 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1418 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1419 if (SS.isEmpty() &&
1420 !(PrevClassTemplate &&
1421 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1422 SemanticContext->getRedeclContext()))) {
1423 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1424 Diag(Shadow->getTargetDecl()->getLocation(),
1425 diag::note_using_decl_target);
1426 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1427 // Recover by ignoring the old declaration.
1428 PrevDecl = PrevClassTemplate = nullptr;
1429 }
1430 }
1431
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001432 // TODO Memory management; associated constraints are not always stored.
1433 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1434
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001435 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001436 // Ensure that the template parameter lists are compatible. Skip this check
1437 // for a friend in a dependent context: the template parameter list itself
1438 // could be dependent.
1439 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1440 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001441 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001442 /*Complain=*/true,
1443 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001444 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001445
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001446 // Check for matching associated constraints on redeclarations.
1447 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1448 const bool RedeclACMismatch = [&] {
1449 if (!(CurAC || PrevAC))
1450 return false; // Nothing to check; no mismatch.
1451 if (CurAC && PrevAC) {
1452 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1453 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1454 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1455 if (CurACInfo == PrevACInfo)
1456 return false; // All good; no mismatch.
1457 }
1458 return true;
1459 }();
1460
1461 if (RedeclACMismatch) {
1462 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1463 diag::err_template_different_associated_constraints);
1464 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1465 diag::note_template_prev_declaration) << /*declaration*/0;
1466 return true;
1467 }
1468
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001469 // C++ [temp.class]p4:
1470 // In a redeclaration, partial specialization, explicit
1471 // specialization or explicit instantiation of a class template,
1472 // the class-key shall agree in kind with the original class
1473 // template declaration (7.1.5.3).
1474 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001475 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001476 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001477 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001478 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001479 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001480 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001481 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001482 }
1483
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001484 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001485 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001486 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001487 // If we have a prior definition that is not visible, treat this as
1488 // simply making that previous definition visible.
1489 NamedDecl *Hidden = nullptr;
1490 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001491 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001492 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1493 assert(Tmpl && "original definition of a class template is not a "
1494 "class template?");
Richard Smith858e0e02017-05-11 23:11:16 +00001495 makeMergedDefinitionVisible(Hidden);
1496 makeMergedDefinitionVisible(Tmpl);
Richard Smithbe3980b2015-03-27 00:41:57 +00001497 return Def;
1498 }
1499
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001500 Diag(NameLoc, diag::err_redefinition) << Name;
1501 Diag(Def->getLocation(), diag::note_previous_definition);
1502 // FIXME: Would it make sense to try to "forget" the previous
1503 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001504 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001505 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001506 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001507 } else if (PrevDecl) {
1508 // C++ [temp]p5:
1509 // A class template shall not have the same name as any other
1510 // template, class, function, object, enumeration, enumerator,
1511 // namespace, or type in the same scope (3.3), except as specified
1512 // in (14.5.4).
1513 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1514 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001515 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001516 }
1517
Douglas Gregordba32632009-02-10 19:49:53 +00001518 // Check the template parameter list of this declaration, possibly
1519 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001520 // template declaration. Skip this check for a friend in a dependent
1521 // context, because the template parameter list might be dependent.
1522 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001523 CheckTemplateParameterList(
1524 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001525 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1526 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001527 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1528 SemanticContext->isDependentContext())
1529 ? TPC_ClassTemplateMember
1530 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1531 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001532 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001533
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001534 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001535 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001536 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001537 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1538 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001539 : diag::err_member_decl_does_not_match)
1540 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001541 Invalid = true;
1542 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001543 }
1544
Vassil Vassilev352e4412017-01-12 09:16:26 +00001545 // If this is a templated friend in a dependent context we should not put it
1546 // on the redecl chain. In some cases, the templated friend can be the most
1547 // recent declaration tricking the template instantiator to make substitutions
1548 // there.
1549 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1550 bool ShouldAddRedecl
1551 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1552
Mike Stump11289f42009-09-09 15:08:12 +00001553 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001554 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001555 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001556 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001557 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001558 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001559 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001560 NewClass->setTemplateParameterListsInfo(
1561 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1562 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001563
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001564 // Add alignment attributes if necessary; these attributes are checked when
1565 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001566 if (TUK == TUK_Definition) {
1567 AddAlignmentAttributesForRecord(NewClass);
1568 AddMsStructLayoutForRecord(NewClass);
1569 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001570
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001571 // Attach the associated constraints when the declaration will not be part of
1572 // a decl chain.
1573 Expr *const ACtoAttach =
1574 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1575
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001576 ClassTemplateDecl *NewTemplate
1577 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1578 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001579 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001580
1581 if (ShouldAddRedecl)
1582 NewTemplate->setPreviousDecl(PrevClassTemplate);
1583
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001584 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001585
Douglas Gregor21823bf2011-12-20 18:11:52 +00001586 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001587 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001588
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001589 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001590 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001591 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001592 assert(T->isDependentType() && "Class template type is not dependent?");
1593 (void)T;
1594
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001595 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001596 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001597 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001598 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1599 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001600
Anders Carlsson137108d2009-03-26 01:24:28 +00001601 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001602 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001603 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001604
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001605 // Set the lexical context of these templates
1606 NewClass->setLexicalDeclContext(CurContext);
1607 NewTemplate->setLexicalDeclContext(CurContext);
1608
John McCall9bb74a52009-07-31 02:45:11 +00001609 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001610 NewClass->startDefinition();
1611
Erich Keanec480f302018-07-12 21:09:05 +00001612 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001613
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001614 if (PrevClassTemplate)
1615 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1616
Rafael Espindola385c0422012-07-13 18:04:45 +00001617 AddPushedVisibilityAttribute(NewClass);
1618
Richard Smith234ff472014-08-23 00:49:01 +00001619 if (TUK != TUK_Friend) {
1620 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1621 Scope *Outer = S;
1622 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1623 Outer = Outer->getParent();
1624 PushOnScopeChains(NewTemplate, Outer);
1625 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001626 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001627 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001628 NewClass->setAccess(PrevClassTemplate->getAccess());
1629 }
John McCall27b5c252009-09-14 21:59:20 +00001630
Richard Smith64017682013-07-17 23:53:16 +00001631 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001632
John McCall27b5c252009-09-14 21:59:20 +00001633 // Friend templates are visible in fairly strange ways.
1634 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001635 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001636 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001637 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1638 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001639 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001640 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001641
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001642 FriendDecl *Friend = FriendDecl::Create(
1643 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001644 Friend->setAccess(AS_public);
1645 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001646 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001647
Richard Smithbecb92d2017-10-10 22:33:17 +00001648 if (PrevClassTemplate)
1649 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1650
Douglas Gregordba32632009-02-10 19:49:53 +00001651 if (Invalid) {
1652 NewTemplate->setInvalidDecl();
1653 NewClass->setInvalidDecl();
1654 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001655
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001656 ActOnDocumentableDecl(NewTemplate);
1657
John McCall48871652010-08-21 09:40:31 +00001658 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001659}
1660
Richard Smith32918772017-02-14 00:25:28 +00001661namespace {
Erik Pilkington69770d32018-07-27 21:23:48 +00001662/// Tree transform to "extract" a transformed type from a class template's
1663/// constructor to a deduction guide.
1664class ExtractTypeForDeductionGuide
1665 : public TreeTransform<ExtractTypeForDeductionGuide> {
1666public:
1667 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
1668 ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1669
1670 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1671
1672 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1673 return TransformType(
1674 TLB,
1675 TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1676 }
1677};
1678
Richard Smith32918772017-02-14 00:25:28 +00001679/// Transform to convert portions of a constructor declaration into the
1680/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1681struct ConvertConstructorToDeductionGuideTransform {
1682 ConvertConstructorToDeductionGuideTransform(Sema &S,
1683 ClassTemplateDecl *Template)
1684 : SemaRef(S), Template(Template) {}
1685
1686 Sema &SemaRef;
1687 ClassTemplateDecl *Template;
1688
1689 DeclContext *DC = Template->getDeclContext();
1690 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1691 DeclarationName DeductionGuideName =
1692 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1693
1694 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1695
1696 // Index adjustment to apply to convert depth-1 template parameters into
1697 // depth-0 template parameters.
1698 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1699
1700 /// Transform a constructor declaration into a deduction guide.
Richard Smithbc491202017-02-17 20:05:37 +00001701 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1702 CXXConstructorDecl *CD) {
Richard Smith32918772017-02-14 00:25:28 +00001703 SmallVector<TemplateArgument, 16> SubstArgs;
1704
Richard Smithb4f96252017-02-21 06:30:38 +00001705 LocalInstantiationScope Scope(SemaRef);
1706
Richard Smith32918772017-02-14 00:25:28 +00001707 // C++ [over.match.class.deduct]p1:
1708 // -- For each constructor of the class template designated by the
1709 // template-name, a function template with the following properties:
1710
1711 // -- The template parameters are the template parameters of the class
1712 // template followed by the template parameters (including default
1713 // template arguments) of the constructor, if any.
1714 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1715 if (FTD) {
1716 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1717 SmallVector<NamedDecl *, 16> AllParams;
1718 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1719 AllParams.insert(AllParams.begin(),
1720 TemplateParams->begin(), TemplateParams->end());
1721 SubstArgs.reserve(InnerParams->size());
1722
1723 // Later template parameters could refer to earlier ones, so build up
1724 // a list of substituted template arguments as we go.
1725 for (NamedDecl *Param : *InnerParams) {
1726 MultiLevelTemplateArgumentList Args;
1727 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001728 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001729 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1730 if (!NewParam)
1731 return nullptr;
1732 AllParams.push_back(NewParam);
1733 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1734 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1735 }
1736 TemplateParams = TemplateParameterList::Create(
1737 SemaRef.Context, InnerParams->getTemplateLoc(),
1738 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1739 /*FIXME: RequiresClause*/ nullptr);
1740 }
1741
1742 // If we built a new template-parameter-list, track that we need to
1743 // substitute references to the old parameters into references to the
1744 // new ones.
1745 MultiLevelTemplateArgumentList Args;
1746 if (FTD) {
1747 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001748 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001749 }
1750
Richard Smithbc491202017-02-17 20:05:37 +00001751 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
Richard Smith32918772017-02-14 00:25:28 +00001752 .getAsAdjusted<FunctionProtoTypeLoc>();
1753 assert(FPTL && "no prototype for constructor declaration");
1754
1755 // Transform the type of the function, adjusting the return type and
1756 // replacing references to the old parameters with references to the
1757 // new ones.
1758 TypeLocBuilder TLB;
1759 SmallVector<ParmVarDecl*, 8> Params;
1760 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1761 if (NewType.isNull())
1762 return nullptr;
1763 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1764
Richard Smithbc491202017-02-17 20:05:37 +00001765 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1766 CD->getLocStart(), CD->getLocation(),
1767 CD->getLocEnd());
Richard Smith32918772017-02-14 00:25:28 +00001768 }
1769
1770 /// Build a deduction guide with the specified parameter types.
1771 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1772 SourceLocation Loc = Template->getLocation();
1773
1774 // Build the requested type.
1775 FunctionProtoType::ExtProtoInfo EPI;
1776 EPI.HasTrailingReturn = true;
1777 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1778 DeductionGuideName, EPI);
1779 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1780
1781 FunctionProtoTypeLoc FPTL =
1782 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1783
1784 // Build the parameters, needed during deduction / substitution.
1785 SmallVector<ParmVarDecl*, 4> Params;
1786 for (auto T : ParamTypes) {
1787 ParmVarDecl *NewParam = ParmVarDecl::Create(
1788 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1789 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1790 NewParam->setScopeInfo(0, Params.size());
1791 FPTL.setParam(Params.size(), NewParam);
1792 Params.push_back(NewParam);
1793 }
1794
1795 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1796 Loc, Loc, Loc);
1797 }
1798
1799private:
1800 /// Transform a constructor template parameter into a deduction guide template
1801 /// parameter, rebuilding any internal references to earlier parameters and
1802 /// renumbering as we go.
1803 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1804 MultiLevelTemplateArgumentList &Args) {
1805 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1806 // TemplateTypeParmDecl's index cannot be changed after creation, so
1807 // substitute it directly.
1808 auto *NewTTP = TemplateTypeParmDecl::Create(
1809 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1810 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1811 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1812 TTP->isParameterPack());
1813 if (TTP->hasDefaultArgument()) {
1814 TypeSourceInfo *InstantiatedDefaultArg =
1815 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1816 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1817 if (InstantiatedDefaultArg)
1818 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1819 }
Richard Smithb4f96252017-02-21 06:30:38 +00001820 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1821 NewTTP);
Richard Smith32918772017-02-14 00:25:28 +00001822 return NewTTP;
1823 }
1824
1825 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1826 return transformTemplateParameterImpl(TTP, Args);
1827
1828 return transformTemplateParameterImpl(
1829 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1830 }
1831 template<typename TemplateParmDecl>
1832 TemplateParmDecl *
1833 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1834 MultiLevelTemplateArgumentList &Args) {
1835 // Ask the template instantiator to do the heavy lifting for us, then adjust
1836 // the index of the parameter once it's done.
1837 auto *NewParam =
1838 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1839 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1840 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1841 return NewParam;
1842 }
1843
1844 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1845 FunctionProtoTypeLoc TL,
1846 SmallVectorImpl<ParmVarDecl*> &Params,
1847 MultiLevelTemplateArgumentList &Args) {
1848 SmallVector<QualType, 4> ParamTypes;
1849 const FunctionProtoType *T = TL.getTypePtr();
1850
1851 // -- The types of the function parameters are those of the constructor.
1852 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001853 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001854 if (!NewParam)
1855 return QualType();
1856 ParamTypes.push_back(NewParam->getType());
1857 Params.push_back(NewParam);
1858 }
1859
1860 // -- The return type is the class template specialization designated by
1861 // the template-name and template arguments corresponding to the
1862 // template parameters obtained from the class template.
1863 //
1864 // We use the injected-class-name type of the primary template instead.
1865 // This has the convenient property that it is different from any type that
1866 // the user can write in a deduction-guide (because they cannot enter the
1867 // context of the template), so implicit deduction guides can never collide
1868 // with explicit ones.
1869 QualType ReturnType = DeducedType;
1870 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1871
1872 // Resolving a wording defect, we also inherit the variadicness of the
1873 // constructor.
1874 FunctionProtoType::ExtProtoInfo EPI;
1875 EPI.Variadic = T->isVariadic();
1876 EPI.HasTrailingReturn = true;
1877
1878 QualType Result = SemaRef.BuildFunctionType(
1879 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1880 if (Result.isNull())
1881 return QualType();
1882
1883 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1884 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1885 NewTL.setLParenLoc(TL.getLParenLoc());
1886 NewTL.setRParenLoc(TL.getRParenLoc());
1887 NewTL.setExceptionSpecRange(SourceRange());
1888 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1889 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1890 NewTL.setParam(I, Params[I]);
1891
1892 return Result;
1893 }
1894
1895 ParmVarDecl *
1896 transformFunctionTypeParam(ParmVarDecl *OldParam,
1897 MultiLevelTemplateArgumentList &Args) {
1898 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smith479ba8e2017-04-20 01:15:31 +00001899 TypeSourceInfo *NewDI;
Erik Pilkington69770d32018-07-27 21:23:48 +00001900 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
Richard Smith479ba8e2017-04-20 01:15:31 +00001901 // Expand out the one and only element in each inner pack.
1902 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1903 NewDI =
1904 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1905 OldParam->getLocation(), OldParam->getDeclName());
1906 if (!NewDI) return nullptr;
1907 NewDI =
1908 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1909 PackTL.getTypePtr()->getNumExpansions());
1910 } else
1911 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1912 OldParam->getDeclName());
Richard Smith32918772017-02-14 00:25:28 +00001913 if (!NewDI)
1914 return nullptr;
1915
Erik Pilkington69770d32018-07-27 21:23:48 +00001916 // Extract the type. This (for instance) replaces references to typedef
1917 // members of the current instantiations with the definitions of those
1918 // typedefs, avoiding triggering instantiation of the deduced type during
1919 // deduction.
1920 NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
Richard Smithc27b3d72017-02-14 01:49:59 +00001921
Richard Smith32918772017-02-14 00:25:28 +00001922 // Resolving a wording defect, we also inherit default arguments from the
1923 // constructor.
1924 ExprResult NewDefArg;
1925 if (OldParam->hasDefaultArg()) {
Erik Pilkington69770d32018-07-27 21:23:48 +00001926 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
Richard Smith32918772017-02-14 00:25:28 +00001927 if (NewDefArg.isInvalid())
1928 return nullptr;
1929 }
1930
1931 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1932 OldParam->getInnerLocStart(),
1933 OldParam->getLocation(),
1934 OldParam->getIdentifier(),
1935 NewDI->getType(),
1936 NewDI,
1937 OldParam->getStorageClass(),
1938 NewDefArg.get());
1939 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1940 OldParam->getFunctionScopeIndex());
Erik Pilkington69770d32018-07-27 21:23:48 +00001941 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
Richard Smith32918772017-02-14 00:25:28 +00001942 return NewParam;
1943 }
1944
1945 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1946 bool Explicit, TypeSourceInfo *TInfo,
1947 SourceLocation LocStart, SourceLocation Loc,
1948 SourceLocation LocEnd) {
Richard Smithbc491202017-02-17 20:05:37 +00001949 DeclarationNameInfo Name(DeductionGuideName, Loc);
Richard Smithefa919a2017-02-16 21:29:21 +00001950 ArrayRef<ParmVarDecl *> Params =
1951 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1952
Richard Smith32918772017-02-14 00:25:28 +00001953 // Build the implicit deduction guide template.
Richard Smithbc491202017-02-17 20:05:37 +00001954 auto *Guide =
1955 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1956 Name, TInfo->getType(), TInfo, LocEnd);
Richard Smith32918772017-02-14 00:25:28 +00001957 Guide->setImplicit();
Richard Smithefa919a2017-02-16 21:29:21 +00001958 Guide->setParams(Params);
1959
1960 for (auto *Param : Params)
1961 Param->setDeclContext(Guide);
Richard Smith32918772017-02-14 00:25:28 +00001962
1963 auto *GuideTemplate = FunctionTemplateDecl::Create(
1964 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1965 GuideTemplate->setImplicit();
1966 Guide->setDescribedFunctionTemplate(GuideTemplate);
1967
1968 if (isa<CXXRecordDecl>(DC)) {
1969 Guide->setAccess(AS_public);
1970 GuideTemplate->setAccess(AS_public);
1971 }
1972
1973 DC->addDecl(GuideTemplate);
1974 return GuideTemplate;
1975 }
1976};
1977}
1978
1979void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1980 SourceLocation Loc) {
1981 DeclContext *DC = Template->getDeclContext();
1982 if (DC->isDependentContext())
1983 return;
1984
1985 ConvertConstructorToDeductionGuideTransform Transform(
1986 *this, cast<ClassTemplateDecl>(Template));
1987 if (!isCompleteType(Loc, Transform.DeducedType))
1988 return;
1989
1990 // Check whether we've already declared deduction guides for this template.
1991 // FIXME: Consider storing a flag on the template to indicate this.
1992 auto Existing = DC->lookup(Transform.DeductionGuideName);
1993 for (auto *D : Existing)
1994 if (D->isImplicit())
1995 return;
1996
1997 // In case we were expanding a pack when we attempted to declare deduction
1998 // guides, turn off pack expansion for everything we're about to do.
1999 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2000 // Create a template instantiation record to track the "instantiation" of
2001 // constructors into deduction guides.
2002 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2003 // this substitution process actually fail?
2004 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
Volodymyr Sapsai2f649f32018-05-14 22:49:44 +00002005 if (BuildingDeductionGuides.isInvalid())
2006 return;
Richard Smith32918772017-02-14 00:25:28 +00002007
2008 // Convert declared constructors into deduction guide templates.
2009 // FIXME: Skip constructors for which deduction must necessarily fail (those
2010 // for which some class template parameter without a default argument never
2011 // appears in a deduced context).
2012 bool AddedAny = false;
Richard Smith32918772017-02-14 00:25:28 +00002013 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2014 D = D->getUnderlyingDecl();
2015 if (D->isInvalidDecl() || D->isImplicit())
2016 continue;
2017 D = cast<NamedDecl>(D->getCanonicalDecl());
2018
2019 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00002020 auto *CD =
2021 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00002022 // Class-scope explicit specializations (MS extension) do not result in
2023 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00002024 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00002025 continue;
2026
Richard Smithbc491202017-02-17 20:05:37 +00002027 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00002028 AddedAny = true;
Richard Smith32918772017-02-14 00:25:28 +00002029 }
2030
Faisal Vali81b756e2017-10-22 14:45:08 +00002031 // C++17 [over.match.class.deduct]
2032 // -- If C is not defined or does not declare any constructors, an
2033 // additional function template derived as above from a hypothetical
2034 // constructor C().
Richard Smith32918772017-02-14 00:25:28 +00002035 if (!AddedAny)
2036 Transform.buildSimpleDeductionGuide(None);
2037
Faisal Vali81b756e2017-10-22 14:45:08 +00002038 // -- An additional function template derived as above from a hypothetical
2039 // constructor C(C), called the copy deduction candidate.
2040 cast<CXXDeductionGuideDecl>(
2041 cast<FunctionTemplateDecl>(
2042 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2043 ->getTemplatedDecl())
2044 ->setIsCopyDeductionCandidate();
Richard Smith32918772017-02-14 00:25:28 +00002045}
2046
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002047/// Diagnose the presence of a default template argument on a
Douglas Gregored5731f2009-11-25 17:50:39 +00002048/// template parameter, which is ill-formed in certain contexts.
2049///
2050/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002051static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00002052 Sema::TemplateParamListContext TPC,
2053 SourceLocation ParamLoc,
2054 SourceRange DefArgRange) {
2055 switch (TPC) {
2056 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002057 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00002058 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002059 return false;
2060
2061 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002062 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002063 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00002064 // A default template-argument shall not be specified in a
2065 // function template declaration or a function template
2066 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00002067 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002068 // template-argument, that declaration shall be a definition and shall be
2069 // the only declaration of the function template in the translation unit.
2070 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002071 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002072 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2073 : diag::ext_template_parameter_default_in_function_template)
2074 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00002075 return false;
2076
2077 case Sema::TPC_ClassTemplateMember:
2078 // C++0x [temp.param]p9:
2079 // A default template-argument shall not be specified in the
2080 // template-parameter-lists of the definition of a member of a
2081 // class template that appears outside of the member's class.
2082 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2083 << DefArgRange;
2084 return true;
2085
David Majnemerba8f17a2013-06-25 22:08:55 +00002086 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002087 case Sema::TPC_FriendFunctionTemplate:
2088 // C++ [temp.param]p9:
2089 // A default template-argument shall not be specified in a
2090 // friend template declaration.
2091 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2092 << DefArgRange;
2093 return true;
2094
2095 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2096 // for friend function templates if there is only a single
2097 // declaration (and it is a definition). Strange!
2098 }
2099
David Blaikie8a40f702012-01-17 06:56:22 +00002100 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00002101}
2102
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002103/// Check for unexpanded parameter packs within the template parameters
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002104/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00002105static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2106 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002107 // A template template parameter which is a parameter pack is also a pack
2108 // expansion.
2109 if (TTP->isParameterPack())
2110 return false;
2111
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002112 TemplateParameterList *Params = TTP->getTemplateParameters();
2113 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2114 NamedDecl *P = Params->getParam(I);
2115 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002116 if (!NTTP->isParameterPack() &&
2117 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002118 NTTP->getTypeSourceInfo(),
2119 Sema::UPPC_NonTypeTemplateParameterType))
2120 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002121
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002122 continue;
2123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124
2125 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002126 = dyn_cast<TemplateTemplateParmDecl>(P))
2127 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2128 return true;
2129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002131 return false;
2132}
2133
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002134/// Checks the validity of a template parameter list, possibly
Douglas Gregordba32632009-02-10 19:49:53 +00002135/// considering the template parameter list from a previous
2136/// declaration.
2137///
2138/// If an "old" template parameter list is provided, it must be
2139/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2140/// template parameter list.
2141///
2142/// \param NewParams Template parameter list for a new template
2143/// declaration. This template parameter list will be updated with any
2144/// default arguments that are carried through from the previous
2145/// template parameter list.
2146///
2147/// \param OldParams If provided, template parameter list from a
2148/// previous declaration of the same template. Default template
2149/// arguments will be merged from the old template parameter list to
2150/// the new template parameter list.
2151///
Douglas Gregored5731f2009-11-25 17:50:39 +00002152/// \param TPC Describes the context in which we are checking the given
2153/// template parameter list.
2154///
Douglas Gregordba32632009-02-10 19:49:53 +00002155/// \returns true if an error occurred, false otherwise.
2156bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00002157 TemplateParameterList *OldParams,
2158 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00002159 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00002160
Douglas Gregordba32632009-02-10 19:49:53 +00002161 // C++ [temp.param]p10:
2162 // The set of default template-arguments available for use with a
2163 // template declaration or definition is obtained by merging the
2164 // default arguments from the definition (if in scope) and all
2165 // declarations in scope in the same way default function
2166 // arguments are (8.3.6).
2167 bool SawDefaultArgument = false;
2168 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00002169
Mike Stumpc89c8e32009-02-11 23:03:27 +00002170 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00002171 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00002172 if (OldParams)
2173 OldParam = OldParams->begin();
2174
Douglas Gregor0693def2011-01-27 01:40:17 +00002175 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00002176 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2177 NewParamEnd = NewParams->end();
2178 NewParam != NewParamEnd; ++NewParam) {
2179 // Variables used to diagnose redundant default arguments
2180 bool RedundantDefaultArg = false;
2181 SourceLocation OldDefaultLoc;
2182 SourceLocation NewDefaultLoc;
2183
David Blaikie651c73c2011-10-19 05:19:50 +00002184 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00002185 bool MissingDefaultArg = false;
2186
David Blaikie651c73c2011-10-19 05:19:50 +00002187 // Variable used to diagnose non-final parameter packs
2188 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00002189
Douglas Gregordba32632009-02-10 19:49:53 +00002190 if (TemplateTypeParmDecl *NewTypeParm
2191 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00002192 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002193 if (NewTypeParm->hasDefaultArgument() &&
2194 DiagnoseDefaultTemplateArgument(*this, TPC,
2195 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002196 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002197 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00002198 NewTypeParm->removeDefaultArgument();
2199
2200 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002201 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002202 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00002203 if (NewTypeParm->isParameterPack()) {
2204 assert(!NewTypeParm->hasDefaultArgument() &&
2205 "Parameter packs can't have a default argument!");
2206 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002207 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00002208 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00002209 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2210 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2211 SawDefaultArgument = true;
2212 RedundantDefaultArg = true;
2213 PreviousDefaultArgLoc = NewDefaultLoc;
2214 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2215 // Merge the default argument from the old declaration to the
2216 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002217 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002218 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2219 } else if (NewTypeParm->hasDefaultArgument()) {
2220 SawDefaultArgument = true;
2221 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2222 } else if (SawDefaultArgument)
2223 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002224 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00002225 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002226 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002227 if (!NewNonTypeParm->isParameterPack() &&
2228 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002229 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002230 UPPC_NonTypeTemplateParameterType)) {
2231 Invalid = true;
2232 continue;
2233 }
2234
Douglas Gregored5731f2009-11-25 17:50:39 +00002235 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002236 if (NewNonTypeParm->hasDefaultArgument() &&
2237 DiagnoseDefaultTemplateArgument(*this, TPC,
2238 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002239 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00002240 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002241 }
2242
Mike Stump12b8ce12009-08-04 21:02:39 +00002243 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002244 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002245 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002246 if (NewNonTypeParm->isParameterPack()) {
2247 assert(!NewNonTypeParm->hasDefaultArgument() &&
2248 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002249 if (!NewNonTypeParm->isPackExpansion())
2250 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002251 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00002252 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00002253 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2254 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2255 SawDefaultArgument = true;
2256 RedundantDefaultArg = true;
2257 PreviousDefaultArgLoc = NewDefaultLoc;
2258 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2259 // Merge the default argument from the old declaration to the
2260 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002261 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002262 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2263 } else if (NewNonTypeParm->hasDefaultArgument()) {
2264 SawDefaultArgument = true;
2265 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2266 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002267 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002268 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00002269 TemplateTemplateParmDecl *NewTemplateParm
2270 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002271
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002272 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002273 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002274 Invalid = true;
2275 continue;
2276 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002277
David Blaikie651c73c2011-10-19 05:19:50 +00002278 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002279 if (NewTemplateParm->hasDefaultArgument() &&
2280 DiagnoseDefaultTemplateArgument(*this, TPC,
2281 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002282 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002283 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002284
2285 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002286 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002287 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002288 if (NewTemplateParm->isParameterPack()) {
2289 assert(!NewTemplateParm->hasDefaultArgument() &&
2290 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002291 if (!NewTemplateParm->isPackExpansion())
2292 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002293 } else if (OldTemplateParm &&
2294 hasVisibleDefaultArgument(OldTemplateParm) &&
2295 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002296 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2297 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002298 SawDefaultArgument = true;
2299 RedundantDefaultArg = true;
2300 PreviousDefaultArgLoc = NewDefaultLoc;
2301 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2302 // Merge the default argument from the old declaration to the
2303 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002304 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002305 PreviousDefaultArgLoc
2306 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002307 } else if (NewTemplateParm->hasDefaultArgument()) {
2308 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002309 PreviousDefaultArgLoc
2310 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002311 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002312 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002313 }
2314
Richard Smith1fde8ec2012-09-07 02:06:42 +00002315 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002316 // If a template parameter of a primary class template or alias template
2317 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002318 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002319 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2320 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002321 Diag((*NewParam)->getLocation(),
2322 diag::err_template_param_pack_must_be_last_template_parameter);
2323 Invalid = true;
2324 }
2325
Douglas Gregordba32632009-02-10 19:49:53 +00002326 if (RedundantDefaultArg) {
2327 // C++ [temp.param]p12:
2328 // A template-parameter shall not be given default arguments
2329 // by two different declarations in the same scope.
2330 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2331 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2332 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002333 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002334 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002335 // If a template-parameter of a class template has a default
2336 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002337 // have a default template-argument supplied or be a template parameter
2338 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002339 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002340 diag::err_template_param_default_arg_missing);
2341 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2342 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002343 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002344 }
2345
2346 // If we have an old template parameter list that we're merging
2347 // in, move on to the next parameter.
2348 if (OldParams)
2349 ++OldParam;
2350 }
2351
Douglas Gregor0693def2011-01-27 01:40:17 +00002352 // We were missing some default arguments at the end of the list, so remove
2353 // all of the default arguments.
2354 if (RemoveDefaultArguments) {
2355 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2356 NewParamEnd = NewParams->end();
2357 NewParam != NewParamEnd; ++NewParam) {
2358 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2359 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002360 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002361 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2362 NTTP->removeDefaultArgument();
2363 else
2364 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2365 }
2366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002367
Douglas Gregordba32632009-02-10 19:49:53 +00002368 return Invalid;
2369}
Douglas Gregord32e0282009-02-09 23:23:08 +00002370
John McCalla020a012010-10-20 05:44:58 +00002371namespace {
2372
2373/// A class which looks for a use of a certain level of template
2374/// parameter.
2375struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2376 typedef RecursiveASTVisitor<DependencyChecker> super;
2377
2378 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00002379
2380 // Whether we're looking for a use of a template parameter that makes the
2381 // overall construct type-dependent / a dependent type. This is strictly
2382 // best-effort for now; we may fail to match at all for a dependent type
2383 // in some cases if this is set.
2384 bool IgnoreNonTypeDependent;
2385
John McCalla020a012010-10-20 05:44:58 +00002386 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002387 SourceLocation MatchLoc;
2388
Richard Smith13894182017-04-13 21:37:24 +00002389 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2390 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2391 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002392
Richard Smith57aae072016-12-28 02:37:25 +00002393 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith13894182017-04-13 21:37:24 +00002394 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2395 NamedDecl *ND = Params->getParam(0);
2396 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2397 Depth = PD->getDepth();
2398 } else if (NonTypeTemplateParmDecl *PD =
2399 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2400 Depth = PD->getDepth();
2401 } else {
2402 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2403 }
2404 }
John McCalla020a012010-10-20 05:44:58 +00002405
Richard Smith6056d5e2014-02-09 00:54:43 +00002406 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith13894182017-04-13 21:37:24 +00002407 if (ParmDepth >= Depth) {
John McCalla020a012010-10-20 05:44:58 +00002408 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002409 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002410 return true;
2411 }
2412 return false;
2413 }
2414
Richard Smith57aae072016-12-28 02:37:25 +00002415 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2416 // Prune out non-type-dependent expressions if requested. This can
2417 // sometimes result in us failing to find a template parameter reference
2418 // (if a value-dependent expression creates a dependent type), but this
2419 // mode is best-effort only.
2420 if (auto *E = dyn_cast_or_null<Expr>(S))
2421 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2422 return true;
2423 return super::TraverseStmt(S, Q);
2424 }
2425
2426 bool TraverseTypeLoc(TypeLoc TL) {
2427 if (IgnoreNonTypeDependent && !TL.isNull() &&
2428 !TL.getType()->isDependentType())
2429 return true;
2430 return super::TraverseTypeLoc(TL);
2431 }
2432
Richard Smith6056d5e2014-02-09 00:54:43 +00002433 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2434 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2435 }
2436
John McCalla020a012010-10-20 05:44:58 +00002437 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002438 // For a best-effort search, keep looking until we find a location.
2439 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002440 }
2441
2442 bool TraverseTemplateName(TemplateName N) {
2443 if (TemplateTemplateParmDecl *PD =
2444 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002445 if (Matches(PD->getDepth()))
2446 return false;
John McCalla020a012010-10-20 05:44:58 +00002447 return super::TraverseTemplateName(N);
2448 }
2449
2450 bool VisitDeclRefExpr(DeclRefExpr *E) {
2451 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002452 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2453 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002454 return false;
John McCalla020a012010-10-20 05:44:58 +00002455 return super::VisitDeclRefExpr(E);
2456 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002457
2458 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2459 return TraverseType(T->getReplacementType());
2460 }
2461
2462 bool
2463 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2464 return TraverseTemplateArgument(T->getArgumentPack());
2465 }
2466
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002467 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2468 return TraverseType(T->getInjectedSpecializationType());
2469 }
John McCalla020a012010-10-20 05:44:58 +00002470};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002471} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002472
Douglas Gregor972fe532011-05-10 18:27:06 +00002473/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002474/// list.
2475static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002476DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002477 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002478 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002479 return Checker.Match;
2480}
2481
Douglas Gregor972fe532011-05-10 18:27:06 +00002482// Find the source range corresponding to the named type in the given
2483// nested-name-specifier, if any.
2484static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2485 QualType T,
2486 const CXXScopeSpec &SS) {
2487 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2488 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2489 if (const Type *CurType = NNS->getAsType()) {
2490 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2491 return NNSLoc.getTypeLoc().getSourceRange();
2492 } else
2493 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002494
Douglas Gregor972fe532011-05-10 18:27:06 +00002495 NNSLoc = NNSLoc.getPrefix();
2496 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002497
Douglas Gregor972fe532011-05-10 18:27:06 +00002498 return SourceRange();
2499}
2500
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002501/// Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002502/// specifier, returning the template parameter list that applies to the
2503/// name.
2504///
2505/// \param DeclStartLoc the start of the declaration that has a scope
2506/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002507///
Douglas Gregor972fe532011-05-10 18:27:06 +00002508/// \param DeclLoc The location of the declaration itself.
2509///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002510/// \param SS the scope specifier that will be matched to the given template
2511/// parameter lists. This scope specifier precedes a qualified name that is
2512/// being declared.
2513///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002514/// \param TemplateId The template-id following the scope specifier, if there
2515/// is one. Used to check for a missing 'template<>'.
2516///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002517/// \param ParamLists the template parameter lists, from the outermost to the
2518/// innermost template parameter lists.
2519///
John McCalle820e5e2010-04-13 20:37:33 +00002520/// \param IsFriend Whether to apply the slightly different rules for
2521/// matching template parameters to scope specifiers in friend
2522/// declarations.
2523///
Richard Smithf445f192017-02-09 21:04:43 +00002524/// \param IsMemberSpecialization will be set true if the scope specifier
2525/// denotes a fully-specialized type, and therefore this is a declaration of
2526/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002527///
Mike Stump11289f42009-09-09 15:08:12 +00002528/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002529/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002530/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002531/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002532/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002533/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002534TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2535 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002536 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002537 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002538 bool &IsMemberSpecialization, bool &Invalid) {
2539 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002540 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002541
Douglas Gregor972fe532011-05-10 18:27:06 +00002542 // The sequence of nested types to which we will match up the template
2543 // parameter lists. We first build this list by starting with the type named
2544 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002545 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002546 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002547 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002548 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002549 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2550 T = Context.getTypeDeclType(Record);
2551 else
2552 T = QualType(SS.getScopeRep()->getAsType(), 0);
2553 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002554
Douglas Gregor972fe532011-05-10 18:27:06 +00002555 // If we found an explicit specialization that prevents us from needing
2556 // 'template<>' headers, this will be set to the location of that
2557 // explicit specialization.
2558 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002559
Douglas Gregor972fe532011-05-10 18:27:06 +00002560 while (!T.isNull()) {
2561 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002562
Douglas Gregor972fe532011-05-10 18:27:06 +00002563 // Retrieve the parent of a record type.
2564 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2565 // If this type is an explicit specialization, we're done.
2566 if (ClassTemplateSpecializationDecl *Spec
2567 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002568 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002569 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2570 ExplicitSpecLoc = Spec->getLocation();
2571 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002572 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002573 } else if (Record->getTemplateSpecializationKind()
2574 == TSK_ExplicitSpecialization) {
2575 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002576 break;
2577 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002578
Douglas Gregor972fe532011-05-10 18:27:06 +00002579 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2580 T = Context.getTypeDeclType(Parent);
2581 else
2582 T = QualType();
2583 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002584 }
2585
Douglas Gregor972fe532011-05-10 18:27:06 +00002586 if (const TemplateSpecializationType *TST
2587 = T->getAs<TemplateSpecializationType>()) {
2588 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2589 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2590 T = Context.getTypeDeclType(Parent);
2591 else
2592 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002593 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002594 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002595 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002596
Douglas Gregor972fe532011-05-10 18:27:06 +00002597 // Look one step prior in a dependent template specialization type.
2598 if (const DependentTemplateSpecializationType *DependentTST
2599 = T->getAs<DependentTemplateSpecializationType>()) {
2600 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2601 T = QualType(NNS->getAsType(), 0);
2602 else
2603 T = QualType();
2604 continue;
2605 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002606
Douglas Gregor972fe532011-05-10 18:27:06 +00002607 // Look one step prior in a dependent name type.
2608 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2609 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2610 T = QualType(NNS->getAsType(), 0);
2611 else
2612 T = QualType();
2613 continue;
2614 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002615
Douglas Gregor972fe532011-05-10 18:27:06 +00002616 // Retrieve the parent of an enumeration type.
2617 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2618 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2619 // check here.
2620 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002621
Douglas Gregor972fe532011-05-10 18:27:06 +00002622 // Get to the parent type.
2623 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2624 T = Context.getTypeDeclType(Parent);
2625 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002626 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002627 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002628 }
Mike Stump11289f42009-09-09 15:08:12 +00002629
Douglas Gregor972fe532011-05-10 18:27:06 +00002630 T = QualType();
2631 }
2632 // Reverse the nested types list, since we want to traverse from the outermost
2633 // to the innermost while checking template-parameter-lists.
2634 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002635
Douglas Gregor972fe532011-05-10 18:27:06 +00002636 // C++0x [temp.expl.spec]p17:
2637 // A member or a member template may be nested within many
2638 // enclosing class templates. In an explicit specialization for
2639 // such a member, the member declaration shall be preceded by a
2640 // template<> for each enclosing class template that is
2641 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002642 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002643
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002644 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002645 if (SawNonEmptyTemplateParameterList) {
2646 Diag(DeclLoc, diag::err_specialize_member_of_template)
2647 << !Recovery << Range;
2648 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002649 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002650 return true;
2651 }
2652
2653 return false;
2654 };
2655
2656 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2657 // Check that we can have an explicit specialization here.
2658 if (CheckExplicitSpecialization(Range, true))
2659 return true;
2660
2661 // We don't have a template header, but we should.
2662 SourceLocation ExpectedTemplateLoc;
2663 if (!ParamLists.empty())
2664 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2665 else
2666 ExpectedTemplateLoc = DeclStartLoc;
2667
2668 Diag(DeclLoc, diag::err_template_spec_needs_header)
2669 << Range
2670 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2671 return false;
2672 };
2673
Douglas Gregor972fe532011-05-10 18:27:06 +00002674 unsigned ParamIdx = 0;
2675 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2676 ++TypeIdx) {
2677 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002678
Douglas Gregor972fe532011-05-10 18:27:06 +00002679 // Whether we expect a 'template<>' header.
2680 bool NeedEmptyTemplateHeader = false;
2681
2682 // Whether we expect a template header with parameters.
2683 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002684
Douglas Gregor972fe532011-05-10 18:27:06 +00002685 // For a dependent type, the set of template parameters that we
2686 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002687 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002688
Douglas Gregor373af9b2011-05-11 23:26:17 +00002689 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002690 // A member or a member template may be nested within many enclosing
2691 // class templates. In an explicit specialization for such a member, the
2692 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002693 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002694 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2695 if (ClassTemplatePartialSpecializationDecl *Partial
2696 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2697 ExpectedTemplateParams = Partial->getTemplateParameters();
2698 NeedNonemptyTemplateHeader = true;
2699 } else if (Record->isDependentType()) {
2700 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002701 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002702 ->getTemplateParameters();
2703 NeedNonemptyTemplateHeader = true;
2704 }
2705 } else if (ClassTemplateSpecializationDecl *Spec
2706 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2707 // C++0x [temp.expl.spec]p4:
2708 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002709 // in the same manner as members of normal classes, and not using
2710 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002711 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2712 NeedEmptyTemplateHeader = true;
2713 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002714 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002715 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002716 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002717 != TSK_ExplicitSpecialization &&
2718 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002719 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002720
Douglas Gregor373af9b2011-05-11 23:26:17 +00002721 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002722 }
2723 } else if (const TemplateSpecializationType *TST
2724 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002725 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002726 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002727 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002728 }
2729 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2730 // FIXME: We actually could/should check the template arguments here
2731 // against the corresponding template parameter list.
2732 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002733 }
2734
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002735 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002736 // In an explicit specialization declaration for a member of a class
2737 // template or a member template that ap- pears in namespace scope, the
2738 // member template and some of its enclosing class templates may remain
2739 // unspecialized, except that the declaration shall not explicitly
2740 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002741 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002742 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002743 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002744 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2745 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002746 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002747 } else
2748 SawNonEmptyTemplateParameterList = true;
2749 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002750
Douglas Gregor972fe532011-05-10 18:27:06 +00002751 if (NeedEmptyTemplateHeader) {
2752 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002753 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002754 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002755 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002756
2757 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002758 if (ParamLists[ParamIdx]->size() > 0) {
2759 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002760 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002761 diag::err_template_param_list_matches_nontemplate)
2762 << T
2763 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2764 ParamLists[ParamIdx]->getRAngleLoc())
2765 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2766 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002767 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002768 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002769
Douglas Gregor972fe532011-05-10 18:27:06 +00002770 // Consume this template header.
2771 ++ParamIdx;
2772 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002773 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002774
2775 if (!IsFriend)
2776 if (DiagnoseMissingExplicitSpecialization(
2777 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002778 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002779
Douglas Gregor972fe532011-05-10 18:27:06 +00002780 continue;
2781 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002782
Douglas Gregor972fe532011-05-10 18:27:06 +00002783 if (NeedNonemptyTemplateHeader) {
2784 // In friend declarations we can have template-ids which don't
2785 // depend on the corresponding template parameter lists. But
2786 // assume that empty parameter lists are supposed to match this
2787 // template-id.
2788 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002789 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002790 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002791 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002792 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002793 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002794 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002795
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002796 if (ParamIdx < ParamLists.size()) {
2797 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002798 if (ExpectedTemplateParams &&
2799 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2800 ExpectedTemplateParams,
2801 true, TPL_TemplateMatch))
2802 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002803
Douglas Gregor972fe532011-05-10 18:27:06 +00002804 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002805 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002806 TPC_ClassTemplateMember))
2807 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002808
Douglas Gregor972fe532011-05-10 18:27:06 +00002809 ++ParamIdx;
2810 continue;
2811 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002812
Douglas Gregor972fe532011-05-10 18:27:06 +00002813 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2814 << T
2815 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2816 Invalid = true;
2817 continue;
2818 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002819 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002820
Douglas Gregord8d297c2009-07-21 23:53:31 +00002821 // If there were at least as many template-ids as there were template
2822 // parameter lists, then there are no template parameter lists remaining for
2823 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002824 if (ParamIdx >= ParamLists.size()) {
2825 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002826 // We don't have a template header for the declaration itself, but we
2827 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002828 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2829 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002830
2831 // Fabricate an empty template parameter list for the invented header.
2832 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002833 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002834 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002835 }
2836
Craig Topperc3ec1492014-05-26 06:22:03 +00002837 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002838 }
Mike Stump11289f42009-09-09 15:08:12 +00002839
Douglas Gregord8d297c2009-07-21 23:53:31 +00002840 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002841 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002842 bool HasAnyExplicitSpecHeader = false;
2843 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002844 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002845 if (ParamLists[I]->size() == 0)
2846 HasAnyExplicitSpecHeader = true;
2847 else
2848 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002849 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002850
Douglas Gregor972fe532011-05-10 18:27:06 +00002851 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002852 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2853 : diag::err_template_spec_extra_headers)
2854 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2855 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002856
2857 // If there was a specialization somewhere, such that 'template<>' is
2858 // not required, and there were any 'template<>' headers, note where the
2859 // specialization occurred.
2860 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002861 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002862 diag::note_explicit_template_spec_does_not_need_header)
2863 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002864
Douglas Gregor972fe532011-05-10 18:27:06 +00002865 // We have a template parameter list with no corresponding scope, which
2866 // means that the resulting template declaration can't be instantiated
2867 // properly (we'll end up with dependent nodes when we shouldn't).
2868 if (!AllExplicitSpecHeaders)
2869 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002870 }
Mike Stump11289f42009-09-09 15:08:12 +00002871
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002872 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002873 // In an explicit specialization declaration for a member of a class
2874 // template or a member template that ap- pears in namespace scope, the
2875 // member template and some of its enclosing class templates may remain
2876 // unspecialized, except that the declaration shall not explicitly
2877 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002878 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002879 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002880 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2881 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002882 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002883
Douglas Gregord8d297c2009-07-21 23:53:31 +00002884 // Return the last template parameter list, which corresponds to the
2885 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002886 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002887}
2888
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002889void Sema::NoteAllFoundTemplates(TemplateName Name) {
2890 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2891 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002892 << (isa<FunctionTemplateDecl>(Template)
2893 ? 0
2894 : isa<ClassTemplateDecl>(Template)
2895 ? 1
2896 : isa<VarTemplateDecl>(Template)
2897 ? 2
2898 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2899 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002900 return;
2901 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002902
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002903 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002904 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002905 IEnd = OST->end();
2906 I != IEnd; ++I)
2907 Diag((*I)->getLocation(), diag::note_template_declared_here)
2908 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002909
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002910 return;
2911 }
2912}
2913
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002914static QualType
2915checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2916 const SmallVectorImpl<TemplateArgument> &Converted,
2917 SourceLocation TemplateLoc,
2918 TemplateArgumentListInfo &TemplateArgs) {
2919 ASTContext &Context = SemaRef.getASTContext();
2920 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002921 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002922 // Specializations of __make_integer_seq<S, T, N> are treated like
2923 // S<T, 0, ..., N-1>.
2924
2925 // C++14 [inteseq.intseq]p1:
2926 // T shall be an integer type.
2927 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2928 SemaRef.Diag(TemplateArgs[1].getLocation(),
2929 diag::err_integer_sequence_integral_element_type);
2930 return QualType();
2931 }
2932
2933 // C++14 [inteseq.make]p1:
2934 // If N is negative the program is ill-formed.
2935 TemplateArgument NumArgsArg = Converted[2];
2936 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2937 if (NumArgs < 0) {
2938 SemaRef.Diag(TemplateArgs[2].getLocation(),
2939 diag::err_integer_sequence_negative_length);
2940 return QualType();
2941 }
2942
2943 QualType ArgTy = NumArgsArg.getIntegralType();
2944 TemplateArgumentListInfo SyntheticTemplateArgs;
2945 // The type argument gets reused as the first template argument in the
2946 // synthetic template argument list.
2947 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2948 // Expand N into 0 ... N-1.
2949 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2950 I < NumArgs; ++I) {
2951 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002952 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2953 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002954 }
2955 // The first template argument will be reused as the template decl that
2956 // our synthetic template arguments will be applied to.
2957 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2958 TemplateLoc, SyntheticTemplateArgs);
2959 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002960
2961 case BTK__type_pack_element:
2962 // Specializations of
2963 // __type_pack_element<Index, T_1, ..., T_N>
2964 // are treated like T_Index.
2965 assert(Converted.size() == 2 &&
2966 "__type_pack_element should be given an index and a parameter pack");
2967
2968 // If the Index is out of bounds, the program is ill-formed.
2969 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2970 llvm::APSInt Index = IndexArg.getAsIntegral();
2971 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2972 "type std::size_t, and hence be non-negative");
2973 if (Index >= Ts.pack_size()) {
2974 SemaRef.Diag(TemplateArgs[0].getLocation(),
2975 diag::err_type_pack_element_out_of_bounds);
2976 return QualType();
2977 }
2978
2979 // We simply return the type at index `Index`.
2980 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2981 return Nth->getAsType();
2982 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002983 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2984}
2985
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002986/// Determine whether this alias template is "enable_if_t".
2987static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
2988 return AliasTemplate->getName().equals("enable_if_t");
2989}
2990
2991/// Collect all of the separable terms in the given condition, which
2992/// might be a conjunction.
2993///
2994/// FIXME: The right answer is to convert the logical expression into
2995/// disjunctive normal form, so we can find the first failed term
2996/// within each possible clause.
2997static void collectConjunctionTerms(Expr *Clause,
2998 SmallVectorImpl<Expr *> &Terms) {
2999 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3000 if (BinOp->getOpcode() == BO_LAnd) {
3001 collectConjunctionTerms(BinOp->getLHS(), Terms);
3002 collectConjunctionTerms(BinOp->getRHS(), Terms);
3003 }
3004
3005 return;
3006 }
3007
3008 Terms.push_back(Clause);
3009}
3010
Douglas Gregorbb33f572017-07-05 20:20:15 +00003011// The ranges-v3 library uses an odd pattern of a top-level "||" with
3012// a left-hand side that is value-dependent but never true. Identify
3013// the idiom and ignore that term.
3014static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3015 // Top-level '||'.
3016 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3017 if (!BinOp) return Cond;
3018
3019 if (BinOp->getOpcode() != BO_LOr) return Cond;
3020
3021 // With an inner '==' that has a literal on the right-hand side.
3022 Expr *LHS = BinOp->getLHS();
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003023 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
Douglas Gregorbb33f572017-07-05 20:20:15 +00003024 if (!InnerBinOp) return Cond;
3025
3026 if (InnerBinOp->getOpcode() != BO_EQ ||
3027 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3028 return Cond;
3029
3030 // If the inner binary operation came from a macro expansion named
3031 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3032 // of the '||', which is the real, user-provided condition.
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003033 SourceLocation Loc = InnerBinOp->getExprLoc();
Douglas Gregorbb33f572017-07-05 20:20:15 +00003034 if (!Loc.isMacroID()) return Cond;
3035
3036 StringRef MacroName = PP.getImmediateMacroName(Loc);
3037 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3038 return BinOp->getRHS();
3039
3040 return Cond;
3041}
3042
Douglas Gregor672281a2017-09-14 23:38:42 +00003043std::pair<Expr *, std::string>
3044Sema::findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond) {
3045 Cond = lookThroughRangesV3Condition(PP, Cond);
Douglas Gregorbb33f572017-07-05 20:20:15 +00003046
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003047 // Separate out all of the terms in a conjunction.
3048 SmallVector<Expr *, 4> Terms;
3049 collectConjunctionTerms(Cond, Terms);
3050
3051 // Determine which term failed.
3052 Expr *FailedCond = nullptr;
3053 for (Expr *Term : Terms) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003054 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3055
3056 // Literals are uninteresting.
3057 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3058 isa<IntegerLiteral>(TermAsWritten))
3059 continue;
3060
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003061 // The initialization of the parameter from the argument is
3062 // a constant-evaluated context.
3063 EnterExpressionEvaluationContext ConstantEvaluated(
Douglas Gregor672281a2017-09-14 23:38:42 +00003064 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003065
3066 bool Succeeded;
Douglas Gregor672281a2017-09-14 23:38:42 +00003067 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003068 !Succeeded) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003069 FailedCond = TermAsWritten;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003070 break;
3071 }
3072 }
3073
Douglas Gregor672281a2017-09-14 23:38:42 +00003074 if (!FailedCond) {
3075 if (!AllowTopLevelCond)
3076 return { nullptr, "" };
3077
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003078 FailedCond = Cond->IgnoreParenImpCasts();
Douglas Gregor672281a2017-09-14 23:38:42 +00003079 }
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003080
3081 std::string Description;
3082 {
3083 llvm::raw_string_ostream Out(Description);
Douglas Gregor672281a2017-09-14 23:38:42 +00003084 FailedCond->printPretty(Out, nullptr, getPrintingPolicy());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003085 }
3086 return { FailedCond, Description };
3087}
3088
Douglas Gregordc572a32009-03-30 22:58:21 +00003089QualType Sema::CheckTemplateIdType(TemplateName Name,
3090 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003091 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00003092 DependentTemplateName *DTN
3093 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00003094 if (DTN && DTN->isIdentifier())
3095 // When building a template-id where the template-name is dependent,
3096 // assume the template is a type template. Either our assumption is
3097 // correct, or the code is ill-formed and will be diagnosed when the
3098 // dependent name is substituted.
3099 return Context.getDependentTemplateSpecializationType(ETK_None,
3100 DTN->getQualifier(),
3101 DTN->getIdentifier(),
3102 TemplateArgs);
3103
Douglas Gregordc572a32009-03-30 22:58:21 +00003104 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00003105 if (!Template || isa<FunctionTemplateDecl>(Template) ||
Faisal Valia534f072018-04-26 00:42:40 +00003106 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003107 // We might have a substituted template template parameter pack. If so,
3108 // build a template specialization type for it.
3109 if (Name.getAsSubstTemplateTemplateParmPack())
3110 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003111
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003112 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3113 << Name;
3114 NoteAllFoundTemplates(Name);
3115 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00003116 }
Douglas Gregordc572a32009-03-30 22:58:21 +00003117
Douglas Gregorc40290e2009-03-09 23:48:35 +00003118 // Check that the template argument list is well-formed for this
3119 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003120 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00003121 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003122 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00003123 return QualType();
3124
Douglas Gregorc40290e2009-03-09 23:48:35 +00003125 QualType CanonType;
3126
Douglas Gregor678d76c2011-07-01 01:22:09 +00003127 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00003128 if (TypeAliasTemplateDecl *AliasTemplate =
3129 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00003130 // Find the canonical type for this type alias template specialization.
3131 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3132 if (Pattern->isInvalidDecl())
3133 return QualType();
3134
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003135 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3136 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003137
3138 // Only substitute for the innermost template argument list.
3139 MultiLevelTemplateArgumentList TemplateArgLists;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003140 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00003141 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3142 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00003143 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003144
Richard Smith802c4b72012-08-23 06:16:52 +00003145 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003146 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003147 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003148 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00003149
Richard Smith3f1b5d02011-05-05 21:57:07 +00003150 CanonType = SubstType(Pattern->getUnderlyingType(),
3151 TemplateArgLists, AliasTemplate->getLocation(),
3152 AliasTemplate->getDeclName());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003153 if (CanonType.isNull()) {
3154 // If this was enable_if and we failed to find the nested type
3155 // within enable_if in a SFINAE context, dig out the specific
3156 // enable_if condition that failed and present that instead.
3157 if (isEnableIfAliasTemplate(AliasTemplate)) {
3158 if (auto DeductionInfo = isSFINAEContext()) {
3159 if (*DeductionInfo &&
3160 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3161 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3162 diag::err_typename_nested_not_found_enable_if &&
3163 TemplateArgs[0].getArgument().getKind()
3164 == TemplateArgument::Expression) {
3165 Expr *FailedCond;
3166 std::string FailedDescription;
3167 std::tie(FailedCond, FailedDescription) =
Douglas Gregor672281a2017-09-14 23:38:42 +00003168 findFailedBooleanCondition(
3169 TemplateArgs[0].getSourceExpression(),
3170 /*AllowTopLevelCond=*/true);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003171
3172 // Remove the old SFINAE diagnostic.
3173 PartialDiagnosticAt OldDiag =
3174 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3175 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3176
3177 // Add a new SFINAE diagnostic specifying which condition
3178 // failed.
3179 (*DeductionInfo)->addSFINAEDiagnostic(
3180 OldDiag.first,
3181 PDiag(diag::err_typename_nested_not_found_requirement)
3182 << FailedDescription
3183 << FailedCond->getSourceRange());
3184 }
3185 }
3186 }
3187
Richard Smith3f1b5d02011-05-05 21:57:07 +00003188 return QualType();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003189 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003190 } else if (Name.isDependent() ||
3191 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00003192 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003193 // This class template specialization is a dependent
3194 // type. Therefore, its canonical type is another class template
3195 // specialization type that contains all of the converted
3196 // arguments in canonical form. This ensures that, e.g., A<T> and
3197 // A<T, T> have identical types when A is declared as:
3198 //
3199 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003200 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00003201
3202 // This might work out to be a current instantiation, in which
3203 // case the canonical type needs to be the InjectedClassNameType.
3204 //
3205 // TODO: in theory this could be a simple hashtable lookup; most
3206 // changes to CurContext don't change the set of current
3207 // instantiations.
3208 if (isa<ClassTemplateDecl>(Template)) {
3209 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3210 // If we get out to a namespace, we're done.
3211 if (Ctx->isFileContext()) break;
3212
3213 // If this isn't a record, keep looking.
3214 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3215 if (!Record) continue;
3216
3217 // Look for one of the two cases with InjectedClassNameTypes
3218 // and check whether it's the same template.
3219 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3220 !Record->getDescribedClassTemplate())
3221 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003222
John McCall2408e322010-04-27 00:57:59 +00003223 // Fetch the injected class name type and check whether its
3224 // injected type is equal to the type we just built.
3225 QualType ICNT = Context.getTypeDeclType(Record);
3226 QualType Injected = cast<InjectedClassNameType>(ICNT)
3227 ->getInjectedSpecializationType();
3228
3229 if (CanonType != Injected->getCanonicalTypeInternal())
3230 continue;
3231
3232 // If so, the canonical type of this TST is the injected
3233 // class name type of the record we just found.
3234 assert(ICNT.isCanonical());
3235 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00003236 break;
3237 }
3238 }
Mike Stump11289f42009-09-09 15:08:12 +00003239 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00003240 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003241 // Find the class template specialization declaration that
3242 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003243 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003244 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00003245 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003246 if (!Decl) {
3247 // This is the first time we have referenced this class template
3248 // specialization. Create the canonical declaration and add it to
3249 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003250 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00003251 ClassTemplate->getTemplatedDecl()->getTagKind(),
3252 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00003253 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003254 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003255 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00003256 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003257 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00003258 if (ClassTemplate->isOutOfLine())
3259 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00003260 }
3261
Erich Keanea32910d2017-03-23 18:51:54 +00003262 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3263 MultiLevelTemplateArgumentList TemplateArgLists;
3264 TemplateArgLists.addOuterTemplateArguments(Converted);
3265 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3266 Decl);
3267 }
3268
Chandler Carruth2acfb222013-09-27 22:14:40 +00003269 // Diagnose uses of this specialization.
3270 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3271
Douglas Gregorc40290e2009-03-09 23:48:35 +00003272 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00003273 assert(isa<RecordType>(CanonType) &&
3274 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003275 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3276 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3277 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003278 }
Mike Stump11289f42009-09-09 15:08:12 +00003279
Douglas Gregorc40290e2009-03-09 23:48:35 +00003280 // Build the fully-sugared type for this class template
3281 // specialization, which refers back to the class template
3282 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00003283 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003284}
3285
John McCallfaf5fb42010-08-26 23:41:50 +00003286TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003287Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00003288 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3289 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00003290 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00003291 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00003292 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00003293 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003294 if (SS.isInvalid())
3295 return true;
3296
Richard Smith62559bd2017-02-01 21:36:38 +00003297 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3298 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3299
3300 // C++ [temp.res]p3:
3301 // A qualified-id that refers to a type and in which the
3302 // nested-name-specifier depends on a template-parameter (14.6.2)
3303 // shall be prefixed by the keyword typename to indicate that the
3304 // qualified-id denotes a type, forming an
3305 // elaborated-type-specifier (7.1.5.3).
3306 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00003307 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00003308 << SS.getScopeRep() << TemplateII->getName();
3309 // Recover as if 'typename' were specified.
3310 // FIXME: This is not quite correct recovery as we don't transform SS
3311 // into the corresponding dependent form (and we don't diagnose missing
3312 // 'template' keywords within SS as a result).
3313 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3314 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3315 TemplateArgsIn, RAngleLoc);
3316 }
3317
3318 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3319 // it's not actually allowed to be used as a type in most cases. Because
3320 // we annotate it before we know whether it's valid, we have to check for
3321 // this case here.
3322 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00003323 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3324 Diag(TemplateIILoc,
3325 TemplateKWLoc.isInvalid()
3326 ? diag::err_out_of_line_qualified_id_type_names_constructor
3327 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3328 << TemplateII << 0 /*injected-class-name used as template name*/
3329 << 1 /*if any keyword was present, it was 'template'*/;
3330 }
3331 }
3332
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003333 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00003334
Douglas Gregorc40290e2009-03-09 23:48:35 +00003335 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003336 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003337 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00003338
Douglas Gregor5a064722011-02-28 17:23:35 +00003339 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00003340 QualType T
3341 = Context.getDependentTemplateSpecializationType(ETK_None,
3342 DTN->getQualifier(),
3343 DTN->getIdentifier(),
3344 TemplateArgs);
3345 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00003346 TypeLocBuilder TLB;
3347 DependentTemplateSpecializationTypeLoc SpecTL
3348 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003349 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3350 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003351 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003352 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003353 SpecTL.setLAngleLoc(LAngleLoc);
3354 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003355 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3356 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3357 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3358 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003359
Richard Smith74f02342017-01-19 21:00:13 +00003360 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003361 if (Result.isNull())
3362 return true;
3363
Douglas Gregore7c20652011-03-02 00:47:37 +00003364 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003365 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00003366 TemplateSpecializationTypeLoc SpecTL
3367 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003368 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003369 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003370 SpecTL.setLAngleLoc(LAngleLoc);
3371 SpecTL.setRAngleLoc(RAngleLoc);
3372 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3373 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00003374
Abramo Bagnara4244b432012-01-27 08:46:19 +00003375 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3376 // constructor or destructor name (in such a case, the scope specifier
3377 // will be attached to the enclosing Decl or Expr node).
3378 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003379 // Create an elaborated-type-specifier containing the nested-name-specifier.
3380 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3381 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003382 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00003383 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3384 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003385
Douglas Gregore7c20652011-03-02 00:47:37 +00003386 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00003387}
John McCall06f6fe8d2009-09-04 01:14:41 +00003388
Douglas Gregore7c20652011-03-02 00:47:37 +00003389TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00003390 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00003391 SourceLocation TagLoc,
3392 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003393 SourceLocation TemplateKWLoc,
3394 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00003395 SourceLocation TemplateLoc,
3396 SourceLocation LAngleLoc,
3397 ASTTemplateArgsPtr TemplateArgsIn,
3398 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003399 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003400
Douglas Gregore7c20652011-03-02 00:47:37 +00003401 // Translate the parser's template argument list in our AST format.
3402 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3403 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003404
Douglas Gregore7c20652011-03-02 00:47:37 +00003405 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00003406 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00003407 ElaboratedTypeKeyword Keyword
3408 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00003409
Douglas Gregore7c20652011-03-02 00:47:37 +00003410 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3411 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00003412 DTN->getQualifier(),
3413 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00003414 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003415
3416 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00003417 TypeLocBuilder TLB;
3418 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003419 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3420 SpecTL.setElaboratedKeywordLoc(TagLoc);
3421 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003422 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003423 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003424 SpecTL.setLAngleLoc(LAngleLoc);
3425 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003426 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3427 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3428 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3429 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003430
3431 if (TypeAliasTemplateDecl *TAT =
3432 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3433 // C++0x [dcl.type.elab]p2:
3434 // If the identifier resolves to a typedef-name or the simple-template-id
3435 // resolves to an alias template specialization, the
3436 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003437 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3438 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003439 Diag(TAT->getLocation(), diag::note_declared_at);
3440 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003441
Douglas Gregore7c20652011-03-02 00:47:37 +00003442 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3443 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003444 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003445
Douglas Gregore7c20652011-03-02 00:47:37 +00003446 // Check the tag kind
3447 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003448 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003449
John McCalld8fe9af2009-09-08 17:47:29 +00003450 IdentifierInfo *Id = D->getIdentifier();
3451 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003452
Richard Trieucaa33d32011-06-10 03:11:26 +00003453 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003454 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003455 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003456 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003457 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003458 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003459 }
3460 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003461
Douglas Gregore7c20652011-03-02 00:47:37 +00003462 // Provide source-location information for the template specialization.
3463 TypeLocBuilder TLB;
3464 TemplateSpecializationTypeLoc SpecTL
3465 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003466 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003467 SpecTL.setTemplateNameLoc(TemplateLoc);
3468 SpecTL.setLAngleLoc(LAngleLoc);
3469 SpecTL.setRAngleLoc(RAngleLoc);
3470 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3471 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003472
Douglas Gregore7c20652011-03-02 00:47:37 +00003473 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003474 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003475 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3476 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003477 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003478 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3479 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003480}
3481
Larisse Voufo39a1e502013-08-06 01:03:05 +00003482static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3483 NamedDecl *PrevDecl,
3484 SourceLocation Loc,
3485 bool IsPartialSpecialization);
3486
3487static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003488
Richard Smith300e0c32013-09-24 04:49:23 +00003489static bool isTemplateArgumentTemplateParameter(
3490 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3491 switch (Arg.getKind()) {
3492 case TemplateArgument::Null:
3493 case TemplateArgument::NullPtr:
3494 case TemplateArgument::Integral:
3495 case TemplateArgument::Declaration:
3496 case TemplateArgument::Pack:
3497 case TemplateArgument::TemplateExpansion:
3498 return false;
3499
3500 case TemplateArgument::Type: {
3501 QualType Type = Arg.getAsType();
3502 const TemplateTypeParmType *TPT =
3503 Arg.getAsType()->getAs<TemplateTypeParmType>();
3504 return TPT && !Type.hasQualifiers() &&
3505 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3506 }
3507
3508 case TemplateArgument::Expression: {
3509 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3510 if (!DRE || !DRE->getDecl())
3511 return false;
3512 const NonTypeTemplateParmDecl *NTTP =
3513 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3514 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3515 }
3516
3517 case TemplateArgument::Template:
3518 const TemplateTemplateParmDecl *TTP =
3519 dyn_cast_or_null<TemplateTemplateParmDecl>(
3520 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3521 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3522 }
3523 llvm_unreachable("unexpected kind of template argument");
3524}
3525
3526static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3527 ArrayRef<TemplateArgument> Args) {
3528 if (Params->size() != Args.size())
3529 return false;
3530
3531 unsigned Depth = Params->getDepth();
3532
3533 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3534 TemplateArgument Arg = Args[I];
3535
3536 // If the parameter is a pack expansion, the argument must be a pack
3537 // whose only element is a pack expansion.
3538 if (Params->getParam(I)->isParameterPack()) {
3539 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3540 !Arg.pack_begin()->isPackExpansion())
3541 return false;
3542 Arg = Arg.pack_begin()->getPackExpansionPattern();
3543 }
3544
3545 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3546 return false;
3547 }
3548
3549 return true;
3550}
3551
Richard Smith4b55a9c2014-04-17 03:29:33 +00003552/// Convert the parser's template argument list representation into our form.
3553static TemplateArgumentListInfo
3554makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3555 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3556 TemplateId.RAngleLoc);
3557 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3558 TemplateId.NumArgs);
3559 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3560 return TemplateArgs;
3561}
3562
Richard Smith0e617ec2016-12-27 07:56:27 +00003563template<typename PartialSpecDecl>
3564static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3565 if (Partial->getDeclContext()->isDependentContext())
3566 return;
3567
3568 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3569 // for non-substitution-failure issues?
3570 TemplateDeductionInfo Info(Partial->getLocation());
3571 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3572 return;
3573
3574 auto *Template = Partial->getSpecializedTemplate();
3575 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003576 diag::ext_partial_spec_not_more_specialized_than_primary)
3577 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003578
3579 if (Info.hasSFINAEDiagnostic()) {
3580 PartialDiagnosticAt Diag = {SourceLocation(),
3581 PartialDiagnostic::NullDiagnostic()};
3582 Info.takeSFINAEDiagnostic(Diag);
3583 SmallString<128> SFINAEArgString;
3584 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3585 S.Diag(Diag.first,
3586 diag::note_partial_spec_not_more_specialized_than_primary)
3587 << SFINAEArgString;
3588 }
3589
3590 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3591}
3592
Richard Smith4e05eaa2017-02-16 00:36:47 +00003593static void
3594noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3595 const llvm::SmallBitVector &DeducibleParams) {
3596 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3597 if (!DeducibleParams[I]) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00003598 NamedDecl *Param = TemplateParams->getParam(I);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003599 if (Param->getDeclName())
3600 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3601 << Param->getDeclName();
3602 else
3603 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3604 << "(anonymous)";
3605 }
3606 }
3607}
3608
3609
Richard Smith57aae072016-12-28 02:37:25 +00003610template<typename PartialSpecDecl>
3611static void checkTemplatePartialSpecialization(Sema &S,
3612 PartialSpecDecl *Partial) {
3613 // C++1z [temp.class.spec]p8: (DR1495)
3614 // - The specialization shall be more specialized than the primary
3615 // template (14.5.5.2).
3616 checkMoreSpecializedThanPrimary(S, Partial);
3617
3618 // C++ [temp.class.spec]p8: (DR1315)
3619 // - Each template-parameter shall appear at least once in the
3620 // template-id outside a non-deduced context.
3621 // C++1z [temp.class.spec.match]p3 (P0127R2)
3622 // If the template arguments of a partial specialization cannot be
3623 // deduced because of the structure of its template-parameter-list
3624 // and the template-id, the program is ill-formed.
3625 auto *TemplateParams = Partial->getTemplateParameters();
3626 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3627 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3628 TemplateParams->getDepth(), DeducibleParams);
3629
3630 if (!DeducibleParams.all()) {
3631 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3632 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3633 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3634 << (NumNonDeducible > 1)
3635 << SourceRange(Partial->getLocation(),
3636 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003637 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003638 }
3639}
3640
3641void Sema::CheckTemplatePartialSpecialization(
3642 ClassTemplatePartialSpecializationDecl *Partial) {
3643 checkTemplatePartialSpecialization(*this, Partial);
3644}
3645
3646void Sema::CheckTemplatePartialSpecialization(
3647 VarTemplatePartialSpecializationDecl *Partial) {
3648 checkTemplatePartialSpecialization(*this, Partial);
3649}
3650
Richard Smith4e05eaa2017-02-16 00:36:47 +00003651void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3652 // C++1z [temp.param]p11:
3653 // A template parameter of a deduction guide template that does not have a
3654 // default-argument shall be deducible from the parameter-type-list of the
3655 // deduction guide template.
3656 auto *TemplateParams = TD->getTemplateParameters();
3657 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3658 MarkDeducedTemplateParameters(TD, DeducibleParams);
3659 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3660 // A parameter pack is deducible (to an empty pack).
3661 auto *Param = TemplateParams->getParam(I);
3662 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3663 DeducibleParams[I] = true;
3664 }
3665
3666 if (!DeducibleParams.all()) {
3667 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3668 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3669 << (NumNonDeducible > 1);
3670 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3671 }
3672}
3673
Larisse Voufo39a1e502013-08-06 01:03:05 +00003674DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003675 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003676 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003677 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003678 // D must be variable template id.
Faisal Vali2ab8c152017-12-30 04:15:27 +00003679 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003680 "Variable template specialization is declared with a template it.");
3681
3682 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003683 TemplateArgumentListInfo TemplateArgs =
3684 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003685 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3686 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3687 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003688
Richard Smithbeef3452014-01-16 23:39:20 +00003689 TemplateName Name = TemplateId->Template.get();
3690
3691 // The template-id must name a variable template.
3692 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003693 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3694 if (!VarTemplate) {
3695 NamedDecl *FnTemplate;
3696 if (auto *OTS = Name.getAsOverloadedTemplate())
3697 FnTemplate = *OTS->begin();
3698 else
3699 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3700 if (FnTemplate)
3701 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3702 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003703 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3704 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003705 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003706
3707 // Check for unexpanded parameter packs in any of the template arguments.
3708 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3709 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3710 UPPC_PartialSpecialization))
3711 return true;
3712
3713 // Check that the template argument list is well-formed for this
3714 // template.
3715 SmallVector<TemplateArgument, 4> Converted;
3716 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3717 false, Converted))
3718 return true;
3719
Larisse Voufo39a1e502013-08-06 01:03:05 +00003720 // Find the variable template (partial) specialization declaration that
3721 // corresponds to these arguments.
3722 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003723 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3724 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003725 return true;
3726
Richard Smith57aae072016-12-28 02:37:25 +00003727 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3728 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003729 bool InstantiationDependent;
3730 if (!Name.isDependent() &&
3731 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003732 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003733 InstantiationDependent)) {
3734 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3735 << VarTemplate->getDeclName();
3736 IsPartialSpecialization = false;
3737 }
Richard Smith300e0c32013-09-24 04:49:23 +00003738
3739 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3740 Converted)) {
3741 // C++ [temp.class.spec]p9b3:
3742 //
3743 // -- The argument list of the specialization shall not be identical
3744 // to the implicit argument list of the primary template.
3745 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3746 << /*variable template*/ 1
3747 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3748 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3749 // FIXME: Recover from this by treating the declaration as a redeclaration
3750 // of the primary template.
3751 return true;
3752 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003753 }
3754
Craig Topperc3ec1492014-05-26 06:22:03 +00003755 void *InsertPos = nullptr;
3756 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003757
3758 if (IsPartialSpecialization)
3759 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003760 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003761 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003762 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003763
Craig Topperc3ec1492014-05-26 06:22:03 +00003764 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003765
3766 // Check whether we can declare a variable template specialization in
3767 // the current scope.
3768 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3769 TemplateNameLoc,
3770 IsPartialSpecialization))
3771 return true;
3772
3773 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3774 // Since the only prior variable template specialization with these
3775 // arguments was referenced but not declared, reuse that
3776 // declaration node as our own, updating its source location and
3777 // the list of outer template parameters to reflect our new declaration.
3778 Specialization = PrevDecl;
3779 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003780 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003781 } else if (IsPartialSpecialization) {
3782 // Create a new class template partial specialization declaration node.
3783 VarTemplatePartialSpecializationDecl *PrevPartial =
3784 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003785 VarTemplatePartialSpecializationDecl *Partial =
3786 VarTemplatePartialSpecializationDecl::Create(
3787 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3788 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003789 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003790
3791 if (!PrevPartial)
3792 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3793 Specialization = Partial;
3794
3795 // If we are providing an explicit specialization of a member variable
3796 // template specialization, make a note of that.
3797 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003798 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003799
Richard Smith57aae072016-12-28 02:37:25 +00003800 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003801 } else {
3802 // Create a new class template specialization declaration node for
3803 // this explicit specialization or friend declaration.
3804 Specialization = VarTemplateSpecializationDecl::Create(
3805 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003806 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003807 Specialization->setTemplateArgsInfo(TemplateArgs);
3808
3809 if (!PrevDecl)
3810 VarTemplate->AddSpecialization(Specialization, InsertPos);
3811 }
3812
3813 // C++ [temp.expl.spec]p6:
3814 // If a template, a member template or the member of a class template is
3815 // explicitly specialized then that specialization shall be declared
3816 // before the first use of that specialization that would cause an implicit
3817 // instantiation to take place, in every translation unit in which such a
3818 // use occurs; no diagnostic is required.
3819 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3820 bool Okay = false;
3821 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3822 // Is there any previous explicit specialization declaration?
3823 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3824 Okay = true;
3825 break;
3826 }
3827 }
3828
3829 if (!Okay) {
3830 SourceRange Range(TemplateNameLoc, RAngleLoc);
3831 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3832 << Name << Range;
3833
3834 Diag(PrevDecl->getPointOfInstantiation(),
3835 diag::note_instantiation_required_here)
3836 << (PrevDecl->getTemplateSpecializationKind() !=
3837 TSK_ImplicitInstantiation);
3838 return true;
3839 }
3840 }
3841
3842 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3843 Specialization->setLexicalDeclContext(CurContext);
3844
3845 // Add the specialization into its lexical context, so that it can
3846 // be seen when iterating through the list of declarations in that
3847 // context. However, specializations are not found by name lookup.
3848 CurContext->addDecl(Specialization);
3849
3850 // Note that this is an explicit specialization.
3851 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3852
3853 if (PrevDecl) {
3854 // Check that this isn't a redefinition of this specialization,
3855 // merging with previous declarations.
3856 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00003857 forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003858 PrevSpec.addDecl(PrevDecl);
3859 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003860 } else if (Specialization->isStaticDataMember() &&
3861 Specialization->isOutOfLine()) {
3862 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003863 }
3864
3865 // Link instantiations of static data members back to the template from
3866 // which they were instantiated.
3867 if (Specialization->isStaticDataMember())
3868 Specialization->setInstantiationOfStaticDataMember(
3869 VarTemplate->getTemplatedDecl(),
3870 Specialization->getSpecializationKind());
3871
3872 return Specialization;
3873}
3874
3875namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003876/// A partial specialization whose template arguments have matched
Larisse Voufo39a1e502013-08-06 01:03:05 +00003877/// a given template-id.
3878struct PartialSpecMatchResult {
3879 VarTemplatePartialSpecializationDecl *Partial;
3880 TemplateArgumentList *Args;
3881};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003882} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003883
3884DeclResult
3885Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3886 SourceLocation TemplateNameLoc,
3887 const TemplateArgumentListInfo &TemplateArgs) {
3888 assert(Template && "A variable template id without template?");
3889
3890 // Check that the template argument list is well-formed for this template.
3891 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003892 if (CheckTemplateArgumentList(
3893 Template, TemplateNameLoc,
3894 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003895 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003896 return true;
3897
3898 // Find the variable template specialization declaration that
3899 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003900 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003901 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003902 Converted, InsertPos)) {
3903 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003904 // If we already have a variable template specialization, return it.
3905 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003906 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003907
3908 // This is the first time we have referenced this variable template
3909 // specialization. Create the canonical declaration and add it to
3910 // the set of specializations, based on the closest partial specialization
3911 // that it represents. That is,
3912 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3913 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003914 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003915 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3916 bool AmbiguousPartialSpec = false;
3917 typedef PartialSpecMatchResult MatchResult;
3918 SmallVector<MatchResult, 4> Matched;
3919 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003920 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3921 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003922
3923 // 1. Attempt to find the closest partial specialization that this
3924 // specializes, if any.
3925 // If any of the template arguments is dependent, then this is probably
3926 // a placeholder for an incomplete declarative context; which must be
3927 // complete by instantiation time. Thus, do not search through the partial
3928 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003929 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3930 // Perhaps better after unification of DeduceTemplateArguments() and
3931 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003932 bool InstantiationDependent = false;
3933 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3934 TemplateArgs, InstantiationDependent)) {
3935
3936 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3937 Template->getPartialSpecializations(PartialSpecs);
3938
3939 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3940 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3941 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3942
3943 if (TemplateDeductionResult Result =
3944 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3945 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003946 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003947 FailedCandidates.addCandidate().set(
3948 DeclAccessPair::make(Template, AS_public), Partial,
3949 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003950 (void)Result;
3951 } else {
3952 Matched.push_back(PartialSpecMatchResult());
3953 Matched.back().Partial = Partial;
3954 Matched.back().Args = Info.take();
3955 }
3956 }
3957
Larisse Voufo39a1e502013-08-06 01:03:05 +00003958 if (Matched.size() >= 1) {
3959 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3960 if (Matched.size() == 1) {
3961 // -- If exactly one matching specialization is found, the
3962 // instantiation is generated from that specialization.
3963 // We don't need to do anything for this.
3964 } else {
3965 // -- If more than one matching specialization is found, the
3966 // partial order rules (14.5.4.2) are used to determine
3967 // whether one of the specializations is more specialized
3968 // than the others. If none of the specializations is more
3969 // specialized than all of the other matching
3970 // specializations, then the use of the variable template is
3971 // ambiguous and the program is ill-formed.
3972 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3973 PEnd = Matched.end();
3974 P != PEnd; ++P) {
3975 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3976 PointOfInstantiation) ==
3977 P->Partial)
3978 Best = P;
3979 }
3980
3981 // Determine if the best partial specialization is more specialized than
3982 // the others.
3983 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3984 PEnd = Matched.end();
3985 P != PEnd; ++P) {
3986 if (P != Best && getMoreSpecializedPartialSpecialization(
3987 P->Partial, Best->Partial,
3988 PointOfInstantiation) != Best->Partial) {
3989 AmbiguousPartialSpec = true;
3990 break;
3991 }
3992 }
3993 }
3994
3995 // Instantiate using the best variable template partial specialization.
3996 InstantiationPattern = Best->Partial;
3997 InstantiationArgs = Best->Args;
3998 } else {
3999 // -- If no match is found, the instantiation is generated
4000 // from the primary template.
4001 // InstantiationPattern = Template->getTemplatedDecl();
4002 }
4003 }
4004
Larisse Voufo39a1e502013-08-06 01:03:05 +00004005 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00004006 // Note that we do not instantiate a definition until we see an odr-use
4007 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00004008 // FIXME: LateAttrs et al.?
4009 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4010 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4011 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4012 if (!Decl)
4013 return true;
4014
4015 if (AmbiguousPartialSpec) {
4016 // Partial ordering did not produce a clear winner. Complain.
4017 Decl->setInvalidDecl();
4018 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4019 << Decl;
4020
4021 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00004022 for (MatchResult P : Matched)
4023 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4024 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4025 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004026 return true;
4027 }
4028
4029 if (VarTemplatePartialSpecializationDecl *D =
4030 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4031 Decl->setInstantiationOf(D, InstantiationArgs);
4032
Richard Smith6739a102016-05-05 00:56:12 +00004033 checkSpecializationVisibility(TemplateNameLoc, Decl);
4034
Larisse Voufo39a1e502013-08-06 01:03:05 +00004035 assert(Decl && "No variable template specialization?");
4036 return Decl;
4037}
4038
4039ExprResult
4040Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4041 const DeclarationNameInfo &NameInfo,
4042 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4043 const TemplateArgumentListInfo *TemplateArgs) {
4044
4045 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4046 *TemplateArgs);
4047 if (Decl.isInvalid())
4048 return ExprError();
4049
4050 VarDecl *Var = cast<VarDecl>(Decl.get());
4051 if (!Var->getTemplateSpecializationKind())
4052 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4053 NameInfo.getLoc());
4054
4055 // Build an ordinary singleton decl ref.
4056 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00004057 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004058}
4059
Richard Smithecad88d2018-04-26 01:08:00 +00004060void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4061 SourceLocation Loc) {
4062 Diag(Loc, diag::err_template_missing_args)
4063 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4064 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4065 Diag(TD->getLocation(), diag::note_template_decl_here)
4066 << TD->getTemplateParameters()->getSourceRange();
4067 }
4068}
4069
John McCalldadc5752010-08-24 06:29:42 +00004070ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004071 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00004072 LookupResult &R,
4073 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004074 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00004075 // FIXME: Can we do any checking at this point? I guess we could check the
4076 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00004077 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00004078 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00004079 // foo<int> could identify a single function unambiguously
4080 // This approach does NOT work, since f<int>(1);
4081 // gets resolved prior to resorting to overload resolution
4082 // i.e., template<class T> void f(double);
4083 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00004084
4085 // These should be filtered out by our callers.
4086 assert(!R.empty() && "empty lookup results when building templateid");
4087 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4088
Richard Smith04100942018-04-26 02:10:22 +00004089 // Non-function templates require a template argument list.
4090 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4091 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4092 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4093 return ExprError();
4094 }
4095 }
4096
Richard Smith0bf96f92018-04-25 22:58:55 +00004097 auto AnyDependentArguments = [&]() -> bool {
4098 bool InstantiationDependent;
4099 return TemplateArgs &&
4100 TemplateSpecializationType::anyDependentTemplateArguments(
4101 *TemplateArgs, InstantiationDependent);
4102 };
4103
Larisse Voufo39a1e502013-08-06 01:03:05 +00004104 // In C++1y, check variable template ids.
Richard Smith0bf96f92018-04-25 22:58:55 +00004105 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
Richard Smithd7d11ef2014-02-03 20:09:56 +00004106 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4107 R.getAsSingle<VarTemplateDecl>(),
4108 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004109 }
4110
John McCall58cc69d2010-01-27 01:50:18 +00004111 // We don't want lookup warnings at this point.
4112 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004113
John McCalle66edc12009-11-24 19:00:30 +00004114 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00004115 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00004116 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004117 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004118 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00004120 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00004121
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004122 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00004123}
4124
John McCalle66edc12009-11-24 19:00:30 +00004125// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00004126ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004127Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004128 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004129 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004130 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004131
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004132 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00004133 DeclContext *DC;
4134 if (!(DC = computeDeclContext(SS, false)) ||
4135 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00004136 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00004137 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004138
Douglas Gregor786123d2010-05-21 23:18:07 +00004139 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004140 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +00004141 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4142 /*Entering*/false, MemberOfUnknownSpecialization,
4143 TemplateKWLoc))
4144 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004145
John McCalle66edc12009-11-24 19:00:30 +00004146 if (R.isAmbiguous())
4147 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004148
John McCalle66edc12009-11-24 19:00:30 +00004149 if (R.empty()) {
Richard Smith79810042018-05-11 02:43:08 +00004150 Diag(NameInfo.getLoc(), diag::err_no_member)
4151 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004152 return ExprError();
4153 }
4154
4155 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004156 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00004157 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00004158 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004159 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4160 return ExprError();
4161 }
4162
Abramo Bagnara7945c982012-01-27 09:46:47 +00004163 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00004164}
4165
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004166/// Form a dependent template name.
Douglas Gregorb67535d2009-03-31 00:43:58 +00004167///
4168/// This action forms a dependent template name given the template
4169/// name and its (presumably dependent) scope specifier. For
4170/// example, given "MetaFun::template apply", the scope specifier \p
4171/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4172/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00004174 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004175 SourceLocation TemplateKWLoc,
Richard Smithc08b6932018-04-27 02:00:13 +00004176 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00004177 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00004178 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00004179 TemplateTy &Result,
4180 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004181 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4182 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004183 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004184 diag::warn_cxx98_compat_template_outside_of_template :
4185 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004186 << FixItHint::CreateRemoval(TemplateKWLoc);
4187
Craig Topperc3ec1492014-05-26 06:22:03 +00004188 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00004189 if (SS.isSet())
4190 LookupCtx = computeDeclContext(SS, EnteringContext);
4191 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00004192 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00004193 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00004194 // C++0x [temp.names]p5:
4195 // If a name prefixed by the keyword template is not the name of
4196 // a template, the program is ill-formed. [Note: the keyword
4197 // template may not be applied to non-template members of class
4198 // templates. -end note ] [ Note: as is the case with the
4199 // typename prefix, the template prefix is allowed in cases
4200 // where it is not strictly necessary; i.e., when the
4201 // nested-name-specifier or the expression on the left of the ->
4202 // or . is not dependent on a template-parameter, or the use
4203 // does not appear in the scope of a template. -end note]
4204 //
4205 // Note: C++03 was more strict here, because it banned the use of
4206 // the "template" keyword prior to a template-name that was not a
4207 // dependent name. C++ DR468 relaxed this requirement (the
4208 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00004209 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00004210 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00004211 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00004212 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00004213 MemberOfUnknownSpecialization);
Richard Smith79810042018-05-11 02:43:08 +00004214 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
Douglas Gregorbb119652010-06-16 23:00:59 +00004215 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00004216 } else if (TNK == TNK_Non_template) {
Richard Smith79810042018-05-11 02:43:08 +00004217 // Do the lookup again to determine if this is a "nothing found" case or
4218 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4219 // need to do this.
4220 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4221 LookupResult R(*this, DNI.getName(), Name.getLocStart(),
4222 LookupOrdinaryName);
4223 bool MOUS;
4224 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
4225 MOUS, TemplateKWLoc))
4226 Diag(Name.getLocStart(), diag::err_no_member)
4227 << DNI.getName() << LookupCtx << SS.getRange();
Douglas Gregorbb119652010-06-16 23:00:59 +00004228 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00004229 } else {
4230 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00004231 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4232 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
Faisal Vali2ab8c152017-12-30 04:15:27 +00004233 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4234 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
Richard Smithfd3dae02017-01-20 00:20:39 +00004235 // C++14 [class.qual]p2:
4236 // In a lookup in which function names are not ignored and the
4237 // nested-name-specifier nominates a class C, if the name specified
4238 // [...] is the injected-class-name of C, [...] the name is instead
4239 // considered to name the constructor
4240 //
4241 // We don't get here if naming the constructor would be valid, so we
4242 // just reject immediately and recover by treating the
4243 // injected-class-name as naming the template.
4244 Diag(Name.getLocStart(),
4245 diag::ext_out_of_line_qualified_id_type_names_constructor)
4246 << Name.Identifier << 0 /*injected-class-name used as template name*/
4247 << 1 /*'template' keyword was used*/;
4248 }
Douglas Gregorbb119652010-06-16 23:00:59 +00004249 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004250 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00004251 }
4252
Aaron Ballman4a979672014-01-03 13:56:08 +00004253 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004254
Douglas Gregor3cf81312009-11-03 23:16:33 +00004255 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00004256 case UnqualifiedIdKind::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00004258 Name.Identifier));
4259 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004260
Faisal Vali2ab8c152017-12-30 04:15:27 +00004261 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00004262 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00004263 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00004264 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00004265
Faisal Vali2ab8c152017-12-30 04:15:27 +00004266 case UnqualifiedIdKind::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00004267 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00004268
Douglas Gregor3cf81312009-11-03 23:16:33 +00004269 default:
4270 break;
4271 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004272
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004273 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00004274 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004275 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00004276 << Name.getSourceRange()
4277 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004278 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004279}
4280
Mike Stump11289f42009-09-09 15:08:12 +00004281bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004282 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004283 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00004284 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00004285 QualType ArgType;
4286 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00004287
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004288 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004289 switch(Arg.getKind()) {
4290 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004291 // C++ [temp.arg.type]p1:
4292 // A template-argument for a template-parameter which is a
4293 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00004294 ArgType = Arg.getAsType();
4295 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004296 break;
Richard Smith77a9c602018-02-28 03:02:23 +00004297 case TemplateArgument::Template:
4298 case TemplateArgument::TemplateExpansion: {
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004299 // We have a template type parameter but the template argument
4300 // is a template without any arguments.
4301 SourceRange SR = AL.getSourceRange();
Richard Smith77a9c602018-02-28 03:02:23 +00004302 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
Richard Smithecad88d2018-04-26 01:08:00 +00004303 diagnoseMissingTemplateArguments(Name, SR.getEnd());
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004304 return true;
4305 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004306 case TemplateArgument::Expression: {
4307 // We have a template type parameter but the template argument is an
4308 // expression; see if maybe it is missing the "typename" keyword.
4309 CXXScopeSpec SS;
4310 DeclarationNameInfo NameInfo;
4311
4312 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4313 SS.Adopt(ArgExpr->getQualifierLoc());
4314 NameInfo = ArgExpr->getNameInfo();
4315 } else if (DependentScopeDeclRefExpr *ArgExpr =
4316 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4317 SS.Adopt(ArgExpr->getQualifierLoc());
4318 NameInfo = ArgExpr->getNameInfo();
4319 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4320 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004321 if (ArgExpr->isImplicitAccess()) {
4322 SS.Adopt(ArgExpr->getQualifierLoc());
4323 NameInfo = ArgExpr->getMemberNameInfo();
4324 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004325 }
4326
Reid Kleckner377c1592014-06-10 23:29:48 +00004327 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004328 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4329 LookupParsedName(Result, CurScope, &SS);
4330
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004331 if (Result.getAsSingle<TypeDecl>() ||
4332 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00004333 LookupResult::NotFoundInCurrentInstantiation) {
4334 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004335 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00004336 Diag(Loc, getLangOpts().MSVCCompat
4337 ? diag::ext_ms_template_type_arg_missing_typename
4338 : diag::err_template_arg_must_be_type_suggest)
4339 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004340 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00004341
4342 // Recover by synthesizing a type using the location information that we
4343 // already have.
4344 ArgType =
4345 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4346 TypeLocBuilder TLB;
4347 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4348 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4349 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4350 TL.setNameLoc(NameInfo.getLoc());
4351 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4352
4353 // Overwrite our input TemplateArgumentLoc so that we can recover
4354 // properly.
4355 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4356 TemplateArgumentLocInfo(TSI));
4357
4358 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004359 }
4360 }
4361 // fallthrough
Galina Kistanova3779cb32017-06-07 06:25:05 +00004362 LLVM_FALLTHROUGH;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004363 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004364 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004365 // We have a template type parameter but the template argument
4366 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00004367 SourceRange SR = AL.getSourceRange();
4368 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004369 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00004370
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004371 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004372 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004373 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004374
Reid Kleckner377c1592014-06-10 23:29:48 +00004375 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004376 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004377
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004378 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00004379 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004380
Douglas Gregore46db902011-06-17 22:11:49 +00004381 // Objective-C ARC:
4382 // If an explicitly-specified template argument type is a lifetime type
4383 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004384 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00004385 ArgType->isObjCLifetimeType() &&
4386 !ArgType.getObjCLifetime()) {
4387 Qualifiers Qs;
4388 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4389 ArgType = Context.getQualifiedType(ArgType, Qs);
4390 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004391
Douglas Gregore46db902011-06-17 22:11:49 +00004392 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004393 return false;
4394}
4395
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004396/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004397/// the given template type parameter.
4398///
4399/// \param SemaRef the semantic analysis object for which we are performing
4400/// the substitution.
4401///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004403/// for.
4404///
4405/// \param TemplateLoc the location of the template name that started the
4406/// template-id we are checking.
4407///
4408/// \param RAngleLoc the location of the right angle bracket ('>') that
4409/// terminates the template-id.
4410///
4411/// \param Param the template template parameter whose default we are
4412/// substituting into.
4413///
4414/// \param Converted the list of template arguments provided for template
4415/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004416/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00004417static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004418SubstDefaultTemplateArgument(Sema &SemaRef,
4419 TemplateDecl *Template,
4420 SourceLocation TemplateLoc,
4421 SourceLocation RAngleLoc,
4422 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00004423 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00004424 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004425
4426 // If the argument type is dependent, instantiate it now based
4427 // on the previously-computed template arguments.
4428 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004429 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004430 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004431 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004432 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004433 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004434
David Majnemer8b622692016-07-03 21:17:51 +00004435 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004436
4437 // Only substitute for the innermost template argument list.
4438 MultiLevelTemplateArgumentList TemplateArgLists;
4439 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4440 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4441 TemplateArgLists.addOuterTemplateArguments(None);
4442
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004443 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004444 ArgType =
4445 SemaRef.SubstType(ArgType, TemplateArgLists,
4446 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004447 }
4448
4449 return ArgType;
4450}
4451
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004452/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004453/// the given non-type template parameter.
4454///
4455/// \param SemaRef the semantic analysis object for which we are performing
4456/// the substitution.
4457///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004458/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004459/// for.
4460///
4461/// \param TemplateLoc the location of the template name that started the
4462/// template-id we are checking.
4463///
4464/// \param RAngleLoc the location of the right angle bracket ('>') that
4465/// terminates the template-id.
4466///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004467/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004468/// substituting into.
4469///
4470/// \param Converted the list of template arguments provided for template
4471/// parameters that precede \p Param in the template parameter list.
4472///
4473/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004474static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004475SubstDefaultTemplateArgument(Sema &SemaRef,
4476 TemplateDecl *Template,
4477 SourceLocation TemplateLoc,
4478 SourceLocation RAngleLoc,
4479 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004480 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004481 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004482 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004483 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004484 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004485 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004486
David Majnemer8b622692016-07-03 21:17:51 +00004487 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004488
4489 // Only substitute for the innermost template argument list.
4490 MultiLevelTemplateArgumentList TemplateArgLists;
4491 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4492 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4493 TemplateArgLists.addOuterTemplateArguments(None);
4494
Faisal Valid143a0c2017-04-01 21:30:49 +00004495 EnterExpressionEvaluationContext ConstantEvaluated(
4496 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004497 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004498}
4499
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004500/// Substitute template arguments into the default template argument for
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004501/// the given template template parameter.
4502///
4503/// \param SemaRef the semantic analysis object for which we are performing
4504/// the substitution.
4505///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004507/// for.
4508///
4509/// \param TemplateLoc the location of the template name that started the
4510/// template-id we are checking.
4511///
4512/// \param RAngleLoc the location of the right angle bracket ('>') that
4513/// terminates the template-id.
4514///
4515/// \param Param the template template parameter whose default we are
4516/// substituting into.
4517///
4518/// \param Converted the list of template arguments provided for template
4519/// parameters that precede \p Param in the template parameter list.
4520///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004521/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004522/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004523///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004524/// \returns the substituted template argument, or NULL if an error occurred.
4525static TemplateName
4526SubstDefaultTemplateArgument(Sema &SemaRef,
4527 TemplateDecl *Template,
4528 SourceLocation TemplateLoc,
4529 SourceLocation RAngleLoc,
4530 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004531 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004532 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004533 Sema::InstantiatingTemplate Inst(
4534 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4535 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004536 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004537 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004538
David Majnemer8b622692016-07-03 21:17:51 +00004539 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004540
4541 // Only substitute for the innermost template argument list.
4542 MultiLevelTemplateArgumentList TemplateArgLists;
4543 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4544 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4545 TemplateArgLists.addOuterTemplateArguments(None);
4546
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004547 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004548 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004549 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004550 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004551 QualifierLoc =
4552 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004553 if (!QualifierLoc)
4554 return TemplateName();
4555 }
David Majnemer89189202013-08-28 23:48:32 +00004556
4557 return SemaRef.SubstTemplateName(
4558 QualifierLoc,
4559 Param->getDefaultArgument().getArgument().getAsTemplate(),
4560 Param->getDefaultArgument().getTemplateNameLoc(),
4561 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004562}
4563
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004564/// If the given template parameter has a default template
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004565/// argument, substitute into that default template argument and
4566/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004567TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004568Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4569 SourceLocation TemplateLoc,
4570 SourceLocation RAngleLoc,
4571 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004572 SmallVectorImpl<TemplateArgument>
4573 &Converted,
4574 bool &HasDefaultArg) {
4575 HasDefaultArg = false;
4576
4577 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004578 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004579 return TemplateArgumentLoc();
4580
Richard Smithc87b9382013-07-04 01:01:24 +00004581 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004582 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004583 TemplateLoc,
4584 RAngleLoc,
4585 TypeParm,
4586 Converted);
4587 if (DI)
4588 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4589
4590 return TemplateArgumentLoc();
4591 }
4592
4593 if (NonTypeTemplateParmDecl *NonTypeParm
4594 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004595 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004596 return TemplateArgumentLoc();
4597
Richard Smithc87b9382013-07-04 01:01:24 +00004598 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004599 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004600 TemplateLoc,
4601 RAngleLoc,
4602 NonTypeParm,
4603 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004604 if (Arg.isInvalid())
4605 return TemplateArgumentLoc();
4606
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004607 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004608 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4609 }
4610
4611 TemplateTemplateParmDecl *TempTempParm
4612 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004613 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004614 return TemplateArgumentLoc();
4615
Richard Smithc87b9382013-07-04 01:01:24 +00004616 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004617 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004618 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004619 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004620 RAngleLoc,
4621 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004622 Converted,
4623 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004624 if (TName.isNull())
4625 return TemplateArgumentLoc();
4626
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004627 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004628 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004629 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4630}
4631
Richard Smith11255ec2017-01-18 19:19:22 +00004632/// Convert a template-argument that we parsed as a type into a template, if
4633/// possible. C++ permits injected-class-names to perform dual service as
4634/// template template arguments and as template type arguments.
4635static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4636 // Extract and step over any surrounding nested-name-specifier.
4637 NestedNameSpecifierLoc QualLoc;
4638 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4639 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4640 return TemplateArgumentLoc();
4641
4642 QualLoc = ETLoc.getQualifierLoc();
4643 TLoc = ETLoc.getNamedTypeLoc();
4644 }
4645
4646 // If this type was written as an injected-class-name, it can be used as a
4647 // template template argument.
4648 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4649 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4650 QualLoc, InjLoc.getNameLoc());
4651
4652 // If this type was written as an injected-class-name, it may have been
4653 // converted to a RecordType during instantiation. If the RecordType is
4654 // *not* wrapped in a TemplateSpecializationType and denotes a class
4655 // template specialization, it must have come from an injected-class-name.
4656 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4657 if (auto *CTSD =
4658 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4659 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4660 QualLoc, RecLoc.getNameLoc());
4661
4662 return TemplateArgumentLoc();
4663}
4664
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004665/// Check that the given template argument corresponds to the given
Douglas Gregorda0fb532009-11-11 19:31:23 +00004666/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004667///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004669/// checked.
4670///
Richard Trieu15b66532015-01-24 02:48:32 +00004671/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004672///
4673/// \param Template The template in which the template argument resides.
4674///
4675/// \param TemplateLoc The location of the template name for the template
4676/// whose argument list we're matching.
4677///
4678/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4679/// the template argument list.
4680///
4681/// \param ArgumentPackIndex The index into the argument pack where this
4682/// argument will be placed. Only valid if the parameter is a parameter pack.
4683///
4684/// \param Converted The checked, converted argument will be added to the
4685/// end of this small vector.
4686///
4687/// \param CTAK Describes how we arrived at this particular template argument:
4688/// explicitly written, deduced, etc.
4689///
4690/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004691bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004692 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004693 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004694 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004695 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004696 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004697 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004698 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004699 // Check template type parameters.
4700 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004701 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702
Douglas Gregoreebed722009-11-11 19:41:09 +00004703 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004704 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004705 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004706 // with the template arguments we've seen thus far. But if the
4707 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004708 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004709 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4710 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004711
Richard Smith5d331022018-03-08 01:07:33 +00004712 // FIXME: Do we need to substitute into parameters here if they're
4713 // instantiation-dependent but not dependent?
Peter Collingbourne01687632010-12-10 17:08:53 +00004714 if (NTTPType->isDependentType() &&
4715 !isa<TemplateTemplateParmDecl>(Template) &&
4716 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004717 // Do substitution on the type of the non-type template parameter.
4718 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004719 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004720 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004721 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004722 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004723
4724 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004725 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004726 NTTPType = SubstType(NTTPType,
4727 MultiLevelTemplateArgumentList(TemplateArgs),
4728 NTTP->getLocation(),
4729 NTTP->getDeclName());
4730 // If that worked, check the non-type template parameter type
4731 // for validity.
4732 if (!NTTPType.isNull())
4733 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4734 NTTP->getLocation());
4735 if (NTTPType.isNull())
4736 return true;
4737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004738
Douglas Gregorda0fb532009-11-11 19:31:23 +00004739 switch (Arg.getArgument().getKind()) {
4740 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004741 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004742
Douglas Gregorda0fb532009-11-11 19:31:23 +00004743 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004744 TemplateArgument Result;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004745 unsigned CurSFINAEErrors = NumSFINAEErrors;
John Wiegley01296292011-04-08 18:41:53 +00004746 ExprResult Res =
4747 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4748 Result, CTAK);
4749 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004750 return true;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004751 // If the current template argument causes an error, give up now.
4752 if (CurSFINAEErrors < NumSFINAEErrors)
4753 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004754
Richard Trieu15b66532015-01-24 02:48:32 +00004755 // If the resulting expression is new, then use it in place of the
4756 // old expression in the template argument.
4757 if (Res.get() != Arg.getArgument().getAsExpr()) {
4758 TemplateArgument TA(Res.get());
4759 Arg = TemplateArgumentLoc(TA, Res.get());
4760 }
4761
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004762 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004763 break;
4764 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765
Douglas Gregorda0fb532009-11-11 19:31:23 +00004766 case TemplateArgument::Declaration:
4767 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004768 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004769 // We've already checked this template argument, so just copy
4770 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004771 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004772 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004773
Douglas Gregorda0fb532009-11-11 19:31:23 +00004774 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004775 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004776 // We were given a template template argument. It may not be ill-formed;
4777 // see below.
4778 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004779 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4780 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004781 // We have a template argument such as \c T::template X, which we
4782 // parsed as a template template argument. However, since we now
4783 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004784 // template name into an expression.
4785
4786 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4787 Arg.getTemplateNameLoc());
4788
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004789 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004790 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004791 // FIXME: the template-template arg was a DependentTemplateName,
4792 // so it was provided with a template keyword. However, its source
4793 // location is not stored in the template argument structure.
4794 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004795 ExprResult E = DependentScopeDeclRefExpr::Create(
4796 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4797 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004798
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004799 // If we parsed the template argument as a pack expansion, create a
4800 // pack expansion expression.
4801 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004802 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004803 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004804 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004806
Douglas Gregorda0fb532009-11-11 19:31:23 +00004807 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004808 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004809 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004810 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004811
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004812 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004813 break;
4814 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004815
Douglas Gregorda0fb532009-11-11 19:31:23 +00004816 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004817 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004818 // therefore cannot be a non-type template argument.
4819 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4820 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004821
Douglas Gregorda0fb532009-11-11 19:31:23 +00004822 Diag(Param->getLocation(), diag::note_template_param_here);
4823 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004824
Douglas Gregorda0fb532009-11-11 19:31:23 +00004825 case TemplateArgument::Type: {
4826 // We have a non-type template parameter but the template
4827 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004828
Douglas Gregorda0fb532009-11-11 19:31:23 +00004829 // C++ [temp.arg]p2:
4830 // In a template-argument, an ambiguity between a type-id and
4831 // an expression is resolved to a type-id, regardless of the
4832 // form of the corresponding template-parameter.
4833 //
4834 // We warn specifically about this case, since it can be rather
4835 // confusing for users.
4836 QualType T = Arg.getArgument().getAsType();
4837 SourceRange SR = Arg.getSourceRange();
4838 if (T->isFunctionType())
4839 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4840 else
4841 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4842 Diag(Param->getLocation(), diag::note_template_param_here);
4843 return true;
4844 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004845
Douglas Gregorda0fb532009-11-11 19:31:23 +00004846 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004847 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004848 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004849
Douglas Gregorda0fb532009-11-11 19:31:23 +00004850 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004851 }
4852
4853
Douglas Gregorda0fb532009-11-11 19:31:23 +00004854 // Check template template parameters.
4855 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004856
Richard Smith5d331022018-03-08 01:07:33 +00004857 TemplateParameterList *Params = TempParm->getTemplateParameters();
4858 if (TempParm->isExpandedParameterPack())
4859 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
4860
Douglas Gregorda0fb532009-11-11 19:31:23 +00004861 // Substitute into the template parameter list of the template
4862 // template parameter, since previously-supplied template arguments
4863 // may appear within the template template parameter.
Richard Smith5d331022018-03-08 01:07:33 +00004864 //
4865 // FIXME: Skip this if the parameters aren't instantiation-dependent.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004866 {
4867 // Set up a template instantiation context.
4868 LocalInstantiationScope Scope(*this);
4869 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004870 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004871 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004872 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004873 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004874
David Majnemer8b622692016-07-03 21:17:51 +00004875 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Richard Smith5d331022018-03-08 01:07:33 +00004876 Params = SubstTemplateParams(Params, CurContext,
4877 MultiLevelTemplateArgumentList(TemplateArgs));
4878 if (!Params)
Douglas Gregorda0fb532009-11-11 19:31:23 +00004879 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004881
Richard Smith11255ec2017-01-18 19:19:22 +00004882 // C++1z [temp.local]p1: (DR1004)
4883 // When [the injected-class-name] is used [...] as a template-argument for
4884 // a template template-parameter [...] it refers to the class template
4885 // itself.
4886 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4887 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4888 Arg.getTypeSourceInfo()->getTypeLoc());
4889 if (!ConvertedArg.getArgument().isNull())
4890 Arg = ConvertedArg;
4891 }
4892
Douglas Gregorda0fb532009-11-11 19:31:23 +00004893 switch (Arg.getArgument().getKind()) {
4894 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004895 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004896
Douglas Gregorda0fb532009-11-11 19:31:23 +00004897 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004898 case TemplateArgument::TemplateExpansion:
Richard Smith5d331022018-03-08 01:07:33 +00004899 if (CheckTemplateTemplateArgument(Params, Arg))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004900 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004901
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004902 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004903 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004904
Douglas Gregorda0fb532009-11-11 19:31:23 +00004905 case TemplateArgument::Expression:
4906 case TemplateArgument::Type:
4907 // We have a template template parameter but the template
4908 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004909 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004910 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004911 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004912
Douglas Gregorda0fb532009-11-11 19:31:23 +00004913 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004914 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004915 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004916 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004917 case TemplateArgument::NullPtr:
4918 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004919
Douglas Gregorda0fb532009-11-11 19:31:23 +00004920 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004921 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004923
Douglas Gregorda0fb532009-11-11 19:31:23 +00004924 return false;
4925}
4926
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004927/// Check whether the template parameter is a pack expansion, and if so,
Richard Smith1fde8ec2012-09-07 02:06:42 +00004928/// determine the number of parameters produced by that expansion. For instance:
4929///
4930/// \code
4931/// template<typename ...Ts> struct A {
4932/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4933/// };
4934/// \endcode
4935///
4936/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4937/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004938static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004939 if (NonTypeTemplateParmDecl *NTTP
4940 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4941 if (NTTP->isExpandedParameterPack())
4942 return NTTP->getNumExpansionTypes();
4943 }
4944
4945 if (TemplateTemplateParmDecl *TTP
4946 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4947 if (TTP->isExpandedParameterPack())
4948 return TTP->getNumExpansionTemplateParameters();
4949 }
4950
David Blaikie7a30dc52013-02-21 01:47:18 +00004951 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00004952}
4953
Richard Smith35c1df52015-06-17 20:16:32 +00004954/// Diagnose a missing template argument.
4955template<typename TemplateParmDecl>
4956static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4957 TemplateDecl *TD,
4958 const TemplateParmDecl *D,
4959 TemplateArgumentListInfo &Args) {
4960 // Dig out the most recent declaration of the template parameter; there may be
4961 // declarations of the template that are more recent than TD.
4962 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4963 ->getTemplateParameters()
4964 ->getParam(D->getIndex()));
4965
4966 // If there's a default argument that's not visible, diagnose that we're
4967 // missing a module import.
4968 llvm::SmallVector<Module*, 8> Modules;
4969 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4970 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4971 D->getDefaultArgumentLoc(), Modules,
4972 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00004973 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00004974 return true;
4975 }
4976
4977 // FIXME: If there's a more recent default argument that *is* visible,
4978 // diagnose that it was declared too late.
4979
Richard Smith4a8f3512018-07-19 19:00:37 +00004980 TemplateParameterList *Params = TD->getTemplateParameters();
4981
4982 S.Diag(Loc, diag::err_template_arg_list_different_arity)
4983 << /*not enough args*/0
4984 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
4985 << TD;
4986 S.Diag(TD->getLocation(), diag::note_template_decl_here)
4987 << Params->getSourceRange();
4988 return true;
Richard Smith35c1df52015-06-17 20:16:32 +00004989}
4990
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004991/// Check that the given template argument list is well-formed
Douglas Gregord32e0282009-02-09 23:23:08 +00004992/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00004993bool Sema::CheckTemplateArgumentList(
4994 TemplateDecl *Template, SourceLocation TemplateLoc,
4995 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4996 SmallVectorImpl<TemplateArgument> &Converted,
4997 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00004998 // Make a copy of the template arguments for processing. Only make the
4999 // changes at the end when successful in matching the arguments to the
5000 // template.
5001 TemplateArgumentListInfo NewArgs = TemplateArgs;
5002
Erich Keaneaf0795b2017-10-24 01:39:56 +00005003 // Make sure we get the template parameter list from the most
5004 // recentdeclaration, since that is the only one that has is guaranteed to
5005 // have all the default template argument information.
5006 TemplateParameterList *Params =
5007 cast<TemplateDecl>(Template->getMostRecentDecl())
5008 ->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00005009
Richard Trieu15b66532015-01-24 02:48:32 +00005010 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00005011
Mike Stump11289f42009-09-09 15:08:12 +00005012 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00005013 // [...] The type and form of each template-argument specified in
5014 // a template-id shall match the type and form specified for the
5015 // corresponding parameter declared by the template in its
5016 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00005017 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005018 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00005019 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00005020 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00005021 for (TemplateParameterList::iterator Param = Params->begin(),
5022 ParamEnd = Params->end();
5023 Param != ParamEnd; /* increment in loop */) {
5024 // If we have an expanded parameter pack, make sure we don't have too
5025 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00005026 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005027 if (*Expansions == ArgumentPack.size()) {
5028 // We're done with this parameter pack. Pack up its arguments and add
5029 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00005030 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00005031 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005032 ArgumentPack.clear();
5033
Richard Smith1fde8ec2012-09-07 02:06:42 +00005034 // This argument is assigned to the next parameter.
5035 ++Param;
5036 continue;
5037 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5038 // Not enough arguments for this parameter pack.
5039 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
Richard Smith4a8f3512018-07-19 19:00:37 +00005040 << /*not enough args*/0
Richard Smith0c062b42017-01-14 02:19:59 +00005041 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00005042 << Template;
5043 Diag(Template->getLocation(), diag::note_template_decl_here)
5044 << Params->getSourceRange();
5045 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005046 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005048
Richard Smith1fde8ec2012-09-07 02:06:42 +00005049 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00005050 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00005051 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005052 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005053 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00005054 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005055
Richard Smith96d71c32014-11-12 23:38:38 +00005056 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00005057 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00005058 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5059 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00005060 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00005061 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00005062 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00005063 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00005064 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00005065 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00005066 Diag((*Param)->getLocation(), diag::note_template_param_here);
5067 return true;
5068 }
5069
Richard Smith1fde8ec2012-09-07 02:06:42 +00005070 // We're now done with this argument.
5071 ++ArgIdx;
5072
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005073 if ((*Param)->isTemplateParameterPack()) {
5074 // The template parameter was a template parameter pack, so take the
5075 // deduced argument and place it on the argument pack. Note that we
5076 // stay on the same template parameter so that we can deduce more
5077 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00005078 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005079 } else {
5080 // Move to the next template parameter.
5081 ++Param;
5082 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005083
Richard Smith96d71c32014-11-12 23:38:38 +00005084 // If we just saw a pack expansion into a non-pack, then directly convert
5085 // the remaining arguments, because we don't know what parameters they'll
5086 // match up with.
5087 if (PackExpansionIntoNonPack) {
5088 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005089 // If we were part way through filling in an expanded parameter pack,
5090 // fall back to just producing individual arguments.
5091 Converted.insert(Converted.end(),
5092 ArgumentPack.begin(), ArgumentPack.end());
5093 ArgumentPack.clear();
5094 }
5095
5096 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00005097 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00005098 ++ArgIdx;
5099 }
5100
Richard Smith1fde8ec2012-09-07 02:06:42 +00005101 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00005102 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005103
Douglas Gregor84d49a22009-11-11 21:54:23 +00005104 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005106
Douglas Gregor2f157c92011-06-03 02:59:40 +00005107 // If we're checking a partial template argument list, we're done.
5108 if (PartialTemplateArgs) {
5109 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00005110 Converted.push_back(
5111 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5112
Richard Smith1fde8ec2012-09-07 02:06:42 +00005113 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00005114 }
5115
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005116 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005117 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00005118 if ((*Param)->isTemplateParameterPack()) {
5119 assert(!getExpandedPackSize(*Param) &&
5120 "Should have dealt with this already");
5121
5122 // A non-expanded parameter pack before the end of the parameter list
5123 // only occurs for an ill-formed template parameter list, unless we've
5124 // got a partial argument list for a function template, so just bail out.
5125 if (Param + 1 != ParamEnd)
5126 return true;
5127
Benjamin Kramercce63472015-08-05 09:40:22 +00005128 Converted.push_back(
5129 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005130 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00005131
5132 ++Param;
5133 continue;
5134 }
5135
Douglas Gregor8e072612012-02-03 07:34:46 +00005136 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00005137 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005138
Douglas Gregor84d49a22009-11-11 21:54:23 +00005139 // Retrieve the default template argument from the template
5140 // parameter. For each kind of template parameter, we substitute the
5141 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005142 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00005143 // the default argument.
5144 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005145 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005146 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5147 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005148
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005149 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005150 Template,
5151 TemplateLoc,
5152 RAngleLoc,
5153 TTP,
5154 Converted);
5155 if (!ArgType)
5156 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005157
Douglas Gregor84d49a22009-11-11 21:54:23 +00005158 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5159 ArgType);
5160 } else if (NonTypeTemplateParmDecl *NTTP
5161 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005162 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005163 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5164 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005165
John McCalldadc5752010-08-24 06:29:42 +00005166 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005167 TemplateLoc,
5168 RAngleLoc,
5169 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005170 Converted);
5171 if (E.isInvalid())
5172 return true;
5173
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005174 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00005175 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5176 } else {
5177 TemplateTemplateParmDecl *TempParm
5178 = cast<TemplateTemplateParmDecl>(*Param);
5179
Richard Smith95d83952015-06-10 20:36:34 +00005180 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00005181 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5182 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005183
Douglas Gregordf846d12011-03-02 18:46:51 +00005184 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00005185 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005186 TemplateLoc,
5187 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005188 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00005189 Converted,
5190 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005191 if (Name.isNull())
5192 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005193
Douglas Gregor9d802122011-03-02 17:09:35 +00005194 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5195 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00005196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005197
Douglas Gregor84d49a22009-11-11 21:54:23 +00005198 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00005199 // the default template argument. We're not actually instantiating a
5200 // template here, we just create this object to put a note into the
5201 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00005202 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5203 SourceRange(TemplateLoc, RAngleLoc));
5204 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005205 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005206
Douglas Gregor84d49a22009-11-11 21:54:23 +00005207 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00005208 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005209 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005210 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005211
Richard Trieu15b66532015-01-24 02:48:32 +00005212 // Core issue 150 (assumed resolution): if this is a template template
5213 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00005214 // template definition.
5215 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00005216 NewArgs.addArgument(Arg);
5217
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005218 // Move to the next template parameter and argument.
5219 ++Param;
5220 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00005221 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005222
Richard Smith07f79912014-06-06 16:00:50 +00005223 // If we're performing a partial argument substitution, allow any trailing
5224 // pack expansions; they might be empty. This can happen even if
5225 // PartialTemplateArgs is false (the list of arguments is complete but
5226 // still dependent).
5227 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5228 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00005229 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5230 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00005231 }
5232
Douglas Gregor8e072612012-02-03 07:34:46 +00005233 // If we have any leftover arguments, then there were too many arguments.
5234 // Complain and fail.
Richard Smith4a8f3512018-07-19 19:00:37 +00005235 if (ArgIdx < NumArgs) {
5236 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5237 << /*too many args*/1
5238 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5239 << Template
5240 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5241 Diag(Template->getLocation(), diag::note_template_decl_here)
5242 << Params->getSourceRange();
5243 return true;
5244 }
Richard Trieu15b66532015-01-24 02:48:32 +00005245
5246 // No problems found with the new argument list, propagate changes back
5247 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00005248 if (UpdateArgsWithConversions)
5249 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005250
Richard Smith1fde8ec2012-09-07 02:06:42 +00005251 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00005252}
5253
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005254namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005255 class UnnamedLocalNoLinkageFinder
5256 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005257 {
5258 Sema &S;
5259 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005260
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005261 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005262
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005263 public:
5264 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5265
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005266 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00005267 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005269
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005270#define TYPE(Class, Parent) \
5271 bool Visit##Class##Type(const Class##Type *);
5272#define ABSTRACT_TYPE(Class, Parent) \
5273 bool Visit##Class##Type(const Class##Type *) { return false; }
5274#define NON_CANONICAL_TYPE(Class, Parent) \
5275 bool Visit##Class##Type(const Class##Type *) { return false; }
5276#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005277
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005278 bool VisitTagDecl(const TagDecl *Tag);
5279 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5280 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005281} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005282
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005283bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005284 return false;
5285}
5286
5287bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5288 return Visit(T->getElementType());
5289}
5290
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005291bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005292 return Visit(T->getPointeeType());
5293}
5294
5295bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005296 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005297 return Visit(T->getPointeeType());
5298}
5299
5300bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005301 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005302 return Visit(T->getPointeeType());
5303}
5304
5305bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005306 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005307 return Visit(T->getPointeeType());
5308}
5309
5310bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005311 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005312 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5313}
5314
5315bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005316 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005317 return Visit(T->getElementType());
5318}
5319
5320bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005321 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005322 return Visit(T->getElementType());
5323}
5324
5325bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005326 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005327 return Visit(T->getElementType());
5328}
5329
5330bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005331 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005332 return Visit(T->getElementType());
5333}
5334
5335bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005336 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005337 return Visit(T->getElementType());
5338}
5339
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005340bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5341 const DependentAddressSpaceType *T) {
5342 return Visit(T->getPointeeType());
5343}
5344
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005345bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5346 return Visit(T->getElementType());
5347}
5348
Erich Keanef702b022018-07-13 19:46:04 +00005349bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5350 const DependentVectorType *T) {
5351 return Visit(T->getElementType());
5352}
5353
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005354bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5355 return Visit(T->getElementType());
5356}
5357
5358bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5359 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005360 for (const auto &A : T->param_types()) {
5361 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005362 return true;
5363 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005364
Alp Toker314cc812014-01-25 16:55:45 +00005365 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005366}
5367
5368bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5369 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00005370 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005371}
5372
5373bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5374 const UnresolvedUsingType*) {
5375 return false;
5376}
5377
5378bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5379 return false;
5380}
5381
5382bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5383 return Visit(T->getUnderlyingType());
5384}
5385
5386bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5387 return false;
5388}
5389
Alexis Hunte852b102011-05-24 22:41:36 +00005390bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5391 const UnaryTransformType*) {
5392 return false;
5393}
5394
Richard Smith30482bc2011-02-20 03:19:35 +00005395bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5396 return Visit(T->getDeducedType());
5397}
5398
Richard Smith600b5262017-01-26 20:40:47 +00005399bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5400 const DeducedTemplateSpecializationType *T) {
5401 return Visit(T->getDeducedType());
5402}
5403
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005404bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5405 return VisitTagDecl(T->getDecl());
5406}
5407
5408bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5409 return VisitTagDecl(T->getDecl());
5410}
5411
5412bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5413 const TemplateTypeParmType*) {
5414 return false;
5415}
5416
Douglas Gregorada4b792011-01-14 02:55:32 +00005417bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5418 const SubstTemplateTypeParmPackType *) {
5419 return false;
5420}
5421
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005422bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5423 const TemplateSpecializationType*) {
5424 return false;
5425}
5426
5427bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5428 const InjectedClassNameType* T) {
5429 return VisitTagDecl(T->getDecl());
5430}
5431
5432bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5433 const DependentNameType* T) {
5434 return VisitNestedNameSpecifier(T->getQualifier());
5435}
5436
5437bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5438 const DependentTemplateSpecializationType* T) {
5439 return VisitNestedNameSpecifier(T->getQualifier());
5440}
5441
Douglas Gregord2fa7662010-12-20 02:24:11 +00005442bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5443 const PackExpansionType* T) {
5444 return Visit(T->getPattern());
5445}
5446
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005447bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5448 return false;
5449}
5450
5451bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5452 const ObjCInterfaceType *) {
5453 return false;
5454}
5455
5456bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5457 const ObjCObjectPointerType *) {
5458 return false;
5459}
5460
Eli Friedman0dfb8892011-10-06 23:00:33 +00005461bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5462 return Visit(T->getValueType());
5463}
5464
Xiuli Pan9c14e282016-01-09 12:53:17 +00005465bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5466 return false;
5467}
5468
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005469bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5470 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005471 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005472 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005473 diag::warn_cxx98_compat_template_arg_local_type :
5474 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005475 << S.Context.getTypeDeclType(Tag) << SR;
5476 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005477 }
5478
John McCall5ea95772013-03-09 00:54:27 +00005479 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005480 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005481 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005482 diag::warn_cxx98_compat_template_arg_unnamed_type :
5483 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005484 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5485 return true;
5486 }
5487
5488 return false;
5489}
5490
5491bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5492 NestedNameSpecifier *NNS) {
5493 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5494 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005495
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005496 switch (NNS->getKind()) {
5497 case NestedNameSpecifier::Identifier:
5498 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005499 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005500 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005501 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005502 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005503
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005504 case NestedNameSpecifier::TypeSpec:
5505 case NestedNameSpecifier::TypeSpecWithTemplate:
5506 return Visit(QualType(NNS->getAsType(), 0));
5507 }
David Blaikie8a40f702012-01-17 06:56:22 +00005508 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005509}
5510
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005511/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00005512/// template type parameter.
5513///
5514/// This routine implements the semantics of C++ [temp.arg.type]. It
5515/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005516bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005517 TypeSourceInfo *ArgInfo) {
5518 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005519 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005520 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005521
5522 if (Arg->isVariablyModifiedType()) {
5523 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005524 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005525 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005526 }
5527
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005528 // C++03 [temp.arg.type]p2:
5529 // A local type, a type with no linkage, an unnamed type or a type
5530 // compounded from any of these types shall not be used as a
5531 // template-argument for a template type-parameter.
5532 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005533 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005534 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005535 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005536 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5537 (void)Finder.Visit(Context.getCanonicalType(Arg));
5538 }
5539
Douglas Gregord32e0282009-02-09 23:23:08 +00005540 return false;
5541}
5542
Douglas Gregor20fdef32012-04-10 17:08:25 +00005543enum NullPointerValueKind {
5544 NPV_NotNullPointer,
5545 NPV_NullPointer,
5546 NPV_Error
5547};
5548
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005549/// Determine whether the given template argument is a null pointer
Douglas Gregor20fdef32012-04-10 17:08:25 +00005550/// value of the appropriate type.
5551static NullPointerValueKind
5552isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
Reid Klecknercd016d82017-07-07 22:04:29 +00005553 QualType ParamType, Expr *Arg,
5554 Decl *Entity = nullptr) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005555 if (Arg->isValueDependent() || Arg->isTypeDependent())
5556 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005557
Reid Klecknercd016d82017-07-07 22:04:29 +00005558 // dllimport'd entities aren't constant but are available inside of template
5559 // arguments.
5560 if (Entity && Entity->hasAttr<DLLImportAttr>())
5561 return NPV_NotNullPointer;
5562
Richard Smithdb0ac552015-12-18 22:40:25 +00005563 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005564 llvm_unreachable(
5565 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005566
David Majnemer5c734ad2014-08-14 00:49:23 +00005567 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005568 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005569
Douglas Gregor20fdef32012-04-10 17:08:25 +00005570 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005571 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5572 if (ArgRV.isInvalid())
5573 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005574 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005575
Douglas Gregor20fdef32012-04-10 17:08:25 +00005576 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005577 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005578 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005579 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005580 EvalResult.HasSideEffects) {
5581 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005582
Douglas Gregor350880c2012-04-10 19:03:30 +00005583 // If our only note is the usual "invalid subexpression" note, just point
5584 // the caret at its location rather than producing an essentially
5585 // redundant note.
5586 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5587 diag::note_invalid_subexpr_in_const_expr) {
5588 DiagLoc = Notes[0].first;
5589 Notes.clear();
5590 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005591
Douglas Gregor350880c2012-04-10 19:03:30 +00005592 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5593 << Arg->getType() << Arg->getSourceRange();
5594 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5595 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005596
Douglas Gregor350880c2012-04-10 19:03:30 +00005597 S.Diag(Param->getLocation(), diag::note_template_param_here);
5598 return NPV_Error;
5599 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005600
Douglas Gregor20fdef32012-04-10 17:08:25 +00005601 // C++11 [temp.arg.nontype]p1:
5602 // - an address constant expression of type std::nullptr_t
5603 if (Arg->getType()->isNullPtrType())
5604 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005605
Douglas Gregor20fdef32012-04-10 17:08:25 +00005606 // - a constant expression that evaluates to a null pointer value (4.10); or
5607 // - a constant expression that evaluates to a null member pointer value
5608 // (4.11); or
5609 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5610 (EvalResult.Val.isMemberPointer() &&
5611 !EvalResult.Val.getMemberPointerDecl())) {
5612 // If our expression has an appropriate type, we've succeeded.
5613 bool ObjCLifetimeConversion;
5614 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5615 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5616 ObjCLifetimeConversion))
5617 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005618
Douglas Gregor20fdef32012-04-10 17:08:25 +00005619 // The types didn't match, but we know we got a null pointer; complain,
5620 // then recover as if the types were correct.
5621 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5622 << Arg->getType() << ParamType << Arg->getSourceRange();
5623 S.Diag(Param->getLocation(), diag::note_template_param_here);
5624 return NPV_NullPointer;
5625 }
5626
5627 // If we don't have a null pointer value, but we do have a NULL pointer
5628 // constant, suggest a cast to the appropriate type.
5629 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5630 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5631 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005632 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5633 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5634 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005635 S.Diag(Param->getLocation(), diag::note_template_param_here);
5636 return NPV_NullPointer;
5637 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005638
Douglas Gregor20fdef32012-04-10 17:08:25 +00005639 // FIXME: If we ever want to support general, address-constant expressions
5640 // as non-type template arguments, we should return the ExprResult here to
5641 // be interpreted by the caller.
5642 return NPV_NotNullPointer;
5643}
5644
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005645/// Checks whether the given template argument is compatible with its
David Majnemer61c39a12013-08-23 05:39:39 +00005646/// template parameter.
5647static bool CheckTemplateArgumentIsCompatibleWithParameter(
5648 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5649 Expr *Arg, QualType ArgType) {
5650 bool ObjCLifetimeConversion;
5651 if (ParamType->isPointerType() &&
5652 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5653 S.IsQualificationConversion(ArgType, ParamType, false,
5654 ObjCLifetimeConversion)) {
5655 // For pointer-to-object types, qualification conversions are
5656 // permitted.
5657 } else {
5658 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5659 if (!ParamRef->getPointeeType()->isFunctionType()) {
5660 // C++ [temp.arg.nontype]p5b3:
5661 // For a non-type template-parameter of type reference to
5662 // object, no conversions apply. The type referred to by the
5663 // reference may be more cv-qualified than the (otherwise
5664 // identical) type of the template- argument. The
5665 // template-parameter is bound directly to the
5666 // template-argument, which shall be an lvalue.
5667
5668 // FIXME: Other qualifiers?
5669 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5670 unsigned ArgQuals = ArgType.getCVRQualifiers();
5671
5672 if ((ParamQuals | ArgQuals) != ParamQuals) {
5673 S.Diag(Arg->getLocStart(),
5674 diag::err_template_arg_ref_bind_ignores_quals)
5675 << ParamType << Arg->getType() << Arg->getSourceRange();
5676 S.Diag(Param->getLocation(), diag::note_template_param_here);
5677 return true;
5678 }
5679 }
5680 }
5681
5682 // At this point, the template argument refers to an object or
5683 // function with external linkage. We now need to check whether the
5684 // argument and parameter types are compatible.
5685 if (!S.Context.hasSameUnqualifiedType(ArgType,
5686 ParamType.getNonReferenceType())) {
5687 // We can't perform this conversion or binding.
5688 if (ParamType->isReferenceType())
5689 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5690 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5691 else
5692 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5693 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5694 S.Diag(Param->getLocation(), diag::note_template_param_here);
5695 return true;
5696 }
5697 }
5698
5699 return false;
5700}
5701
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005702/// Checks whether the given template argument is the address
Douglas Gregorccb07762009-02-11 19:52:55 +00005703/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005704static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005705CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5706 NonTypeTemplateParmDecl *Param,
5707 QualType ParamType,
5708 Expr *ArgIn,
5709 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005710 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005711 Expr *Arg = ArgIn;
5712 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005713
Douglas Gregorb242683d2010-04-01 18:32:35 +00005714 bool AddressTaken = false;
5715 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005716 if (S.getLangOpts().MicrosoftExt) {
5717 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5718 // dereference and address-of operators.
5719 Arg = Arg->IgnoreParenCasts();
5720
5721 bool ExtWarnMSTemplateArg = false;
5722 UnaryOperatorKind FirstOpKind;
5723 SourceLocation FirstOpLoc;
5724 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5725 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5726 if (UnOpKind == UO_Deref)
5727 ExtWarnMSTemplateArg = true;
5728 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5729 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5730 if (!AddrOpLoc.isValid()) {
5731 FirstOpKind = UnOpKind;
5732 FirstOpLoc = UnOp->getOperatorLoc();
5733 }
5734 } else
5735 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005736 }
David Majnemer61c39a12013-08-23 05:39:39 +00005737 if (FirstOpLoc.isValid()) {
5738 if (ExtWarnMSTemplateArg)
5739 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5740 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005741
David Majnemer61c39a12013-08-23 05:39:39 +00005742 if (FirstOpKind == UO_AddrOf)
5743 AddressTaken = true;
5744 else if (Arg->getType()->isPointerType()) {
5745 // We cannot let pointers get dereferenced here, that is obviously not a
5746 // constant expression.
5747 assert(FirstOpKind == UO_Deref);
5748 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5749 << Arg->getSourceRange();
5750 }
5751 }
5752 } else {
5753 // See through any implicit casts we added to fix the type.
5754 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005755
David Majnemer61c39a12013-08-23 05:39:39 +00005756 // C++ [temp.arg.nontype]p1:
5757 //
5758 // A template-argument for a non-type, non-template
5759 // template-parameter shall be one of: [...]
5760 //
5761 // -- the address of an object or function with external
5762 // linkage, including function templates and function
5763 // template-ids but excluding non-static class members,
5764 // expressed as & id-expression where the & is optional if
5765 // the name refers to a function or array, or if the
5766 // corresponding template-parameter is a reference; or
5767
5768 // In C++98/03 mode, give an extension warning on any extra parentheses.
5769 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5770 bool ExtraParens = false;
5771 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5772 if (!Invalid && !ExtraParens) {
5773 S.Diag(Arg->getLocStart(),
5774 S.getLangOpts().CPlusPlus11
5775 ? diag::warn_cxx98_compat_template_arg_extra_parens
5776 : diag::ext_template_arg_extra_parens)
5777 << Arg->getSourceRange();
5778 ExtraParens = true;
5779 }
5780
5781 Arg = Parens->getSubExpr();
5782 }
5783
5784 while (SubstNonTypeTemplateParmExpr *subst =
5785 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5786 Arg = subst->getReplacement()->IgnoreImpCasts();
5787
5788 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5789 if (UnOp->getOpcode() == UO_AddrOf) {
5790 Arg = UnOp->getSubExpr();
5791 AddressTaken = true;
5792 AddrOpLoc = UnOp->getOperatorLoc();
5793 }
5794 }
5795
5796 while (SubstNonTypeTemplateParmExpr *subst =
5797 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5798 Arg = subst->getReplacement()->IgnoreImpCasts();
5799 }
John McCall7c454bb2011-07-15 05:09:51 +00005800
David Majnemer07910d62014-06-26 07:48:46 +00005801 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5802 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5803
5804 // If our parameter has pointer type, check for a null template value.
5805 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
Reid Klecknercd016d82017-07-07 22:04:29 +00005806 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5807 Entity)) {
David Majnemer07910d62014-06-26 07:48:46 +00005808 case NPV_NullPointer:
5809 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005810 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5811 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005812 return false;
5813
5814 case NPV_Error:
5815 return true;
5816
5817 case NPV_NotNullPointer:
5818 break;
5819 }
5820 }
5821
Chandler Carruth724a8a12010-01-31 10:01:20 +00005822 // Stop checking the precise nature of the argument if it is value dependent,
5823 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005824 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005825 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005826 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005827 }
David Majnemer61c39a12013-08-23 05:39:39 +00005828
5829 if (isa<CXXUuidofExpr>(Arg)) {
5830 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5831 ArgIn, Arg, ArgType))
5832 return true;
5833
5834 Converted = TemplateArgument(ArgIn);
5835 return false;
5836 }
5837
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005838 if (!DRE) {
5839 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5840 << Arg->getSourceRange();
5841 S.Diag(Param->getLocation(), diag::note_template_param_here);
5842 return true;
5843 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00005844
Douglas Gregorccb07762009-02-11 19:52:55 +00005845 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00005846 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005847 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00005848 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005849 S.Diag(Param->getLocation(), diag::note_template_param_here);
5850 return true;
5851 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005852
5853 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00005854 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005855 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005856 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00005857 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005858 S.Diag(Param->getLocation(), diag::note_template_param_here);
5859 return true;
5860 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005861 }
Mike Stump11289f42009-09-09 15:08:12 +00005862
Richard Smith9380e0e2012-04-04 21:11:30 +00005863 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5864 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00005865
Richard Smith9380e0e2012-04-04 21:11:30 +00005866 // A non-type template argument must refer to an object or function.
5867 if (!Func && !Var) {
5868 // We found something, but we don't know specifically what it is.
5869 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5870 << Arg->getSourceRange();
5871 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5872 return true;
5873 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005874
Richard Smith9380e0e2012-04-04 21:11:30 +00005875 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00005876 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005877 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00005878 diag::warn_cxx98_compat_template_arg_object_internal :
5879 diag::ext_template_arg_object_internal)
5880 << !Func << Entity << Arg->getSourceRange();
5881 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5882 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00005883 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005884 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5885 << !Func << Entity << Arg->getSourceRange();
5886 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5887 << !Func;
5888 return true;
5889 }
5890
5891 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005892 // If the template parameter has pointer type, the function decays.
5893 if (ParamType->isPointerType() && !AddressTaken)
5894 ArgType = S.Context.getPointerType(Func->getType());
5895 else if (AddressTaken && ParamType->isReferenceType()) {
5896 // If we originally had an address-of operator, but the
5897 // parameter has reference type, complain and (if things look
5898 // like they will work) drop the address-of operator.
5899 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5900 ParamType.getNonReferenceType())) {
5901 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5902 << ParamType;
5903 S.Diag(Param->getLocation(), diag::note_template_param_here);
5904 return true;
5905 }
5906
5907 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5908 << ParamType
5909 << FixItHint::CreateRemoval(AddrOpLoc);
5910 S.Diag(Param->getLocation(), diag::note_template_param_here);
5911
5912 ArgType = Func->getType();
5913 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005914 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005915 // A value of reference type is not an object.
5916 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005917 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00005918 diag::err_template_arg_reference_var)
5919 << Var->getType() << Arg->getSourceRange();
5920 S.Diag(Param->getLocation(), diag::note_template_param_here);
5921 return true;
5922 }
5923
Richard Smith9380e0e2012-04-04 21:11:30 +00005924 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005925 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005926 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5927 << Arg->getSourceRange();
5928 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5929 return true;
5930 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005931
5932 // If the template parameter has pointer type, we must have taken
5933 // the address of this object.
5934 if (ParamType->isReferenceType()) {
5935 if (AddressTaken) {
5936 // If we originally had an address-of operator, but the
5937 // parameter has reference type, complain and (if things look
5938 // like they will work) drop the address-of operator.
5939 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5940 ParamType.getNonReferenceType())) {
5941 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5942 << ParamType;
5943 S.Diag(Param->getLocation(), diag::note_template_param_here);
5944 return true;
5945 }
5946
5947 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5948 << ParamType
5949 << FixItHint::CreateRemoval(AddrOpLoc);
5950 S.Diag(Param->getLocation(), diag::note_template_param_here);
5951
5952 ArgType = Var->getType();
5953 }
5954 } else if (!AddressTaken && ParamType->isPointerType()) {
5955 if (Var->getType()->isArrayType()) {
5956 // Array-to-pointer decay.
5957 ArgType = S.Context.getArrayDecayedType(Var->getType());
5958 } else {
5959 // If the template parameter has pointer type but the address of
5960 // this object was not taken, complain and (possibly) recover by
5961 // taking the address of the entity.
5962 ArgType = S.Context.getPointerType(Var->getType());
5963 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5964 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5965 << ParamType;
5966 S.Diag(Param->getLocation(), diag::note_template_param_here);
5967 return true;
5968 }
5969
5970 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5971 << ParamType
5972 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5973
5974 S.Diag(Param->getLocation(), diag::note_template_param_here);
5975 }
5976 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005977 }
Mike Stump11289f42009-09-09 15:08:12 +00005978
David Majnemer61c39a12013-08-23 05:39:39 +00005979 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5980 Arg, ArgType))
5981 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005982
5983 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00005984 Converted =
5985 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00005986 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00005987 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005988}
5989
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005990/// Checks whether the given template argument is a pointer to
Douglas Gregorccb07762009-02-11 19:52:55 +00005991/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005992static bool CheckTemplateArgumentPointerToMember(Sema &S,
5993 NonTypeTemplateParmDecl *Param,
5994 QualType ParamType,
5995 Expr *&ResultArg,
5996 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005997 bool Invalid = false;
5998
Douglas Gregor20fdef32012-04-10 17:08:25 +00005999 Expr *Arg = ResultArg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006000 bool ObjCLifetimeConversion;
Douglas Gregorccb07762009-02-11 19:52:55 +00006001
6002 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006003 //
Douglas Gregorccb07762009-02-11 19:52:55 +00006004 // A template-argument for a non-type, non-template
6005 // template-parameter shall be one of: [...]
6006 //
6007 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00006008 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00006009
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006010 // In C++98/03 mode, give an extension warning on any extra parentheses.
6011 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6012 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006013 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00006014 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00006015 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006016 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00006017 diag::warn_cxx98_compat_template_arg_extra_parens :
6018 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00006019 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006020 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00006021 }
6022
6023 Arg = Parens->getSubExpr();
6024 }
6025
John McCall7c454bb2011-07-15 05:09:51 +00006026 while (SubstNonTypeTemplateParmExpr *subst =
6027 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6028 Arg = subst->getReplacement()->IgnoreImpCasts();
6029
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006030 // A pointer-to-member constant written &Class::member.
6031 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00006032 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006033 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6034 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00006035 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006036 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006037 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006038 // A constant of pointer-to-member type.
6039 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006040 ValueDecl *VD = DRE->getDecl();
6041 if (VD->getType()->isMemberPointerType()) {
6042 if (isa<NonTypeTemplateParmDecl>(VD)) {
6043 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6044 Converted = TemplateArgument(Arg);
6045 } else {
6046 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6047 Converted = TemplateArgument(VD, ParamType);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006048 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00006049 return Invalid;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006050 }
6051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006052
Craig Topperc3ec1492014-05-26 06:22:03 +00006053 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006054 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006055
Reid Klecknercd016d82017-07-07 22:04:29 +00006056 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6057
6058 // Check for a null pointer value.
6059 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6060 Entity)) {
6061 case NPV_Error:
6062 return true;
6063 case NPV_NullPointer:
6064 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6065 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6066 /*isNullPtr*/true);
6067 return false;
6068 case NPV_NotNullPointer:
6069 break;
6070 }
6071
6072 if (S.IsQualificationConversion(ResultArg->getType(),
6073 ParamType.getNonReferenceType(), false,
6074 ObjCLifetimeConversion)) {
6075 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6076 ResultArg->getValueKind())
6077 .get();
6078 } else if (!S.Context.hasSameUnqualifiedType(
6079 ResultArg->getType(), ParamType.getNonReferenceType())) {
6080 // We can't perform this conversion.
6081 S.Diag(ResultArg->getLocStart(), diag::err_template_arg_not_convertible)
6082 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6083 S.Diag(Param->getLocation(), diag::note_template_param_here);
6084 return true;
6085 }
6086
Douglas Gregorccb07762009-02-11 19:52:55 +00006087 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00006088 return S.Diag(Arg->getLocStart(),
6089 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00006090 << Arg->getSourceRange();
6091
David Majnemer3ac84e62013-10-22 21:56:38 +00006092 if (isa<FieldDecl>(DRE->getDecl()) ||
6093 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6094 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006095 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00006096 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00006097 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6098 "Only non-static member pointers can make it here");
6099
6100 // Okay: this is the address of a non-static member, and therefore
6101 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00006102 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00006103 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00006104 } else {
6105 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00006106 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00006107 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006108 return Invalid;
6109 }
6110
6111 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00006112 S.Diag(Arg->getLocStart(),
6113 diag::err_template_arg_not_pointer_to_member_form)
6114 << Arg->getSourceRange();
6115 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00006116 return true;
6117}
6118
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006119/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006120/// non-type template parameter.
6121///
Douglas Gregor463421d2009-03-03 04:44:36 +00006122/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00006123/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00006124/// returns the converted template argument. \p ParamType is the
6125/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00006126ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00006127 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00006128 TemplateArgument &Converted,
6129 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006130 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00006131
Richard Smith5f274382016-09-28 23:55:27 +00006132 // If the parameter type somehow involves auto, deduce the type now.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006133 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
Richard Smith4ae5ec82017-02-22 20:01:55 +00006134 // During template argument deduction, we allow 'decltype(auto)' to
6135 // match an arbitrary dependent argument.
6136 // FIXME: The language rules don't say what happens in this case.
6137 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6138 // expression is merely instantiation-dependent; is this enough?
6139 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6140 auto *AT = dyn_cast<AutoType>(ParamType);
6141 if (AT && AT->isDecltypeAuto()) {
6142 Converted = TemplateArgument(Arg);
6143 return Arg;
6144 }
6145 }
6146
Richard Smith87d263e2016-12-25 08:05:23 +00006147 // When checking a deduced template argument, deduce from its type even if
6148 // the type is dependent, in order to check the types of non-type template
6149 // arguments line up properly in partial ordering.
6150 Optional<unsigned> Depth;
6151 if (CTAK != CTAK_Specified)
6152 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00006153 if (DeduceAutoType(
6154 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00006155 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00006156 Diag(Arg->getExprLoc(),
6157 diag::err_non_type_template_parm_type_deduction_failure)
6158 << Param->getDeclName() << Param->getType() << Arg->getType()
6159 << Arg->getSourceRange();
6160 Diag(Param->getLocation(), diag::note_template_param_here);
6161 return ExprError();
6162 }
6163 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6164 // an error. The error message normally references the parameter
6165 // declaration, but here we'll pass the argument location because that's
6166 // where the parameter type is deduced.
6167 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6168 if (ParamType.isNull()) {
6169 Diag(Param->getLocation(), diag::note_template_param_here);
6170 return ExprError();
6171 }
6172 }
6173
Richard Smithd663fdd2014-12-17 20:42:37 +00006174 // We should have already dropped all cv-qualifiers by now.
6175 assert(!ParamType.hasQualifiers() &&
6176 "non-type template parameter type cannot be qualified");
6177
6178 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00006179 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00006180 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00006181 // FIXME: If either type is dependent, we skip the check. This isn't
6182 // correct, since during deduction we're supposed to have replaced each
6183 // template parameter with some unique (non-dependent) placeholder.
6184 // FIXME: If the argument type contains 'auto', we carry on and fail the
6185 // type check in order to force specific types to be more specialized than
6186 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6187 // work.
6188 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6189 !Arg->getType()->getContainedAutoType()) {
6190 Converted = TemplateArgument(Arg);
6191 return Arg;
6192 }
6193 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6194 // we should actually be checking the type of the template argument in P,
6195 // not the type of the template argument deduced from A, against the
6196 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00006197 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00006198 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00006199 << ParamType.getUnqualifiedType();
6200 Diag(Param->getLocation(), diag::note_template_param_here);
6201 return ExprError();
6202 }
6203
Richard Smith87d263e2016-12-25 08:05:23 +00006204 // If either the parameter has a dependent type or the argument is
6205 // type-dependent, there's nothing we can check now.
6206 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6207 // FIXME: Produce a cloned, canonical expression?
6208 Converted = TemplateArgument(Arg);
6209 return Arg;
6210 }
6211
Richard Smithe5945872017-01-06 22:52:53 +00006212 // The initialization of the parameter from the argument is
6213 // a constant-evaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006214 EnterExpressionEvaluationContext ConstantEvaluated(
6215 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smithe5945872017-01-06 22:52:53 +00006216
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006217 if (getLangOpts().CPlusPlus17) {
6218 // C++17 [temp.arg.nontype]p1:
Richard Smith410cc892014-11-26 03:26:53 +00006219 // A template-argument for a non-type template parameter shall be
6220 // a converted constant expression of the type of the template-parameter.
6221 APValue Value;
6222 ExprResult ArgResult = CheckConvertedConstantExpression(
6223 Arg, ParamType, Value, CCEK_TemplateArg);
6224 if (ArgResult.isInvalid())
6225 return ExprError();
6226
Richard Smith52e624f2016-12-21 21:42:57 +00006227 // For a value-dependent argument, CheckConvertedConstantExpression is
6228 // permitted (and expected) to be unable to determine a value.
6229 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00006230 Converted = TemplateArgument(ArgResult.get());
6231 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00006232 }
6233
Richard Smithd663fdd2014-12-17 20:42:37 +00006234 QualType CanonParamType = Context.getCanonicalType(ParamType);
6235
Richard Smith410cc892014-11-26 03:26:53 +00006236 // Convert the APValue to a TemplateArgument.
6237 switch (Value.getKind()) {
6238 case APValue::Uninitialized:
6239 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006240 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006241 break;
6242 case APValue::Int:
6243 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006244 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00006245 break;
6246 case APValue::MemberPointer: {
6247 assert(ParamType->isMemberPointerType());
6248
6249 // FIXME: We need TemplateArgument representation and mangling for these.
6250 if (!Value.getMemberPointerPath().empty()) {
6251 Diag(Arg->getLocStart(),
6252 diag::err_template_arg_member_ptr_base_derived_not_supported)
6253 << Value.getMemberPointerDecl() << ParamType
6254 << Arg->getSourceRange();
6255 return ExprError();
6256 }
6257
6258 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00006259 Converted = VD ? TemplateArgument(VD, CanonParamType)
6260 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006261 break;
6262 }
6263 case APValue::LValue: {
6264 // For a non-type template-parameter of pointer or reference type,
6265 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00006266 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6267 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00006268 // -- a temporary object
6269 // -- a string literal
6270 // -- the result of a typeid expression, or
Eric Christopher0d2c56a2017-03-31 01:45:39 +00006271 // -- a predefined __func__ variable
Richard Smith410cc892014-11-26 03:26:53 +00006272 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6273 if (isa<CXXUuidofExpr>(E)) {
Nico Weberd60bbce2018-05-17 15:26:37 +00006274 Converted = TemplateArgument(ArgResult.get());
Richard Smith410cc892014-11-26 03:26:53 +00006275 break;
6276 }
6277 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
6278 << Arg->getSourceRange();
6279 return ExprError();
6280 }
6281 auto *VD = const_cast<ValueDecl *>(
6282 Value.getLValueBase().dyn_cast<const ValueDecl *>());
6283 // -- a subobject
6284 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6285 VD && VD->getType()->isArrayType() &&
6286 Value.getLValuePath()[0].ArrayIndex == 0 &&
6287 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6288 // Per defect report (no number yet):
6289 // ... other than a pointer to the first element of a complete array
6290 // object.
6291 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6292 Value.isLValueOnePastTheEnd()) {
6293 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6294 << Value.getAsString(Context, ParamType);
6295 return ExprError();
6296 }
Richard Smithd663fdd2014-12-17 20:42:37 +00006297 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00006298 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00006299 assert((!VD || !ParamType->isNullPtrType()) &&
6300 "non-null value of type nullptr_t?");
6301 Converted = VD ? TemplateArgument(VD, CanonParamType)
6302 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006303 break;
6304 }
6305 case APValue::AddrLabelDiff:
6306 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6307 case APValue::Float:
6308 case APValue::ComplexInt:
6309 case APValue::ComplexFloat:
6310 case APValue::Vector:
6311 case APValue::Array:
6312 case APValue::Struct:
6313 case APValue::Union:
6314 llvm_unreachable("invalid kind for template argument");
6315 }
6316
6317 return ArgResult.get();
6318 }
6319
Douglas Gregor86560402009-02-10 23:36:10 +00006320 // C++ [temp.arg.nontype]p5:
6321 // The following conversions are performed on each expression used
6322 // as a non-type template-argument. If a non-type
6323 // template-argument cannot be converted to the type of the
6324 // corresponding template-parameter then the program is
6325 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00006326 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00006327 // C++11:
6328 // -- for a non-type template-parameter of integral or
6329 // enumeration type, conversions permitted in a converted
6330 // constant expression are applied.
6331 //
6332 // C++98:
6333 // -- for a non-type template-parameter of integral or
6334 // enumeration type, integral promotions (4.5) and integral
6335 // conversions (4.7) are applied.
6336
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006337 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00006338 // C++ [temp.arg.nontype]p1:
6339 // A template-argument for a non-type, non-template template-parameter
6340 // shall be one of:
6341 //
6342 // -- for a non-type template-parameter of integral or enumeration
6343 // type, a converted constant expression of the type of the
6344 // template-parameter; or
6345 llvm::APSInt Value;
6346 ExprResult ArgResult =
6347 CheckConvertedConstantExpression(Arg, ParamType, Value,
6348 CCEK_TemplateArg);
6349 if (ArgResult.isInvalid())
6350 return ExprError();
6351
Richard Smith01bfa682016-12-27 02:02:09 +00006352 // We can't check arbitrary value-dependent arguments.
6353 if (ArgResult.get()->isValueDependent()) {
6354 Converted = TemplateArgument(ArgResult.get());
6355 return ArgResult;
6356 }
6357
Richard Smithf8379a02012-01-18 23:55:52 +00006358 // Widen the argument value to sizeof(parameter type). This is almost
6359 // always a no-op, except when the parameter type is bool. In
6360 // that case, this may extend the argument from 1 bit to 8 bits.
6361 QualType IntegerType = ParamType;
6362 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6363 IntegerType = Enum->getDecl()->getIntegerType();
6364 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6365
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006366 Converted = TemplateArgument(Context, Value,
6367 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00006368 return ArgResult;
6369 }
6370
Richard Smith08b12f12011-10-27 22:11:44 +00006371 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6372 if (ArgResult.isInvalid())
6373 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006374 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00006375
6376 QualType ArgType = Arg->getType();
6377
Douglas Gregor86560402009-02-10 23:36:10 +00006378 // C++ [temp.arg.nontype]p1:
6379 // A template-argument for a non-type, non-template
6380 // template-parameter shall be one of:
6381 //
6382 // -- an integral constant-expression of integral or enumeration
6383 // type; or
6384 // -- the name of a non-type template-parameter; or
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006385 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00006386 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006387 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00006388 diag::err_template_arg_not_integral_or_enumeral)
6389 << ArgType << Arg->getSourceRange();
6390 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006391 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00006392 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00006393 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6394 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006395
Douglas Gregore2b37442012-05-04 22:38:52 +00006396 public:
6397 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00006398
6399 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6400 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00006401 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6402 }
6403 } Diagnoser(ArgType);
6404
6405 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006406 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00006407 if (!Arg)
6408 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006409 }
6410
Richard Smithd663fdd2014-12-17 20:42:37 +00006411 // From here on out, all we care about is the unqualified form
6412 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006413 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00006414
6415 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00006416 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00006417 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00006418 } else if (ParamType->isBooleanType()) {
6419 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006420 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006421 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6422 !ParamType->isEnumeralType()) {
6423 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006424 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006425 } else {
6426 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006427 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00006428 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00006429 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006430 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006431 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006432 }
6433
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006434 // Add the value of this argument to the list of converted
6435 // arguments. We use the bitwidth and signedness of the template
6436 // parameter.
6437 if (Arg->isValueDependent()) {
6438 // The argument is value-dependent. Create a new
6439 // TemplateArgument with the converted expression.
6440 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006441 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006442 }
6443
Douglas Gregor52aba872009-03-14 00:20:21 +00006444 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00006445 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00006446 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00006447
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006448 if (ParamType->isBooleanType()) {
6449 // Value must be zero or one.
6450 Value = Value != 0;
6451 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6452 if (Value.getBitWidth() != AllowedBits)
6453 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006454 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006455 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006456 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006457
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006458 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006459 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006460 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006461 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006462 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006463 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00006464
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006465 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006466 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006467 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006468 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006469 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6470 << Arg->getSourceRange();
6471 Diag(Param->getLocation(), diag::note_template_param_here);
6472 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006473
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006474 // Complain if we overflowed the template parameter's type.
6475 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006476 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006477 RequiredBits = OldValue.getActiveBits();
6478 else if (OldValue.isUnsigned())
6479 RequiredBits = OldValue.getActiveBits() + 1;
6480 else
6481 RequiredBits = OldValue.getMinSignedBits();
6482 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006483 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006484 diag::warn_template_arg_too_large)
6485 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6486 << Arg->getSourceRange();
6487 Diag(Param->getLocation(), diag::note_template_param_here);
6488 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006489 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006490
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006491 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006492 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006493 ? Context.getCanonicalType(ParamType)
6494 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006495 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006496 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006497
Richard Smith08b12f12011-10-27 22:11:44 +00006498 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006499 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6500
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006501 // Handle pointer-to-function, reference-to-function, and
6502 // pointer-to-member-function all in (roughly) the same way.
6503 if (// -- For a non-type template-parameter of type pointer to
6504 // function, only the function-to-pointer conversion (4.3) is
6505 // applied. If the template-argument represents a set of
6506 // overloaded functions (or a pointer to such), the matching
6507 // function is selected from the set (13.4).
6508 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006509 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006510 // -- For a non-type template-parameter of type reference to
6511 // function, no conversions apply. If the template-argument
6512 // represents a set of overloaded functions, the matching
6513 // function is selected from the set (13.4).
6514 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006515 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006516 // -- For a non-type template-parameter of type pointer to
6517 // member function, no conversions apply. If the
6518 // template-argument represents a set of overloaded member
6519 // functions, the matching member function is selected from
6520 // the set (13.4).
6521 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006522 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006523 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006524
Douglas Gregor064fdb22010-04-14 23:11:21 +00006525 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006526 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006527 true,
6528 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006529 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006530 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006531
6532 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6533 ArgType = Arg->getType();
6534 } else
John Wiegley01296292011-04-08 18:41:53 +00006535 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006536 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006537
John Wiegley01296292011-04-08 18:41:53 +00006538 if (!ParamType->isMemberPointerType()) {
6539 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6540 ParamType,
6541 Arg, Converted))
6542 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006543 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006544 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006545
Douglas Gregor20fdef32012-04-10 17:08:25 +00006546 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6547 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006548 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006549 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006550 }
6551
Chris Lattner696197c2009-02-20 21:37:53 +00006552 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006553 // -- for a non-type template-parameter of type pointer to
6554 // object, qualification conversions (4.4) and the
6555 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006556 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006557 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006558 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006559
John Wiegley01296292011-04-08 18:41:53 +00006560 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6561 ParamType,
6562 Arg, Converted))
6563 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006564 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006565 }
Mike Stump11289f42009-09-09 15:08:12 +00006566
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006567 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006568 // -- For a non-type template-parameter of type reference to
6569 // object, no conversions apply. The type referred to by the
6570 // reference may be more cv-qualified than the (otherwise
6571 // identical) type of the template-argument. The
6572 // template-parameter is bound directly to the
6573 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006574 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006575 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006576
Douglas Gregor064fdb22010-04-14 23:11:21 +00006577 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006578 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6579 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006580 true,
6581 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006582 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006583 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006584
6585 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6586 ArgType = Arg->getType();
6587 } else
John Wiegley01296292011-04-08 18:41:53 +00006588 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006590
John Wiegley01296292011-04-08 18:41:53 +00006591 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6592 ParamType,
6593 Arg, Converted))
6594 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006595 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006596 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006597
Douglas Gregor20fdef32012-04-10 17:08:25 +00006598 // Deal with parameters of type std::nullptr_t.
6599 if (ParamType->isNullPtrType()) {
6600 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6601 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006602 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006603 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006604
Douglas Gregor20fdef32012-04-10 17:08:25 +00006605 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6606 case NPV_NotNullPointer:
6607 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6608 << Arg->getType() << ParamType;
6609 Diag(Param->getLocation(), diag::note_template_param_here);
6610 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006611
Douglas Gregor20fdef32012-04-10 17:08:25 +00006612 case NPV_Error:
6613 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006614
Douglas Gregor20fdef32012-04-10 17:08:25 +00006615 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006616 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006617 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6618 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006619 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006620 }
6621 }
6622
Douglas Gregor0e558532009-02-11 16:16:59 +00006623 // -- For a non-type template-parameter of type pointer to data
6624 // member, qualification conversions (4.4) are applied.
6625 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6626
Douglas Gregor20fdef32012-04-10 17:08:25 +00006627 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6628 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006629 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006630 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006631}
6632
Richard Smith26b86ea2016-12-31 21:41:23 +00006633static void DiagnoseTemplateParameterListArityMismatch(
6634 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6635 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6636
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006637/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006638/// template template parameter.
6639///
6640/// This routine implements the semantics of C++ [temp.arg.template].
6641/// It returns true if an error occurred, and false otherwise.
Richard Smith5d331022018-03-08 01:07:33 +00006642bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6643 TemplateArgumentLoc &Arg) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006644 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006645 TemplateDecl *Template = Name.getAsTemplateDecl();
6646 if (!Template) {
6647 // Any dependent template name is fine.
6648 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6649 return false;
6650 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006651
Richard Smith26b86ea2016-12-31 21:41:23 +00006652 if (Template->isInvalidDecl())
6653 return true;
6654
Richard Smith3f1b5d02011-05-05 21:57:07 +00006655 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006656 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006657 // the name of a class template or an alias template, expressed as an
6658 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006659 // primary class templates are considered when matching the
6660 // template template argument with the corresponding parameter;
6661 // partial specializations are not considered even if their
6662 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006663 //
6664 // Note that we also allow template template parameters here, which
6665 // will happen when we are dealing with, e.g., class template
6666 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006667 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006668 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006669 !isa<TypeAliasTemplateDecl>(Template) &&
6670 !isa<BuiltinTemplateDecl>(Template)) {
6671 assert(isa<FunctionTemplateDecl>(Template) &&
6672 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006673 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006674 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6675 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006676 }
6677
Richard Smith26b86ea2016-12-31 21:41:23 +00006678 // C++1z [temp.arg.template]p3: (DR 150)
6679 // A template-argument matches a template template-parameter P when P
6680 // is at least as specialized as the template-argument A.
6681 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6682 // Quick check for the common case:
6683 // If P contains a parameter pack, then A [...] matches P if each of A's
6684 // template parameters matches the corresponding template parameter in
6685 // the template-parameter-list of P.
6686 if (TemplateParameterListsAreEqual(
6687 Template->getTemplateParameters(), Params, false,
6688 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6689 return false;
6690
6691 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6692 Arg.getLocation()))
6693 return false;
6694 // FIXME: Produce better diagnostics for deduction failures.
6695 }
6696
Douglas Gregor85e0f662009-02-10 00:24:35 +00006697 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006698 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006699 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006700 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006701 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006702}
6703
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006704/// Given a non-type template argument that refers to a
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006705/// declaration and the type of its corresponding non-type template
6706/// parameter, produce an expression that properly refers to that
6707/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006708ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006709Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6710 QualType ParamType,
6711 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006712 // C++ [temp.param]p8:
6713 //
6714 // A non-type template-parameter of type "array of T" or
6715 // "function returning T" is adjusted to be of type "pointer to
6716 // T" or "pointer to function returning T", respectively.
6717 if (ParamType->isArrayType())
6718 ParamType = Context.getArrayDecayedType(ParamType);
6719 else if (ParamType->isFunctionType())
6720 ParamType = Context.getPointerType(ParamType);
6721
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006722 // For a NULL non-type template argument, return nullptr casted to the
6723 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006724 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006725 return ImpCastExprToType(
6726 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6727 ParamType,
6728 ParamType->getAs<MemberPointerType>()
6729 ? CK_NullToMemberPointer
6730 : CK_NullToPointer);
6731 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006732 assert(Arg.getKind() == TemplateArgument::Declaration &&
6733 "Only declaration template arguments permitted here");
6734
George Burgess IV00f70bd2018-03-01 05:43:23 +00006735 ValueDecl *VD = Arg.getAsDecl();
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006736
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006737 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006738 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6739 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006740 // If the value is a class member, we might have a pointer-to-member.
6741 // Determine whether the non-type template template parameter is of
6742 // pointer-to-member type. If so, we need to build an appropriate
6743 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6744 // would refer to the member itself.
6745 if (ParamType->isMemberPointerType()) {
6746 QualType ClassType
6747 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6748 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006749 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006750 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006751 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006752 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006753
6754 // The actual value-ness of this is unimportant, but for
6755 // internal consistency's sake, references to instance methods
6756 // are r-values.
6757 ExprValueKind VK = VK_LValue;
6758 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6759 VK = VK_RValue;
6760
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006761 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006762 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006763 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006764 Loc,
6765 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006766 if (RefExpr.isInvalid())
6767 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006768
John McCalle3027922010-08-25 11:45:40 +00006769 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006771 // We might need to perform a trailing qualification conversion, since
6772 // the element type on the parameter could be more qualified than the
6773 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006774 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006775 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006776 ParamType.getUnqualifiedType(), false,
6777 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006778 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006779
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006780 assert(!RefExpr.isInvalid() &&
6781 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006782 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006783 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006784 }
6785 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006786
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006787 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006788
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006789 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006790 // When the non-type template parameter is a pointer, take the
6791 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006792 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006793 if (RefExpr.isInvalid())
6794 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006795
Richard Smithfc6fca12017-01-28 00:38:35 +00006796 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6797 (T->isFunctionType() || T->isArrayType())) {
6798 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006799 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006800 if (RefExpr.isInvalid())
6801 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006802
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006803 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006805
Douglas Gregorb242683d2010-04-01 18:32:35 +00006806 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006807 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006808 }
6809
John McCall7decc9e2010-11-18 06:31:45 +00006810 ExprValueKind VK = VK_RValue;
6811
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006812 // If the non-type template parameter has reference type, qualify the
6813 // resulting declaration reference with the extra qualifiers on the
6814 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006815 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6816 VK = VK_LValue;
6817 T = Context.getQualifiedType(T,
6818 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006819 } else if (isa<FunctionDecl>(VD)) {
6820 // References to functions are always lvalues.
6821 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006823
John McCall7decc9e2010-11-18 06:31:45 +00006824 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006825}
6826
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006827/// Construct a new expression that refers to the given
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006828/// integral template argument with the given source-location
6829/// information.
6830///
6831/// This routine takes care of the mapping from an integral template
6832/// argument (which may have any integral type) to the appropriate
6833/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006834ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006835Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6836 SourceLocation Loc) {
6837 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006838 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006839 QualType OrigT = Arg.getIntegralType();
6840
6841 // If this is an enum type that we're instantiating, we need to use an integer
6842 // type the same size as the enumerator. We don't want to build an
6843 // IntegerLiteral with enum type. The integer type of an enum type can be of
6844 // any integral type with C++11 enum classes, make sure we create the right
6845 // type of literal for it.
6846 QualType T = OrigT;
6847 if (const EnumType *ET = OrigT->getAs<EnumType>())
6848 T = ET->getDecl()->getIntegerType();
6849
6850 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006851 if (T->isAnyCharacterType()) {
6852 CharacterLiteral::CharacterKind Kind;
6853 if (T->isWideCharType())
6854 Kind = CharacterLiteral::Wide;
Richard Smith3a8244d2018-05-01 05:02:45 +00006855 else if (T->isChar8Type() && getLangOpts().Char8)
6856 Kind = CharacterLiteral::UTF8;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006857 else if (T->isChar16Type())
6858 Kind = CharacterLiteral::UTF16;
6859 else if (T->isChar32Type())
6860 Kind = CharacterLiteral::UTF32;
6861 else
6862 Kind = CharacterLiteral::Ascii;
6863
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006864 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6865 Kind, T, Loc);
6866 } else if (T->isBooleanType()) {
6867 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6868 T, Loc);
6869 } else if (T->isNullPtrType()) {
6870 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6871 } else {
6872 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00006873 }
6874
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006875 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00006876 // FIXME: This is a hack. We need a better way to handle substituted
6877 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00006878 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6879 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006880 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00006881 Loc, Loc);
6882 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006883
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006884 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006885}
6886
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006887/// Match two template parameters within template parameter lists.
Douglas Gregor641040a2011-01-12 23:45:44 +00006888static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6889 bool Complain,
6890 Sema::TemplateParameterListEqualKind Kind,
6891 SourceLocation TemplateArgLoc) {
6892 // Check the actual kind (type, non-type, template).
6893 if (Old->getKind() != New->getKind()) {
6894 if (Complain) {
6895 unsigned NextDiag = diag::err_template_param_different_kind;
6896 if (TemplateArgLoc.isValid()) {
6897 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6898 NextDiag = diag::note_template_param_different_kind;
6899 }
6900 S.Diag(New->getLocation(), NextDiag)
6901 << (Kind != Sema::TPL_TemplateMatch);
6902 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6903 << (Kind != Sema::TPL_TemplateMatch);
6904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006905
Douglas Gregor641040a2011-01-12 23:45:44 +00006906 return false;
6907 }
6908
Richard Smith26b86ea2016-12-31 21:41:23 +00006909 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006910 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006911 // template template parameter, the template template parameter can have
6912 // a parameter pack where the template template argument does not.
6913 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6914 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6915 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006916 if (Complain) {
6917 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6918 if (TemplateArgLoc.isValid()) {
6919 S.Diag(TemplateArgLoc,
6920 diag::err_template_arg_template_params_mismatch);
6921 NextDiag = diag::note_template_parameter_pack_non_pack;
6922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006923
Douglas Gregor641040a2011-01-12 23:45:44 +00006924 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6925 : isa<NonTypeTemplateParmDecl>(New)? 1
6926 : 2;
6927 S.Diag(New->getLocation(), NextDiag)
6928 << ParamKind << New->isParameterPack();
6929 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6930 << ParamKind << Old->isParameterPack();
6931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006932
Douglas Gregor641040a2011-01-12 23:45:44 +00006933 return false;
6934 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006935
Douglas Gregor641040a2011-01-12 23:45:44 +00006936 // For non-type template parameters, check the type of the parameter.
6937 if (NonTypeTemplateParmDecl *OldNTTP
6938 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6939 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006940
Douglas Gregor641040a2011-01-12 23:45:44 +00006941 // If we are matching a template template argument to a template
6942 // template parameter and one of the non-type template parameter types
Richard Smith13894182017-04-13 21:37:24 +00006943 // is dependent, then we must wait until template instantiation time
6944 // to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00006945 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith13894182017-04-13 21:37:24 +00006946 (OldNTTP->getType()->isDependentType() ||
6947 NewNTTP->getType()->isDependentType()))
Douglas Gregor641040a2011-01-12 23:45:44 +00006948 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006949
Douglas Gregor641040a2011-01-12 23:45:44 +00006950 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6951 if (Complain) {
6952 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6953 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006954 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00006955 diag::err_template_arg_template_params_mismatch);
6956 NextDiag = diag::note_template_nontype_parm_different_type;
6957 }
6958 S.Diag(NewNTTP->getLocation(), NextDiag)
6959 << NewNTTP->getType()
6960 << (Kind != Sema::TPL_TemplateMatch);
6961 S.Diag(OldNTTP->getLocation(),
6962 diag::note_template_nontype_parm_prev_declaration)
6963 << OldNTTP->getType();
6964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006965
Douglas Gregor641040a2011-01-12 23:45:44 +00006966 return false;
6967 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006968
Douglas Gregor641040a2011-01-12 23:45:44 +00006969 return true;
6970 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006971
Douglas Gregor641040a2011-01-12 23:45:44 +00006972 // For template template parameters, check the template parameter types.
6973 // The template parameter lists of template template
6974 // parameters must agree.
6975 if (TemplateTemplateParmDecl *OldTTP
6976 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006977 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00006978 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6979 OldTTP->getTemplateParameters(),
6980 Complain,
6981 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006982 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00006983 : Kind),
6984 TemplateArgLoc);
6985 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006986
Douglas Gregor641040a2011-01-12 23:45:44 +00006987 return true;
6988}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006989
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006990/// Diagnose a known arity mismatch when comparing template argument
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006991/// lists.
6992static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006993void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006994 TemplateParameterList *New,
6995 TemplateParameterList *Old,
6996 Sema::TemplateParameterListEqualKind Kind,
6997 SourceLocation TemplateArgLoc) {
6998 unsigned NextDiag = diag::err_template_param_list_different_arity;
6999 if (TemplateArgLoc.isValid()) {
7000 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7001 NextDiag = diag::note_template_param_list_different_arity;
7002 }
7003 S.Diag(New->getTemplateLoc(), NextDiag)
7004 << (New->size() > Old->size())
7005 << (Kind != Sema::TPL_TemplateMatch)
7006 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7007 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7008 << (Kind != Sema::TPL_TemplateMatch)
7009 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7010}
7011
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007012/// Determine whether the given template parameter lists are
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007013/// equivalent.
7014///
Mike Stump11289f42009-09-09 15:08:12 +00007015/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007016/// source code as part of a new template declaration.
7017///
7018/// \param Old The old template parameter list, typically found via
7019/// name lookup of the template declared with this template parameter
7020/// list.
7021///
7022/// \param Complain If true, this routine will produce a diagnostic if
7023/// the template parameter lists are not equivalent.
7024///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007025/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00007026///
7027/// \param TemplateArgLoc If this source location is valid, then we
7028/// are actually checking the template parameter list of a template
7029/// argument (New) against the template parameter list of its
7030/// corresponding template template parameter (Old). We produce
7031/// slightly different diagnostics in this scenario.
7032///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007033/// \returns True if the template parameter lists are equal, false
7034/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00007035bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007036Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7037 TemplateParameterList *Old,
7038 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007039 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00007040 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007041 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7042 if (Complain)
7043 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7044 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007045
7046 return false;
7047 }
7048
Douglas Gregor641040a2011-01-12 23:45:44 +00007049 // C++0x [temp.arg.template]p3:
7050 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007051 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00007052 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007053 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007054 // template-parameter-list of P. [...]
7055 TemplateParameterList::iterator NewParm = New->begin();
7056 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007057 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007058 OldParmEnd = Old->end();
7059 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00007060 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7061 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007062 if (NewParm == NewParmEnd) {
7063 if (Complain)
7064 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7065 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007066
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007067 return false;
7068 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007069
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007070 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7071 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007072 return false;
7073
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007074 ++NewParm;
7075 continue;
7076 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007077
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007078 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007079 // [...] When P's template- parameter-list contains a template parameter
7080 // pack (14.5.3), the template parameter pack will match zero or more
7081 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007082 // template-parameter-list of A with the same type and form as the
7083 // template parameter pack in P (ignoring whether those template
7084 // parameters are template parameter packs).
7085 for (; NewParm != NewParmEnd; ++NewParm) {
7086 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7087 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007088 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007089 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007091
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007092 // Make sure we exhausted all of the arguments.
7093 if (NewParm != NewParmEnd) {
7094 if (Complain)
7095 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7096 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007097
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007098 return false;
7099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007100
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007101 return true;
7102}
7103
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007104/// Check whether a template can be declared within this scope.
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007105///
7106/// If the template declaration is valid in this scope, returns
7107/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00007108bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007109Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00007110 if (!S)
7111 return false;
7112
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007113 // Find the nearest enclosing declaration scope.
7114 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7115 (S->getFlags() & Scope::TemplateParamScope) != 0)
7116 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00007117
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007118 // C++ [temp]p4:
7119 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007120 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00007121 if (Ctx && Ctx->isExternCContext()) {
7122 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7123 << TemplateParams->getSourceRange();
7124 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7125 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7126 return true;
7127 }
Richard Smith8df390f2016-09-08 23:14:54 +00007128 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007129
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007130 // C++ [temp]p2:
7131 // A template-declaration can appear only as a namespace scope or
7132 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00007133 if (Ctx) {
7134 if (Ctx->isFileContext())
7135 return false;
7136 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7137 // C++ [temp.mem]p2:
7138 // A local class shall not have member templates.
7139 if (RD->isLocalClass())
7140 return Diag(TemplateParams->getTemplateLoc(),
7141 diag::err_template_inside_local_class)
7142 << TemplateParams->getSourceRange();
7143 else
7144 return false;
7145 }
7146 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007147
Mike Stump11289f42009-09-09 15:08:12 +00007148 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007149 diag::err_template_outside_namespace_or_class_scope)
7150 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007151}
Douglas Gregor67a65642009-02-17 23:15:12 +00007152
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007153/// Determine what kind of template specialization the given declaration
Douglas Gregor54888652009-10-07 00:13:32 +00007154/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007155static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00007156 if (!D)
7157 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007158
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007159 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7160 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00007161 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7162 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007163 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7164 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007165
Douglas Gregor54888652009-10-07 00:13:32 +00007166 return TSK_Undeclared;
7167}
7168
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007169/// Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007170/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00007171///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007172/// This routine determines whether a template specialization can be declared
7173/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00007174///
7175/// \param S the semantic analysis object for which this check is being
7176/// performed.
7177///
7178/// \param Specialized the entity being specialized or instantiated, which
7179/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007180/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00007181/// member class).
7182///
7183/// \param PrevDecl the previous declaration of this entity, if any.
7184///
7185/// \param Loc the location of the explicit specialization or instantiation of
7186/// this entity.
7187///
7188/// \param IsPartialSpecialization whether this is a partial specialization of
7189/// a class template.
7190///
Douglas Gregor54888652009-10-07 00:13:32 +00007191/// \returns true if there was an error that we cannot recover from, false
7192/// otherwise.
7193static bool CheckTemplateSpecializationScope(Sema &S,
7194 NamedDecl *Specialized,
7195 NamedDecl *PrevDecl,
7196 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007197 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00007198 // Keep these "kind" numbers in sync with the %select statements in the
7199 // various diagnostics emitted by this routine.
7200 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007201 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007202 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007203 else if (isa<VarTemplateDecl>(Specialized))
7204 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007205 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007206 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007207 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007208 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007209 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00007210 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007211 else if (isa<RecordDecl>(Specialized))
7212 EntityKind = 7;
7213 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7214 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00007215 else {
Richard Smith7d137e32012-03-23 03:33:32 +00007216 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007217 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007218 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00007219 return true;
7220 }
7221
Douglas Gregorf47b9112009-02-25 22:02:03 +00007222 // C++ [temp.expl.spec]p2:
Richard Smithc660c8f2018-03-16 13:36:56 +00007223 // An explicit specialization may be declared in any scope in which
7224 // the corresponding primary template may be defined.
Sebastian Redl50c68252010-08-31 00:36:30 +00007225 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00007226 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007227 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007228 return true;
7229 }
Douglas Gregore4b05162009-10-07 17:21:34 +00007230
7231 // C++ [temp.class.spec]p6:
Richard Smithc660c8f2018-03-16 13:36:56 +00007232 // A class template partial specialization may be declared in any
7233 // scope in which the primary template may be defined.
7234 DeclContext *SpecializedContext =
7235 Specialized->getDeclContext()->getRedeclContext();
7236 DeclContext *DC = S.CurContext->getRedeclContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00007237
Richard Smithc660c8f2018-03-16 13:36:56 +00007238 // Make sure that this redeclaration (or definition) occurs in the same
7239 // scope or an enclosing namespace.
7240 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7241 : DC->Equals(SpecializedContext))) {
Richard Smitha98f8fc2013-12-07 05:09:50 +00007242 if (isa<TranslationUnitDecl>(SpecializedContext))
7243 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7244 << EntityKind << Specialized;
Richard Smithc660c8f2018-03-16 13:36:56 +00007245 else {
7246 auto *ND = cast<NamedDecl>(SpecializedContext);
Alexey Bataev0068cb22015-03-20 07:21:46 +00007247 int Diag = diag::err_template_spec_redecl_out_of_scope;
Richard Smithc660c8f2018-03-16 13:36:56 +00007248 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
Alexey Bataev0068cb22015-03-20 07:21:46 +00007249 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7250 S.Diag(Loc, Diag) << EntityKind << Specialized
Richard Smithc660c8f2018-03-16 13:36:56 +00007251 << ND << isa<CXXRecordDecl>(ND);
7252 }
Richard Smitha98f8fc2013-12-07 05:09:50 +00007253
7254 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007255
Richard Smithc660c8f2018-03-16 13:36:56 +00007256 // Don't allow specializing in the wrong class during error recovery.
7257 // Otherwise, things can go horribly wrong.
7258 if (DC->isRecord())
7259 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007260 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007261
Douglas Gregorf47b9112009-02-25 22:02:03 +00007262 return false;
7263}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007264
Richard Smith57aae072016-12-28 02:37:25 +00007265static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7266 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00007267 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007268 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007269 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00007270 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007271 return E->getSourceRange();
7272 return Checker.MatchLoc;
7273}
7274
7275static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7276 if (!TL.getType()->isDependentType())
7277 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007278 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007279 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00007280 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007281 return TL.getSourceRange();
7282 return Checker.MatchLoc;
7283}
7284
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007285/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007286/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007287static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007288 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7289 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007290 for (unsigned I = 0; I != NumArgs; ++I) {
7291 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007292 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007293 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7294 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007295 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007296
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007297 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007299
Eli Friedmanb826a002012-09-26 02:36:12 +00007300 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007301 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00007302
7303 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007304
Douglas Gregor98318c22011-01-03 21:37:45 +00007305 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007306 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7307 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00007308
7309 // Strip off any implicit casts we added as part of type checking.
7310 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7311 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007312
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007313 // C++ [temp.class.spec]p8:
7314 // A non-type argument is non-specialized if it is the name of a
7315 // non-type parameter. All other non-type arguments are
7316 // specialized.
7317 //
7318 // Below, we check the two conditions that only apply to
7319 // specialized non-type arguments, so skip any non-specialized
7320 // arguments.
7321 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00007322 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007323 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007324
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007325 // C++ [temp.class.spec]p9:
7326 // Within the argument list of a class template partial
7327 // specialization, the following restrictions apply:
7328 // -- A partially specialized non-type argument expression
7329 // shall not involve a template parameter of the partial
7330 // specialization except when the argument expression is a
7331 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00007332 // -- The type of a template parameter corresponding to a
7333 // specialized non-type argument shall not be dependent on a
7334 // parameter of the specialization.
7335 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7336 // We implement a compromise between the original rules and DR1315:
7337 // -- A specialized non-type template argument shall not be
7338 // type-dependent and the corresponding template parameter
7339 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00007340 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00007341 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00007342 if (ParamUseRange.isValid()) {
7343 if (IsDefaultArgument) {
7344 S.Diag(TemplateNameLoc,
7345 diag::err_dependent_non_type_arg_in_partial_spec);
7346 S.Diag(ParamUseRange.getBegin(),
7347 diag::note_dependent_non_type_default_arg_in_partial_spec)
7348 << ParamUseRange;
7349 } else {
7350 S.Diag(ParamUseRange.getBegin(),
7351 diag::err_dependent_non_type_arg_in_partial_spec)
7352 << ParamUseRange;
7353 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007354 return true;
7355 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007356
Richard Smith6056d5e2014-02-09 00:54:43 +00007357 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00007358 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00007359 if (ParamUseRange.isValid()) {
7360 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7361 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Richard Smith57aae072016-12-28 02:37:25 +00007362 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00007363 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00007364 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7365 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007366 return true;
7367 }
7368 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007369
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007370 return false;
7371}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007372
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007373/// Check the non-type template arguments of a class template
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007374/// partial specialization according to C++ [temp.class.spec]p9.
7375///
Richard Smith6056d5e2014-02-09 00:54:43 +00007376/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00007377/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00007378/// template.
7379/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00007380/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00007381/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007382///
Richard Smith6056d5e2014-02-09 00:54:43 +00007383/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00007384bool Sema::CheckTemplatePartialSpecializationArgs(
7385 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7386 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7387 // We have to be conservative when checking a template in a dependent
7388 // context.
7389 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7390 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007391
Richard Smith57aae072016-12-28 02:37:25 +00007392 TemplateParameterList *TemplateParams =
7393 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007394 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7395 NonTypeTemplateParmDecl *Param
7396 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7397 if (!Param)
7398 continue;
7399
Richard Smith57aae072016-12-28 02:37:25 +00007400 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7401 Param, &TemplateArgs[I],
7402 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007403 return true;
7404 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007405
7406 return false;
7407}
7408
Erich Keanec480f302018-07-12 21:09:05 +00007409DeclResult Sema::ActOnClassTemplateSpecialization(
7410 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7411 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7412 const ParsedAttributesView &Attr,
7413 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007414 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007415
Richard Smith4b55a9c2014-04-17 03:29:33 +00007416 CXXScopeSpec &SS = TemplateId.SS;
7417
Abramo Bagnara60804e12011-03-18 15:16:37 +00007418 // NOTE: KWLoc is the location of the tag keyword. This will instead
7419 // store the location of the outermost template keyword in the declaration.
7420 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007421 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7422 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7423 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7424 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007425
Douglas Gregor67a65642009-02-17 23:15:12 +00007426 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007427 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007428 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007429 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7430
7431 if (!ClassTemplate) {
7432 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007433 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007434 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7435 return true;
7436 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007437
Richard Smithf445f192017-02-09 21:04:43 +00007438 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007439 bool isPartialSpecialization = false;
7440
Douglas Gregorf47b9112009-02-25 22:02:03 +00007441 // Check the validity of the template headers that introduce this
7442 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007443 // FIXME: We probably shouldn't complain about these headers for
7444 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007445 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007446 TemplateParameterList *TemplateParams =
7447 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007448 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007449 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007450 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007451 if (Invalid)
7452 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007453
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007454 if (TemplateParams && TemplateParams->size() > 0) {
7455 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007456
Douglas Gregorec9518b2010-12-21 08:14:57 +00007457 if (TUK == TUK_Friend) {
7458 Diag(KWLoc, diag::err_partial_specialization_friend)
7459 << SourceRange(LAngleLoc, RAngleLoc);
7460 return true;
7461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007462
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007463 // C++ [temp.class.spec]p10:
7464 // The template parameter list of a specialization shall not
7465 // contain default template argument values.
7466 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7467 Decl *Param = TemplateParams->getParam(I);
7468 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7469 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007470 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007471 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007472 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007473 }
7474 } else if (NonTypeTemplateParmDecl *NTTP
7475 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7476 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007477 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007478 diag::err_default_arg_in_partial_spec)
7479 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007480 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007481 }
7482 } else {
7483 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007484 if (TTP->hasDefaultArgument()) {
7485 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007486 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007487 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007488 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007489 }
7490 }
7491 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007492 } else if (TemplateParams) {
7493 if (TUK == TUK_Friend)
7494 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007495 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007496 SourceRange(TemplateParams->getTemplateLoc(),
7497 TemplateParams->getRAngleLoc()))
7498 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007499 } else {
7500 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007501 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007502
Douglas Gregor67a65642009-02-17 23:15:12 +00007503 // Check that the specialization uses the same tag kind as the
7504 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007505 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7506 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007507 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007508 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007509 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007510 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007511 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007512 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007513 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007514 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007515 diag::note_previous_use);
7516 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7517 }
7518
Douglas Gregorc40290e2009-03-09 23:48:35 +00007519 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007520 TemplateArgumentListInfo TemplateArgs =
7521 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007522
Douglas Gregor14406932011-01-03 20:35:03 +00007523 // Check for unexpanded parameter packs in any of the template arguments.
7524 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007525 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007526 UPPC_PartialSpecialization))
7527 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007528
Douglas Gregor67a65642009-02-17 23:15:12 +00007529 // Check that the template argument list is well-formed for this
7530 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007531 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007532 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7533 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007534 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007535
Douglas Gregor2373c592009-05-31 09:31:02 +00007536 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007537 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007538 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007539 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7540 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007541 return true;
7542
Richard Smith57aae072016-12-28 02:37:25 +00007543 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7544 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007545 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007546 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007547 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007548 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007549 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7550 << ClassTemplate->getDeclName();
7551 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007552 }
7553 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007554
Craig Topperc3ec1492014-05-26 06:22:03 +00007555 void *InsertPos = nullptr;
7556 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007557
7558 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007559 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007560 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007561 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007562 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007563
Craig Topperc3ec1492014-05-26 06:22:03 +00007564 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007565
Douglas Gregorf47b9112009-02-25 22:02:03 +00007566 // Check whether we can declare a class template specialization in
7567 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007568 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007569 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7570 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007571 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007572 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007573
Douglas Gregor15301382009-07-30 17:40:51 +00007574 // The canonical type
7575 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007576 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007577 // Build the canonical type that describes the converted template
7578 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007579 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7580 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007581 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007582
7583 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007584 ClassTemplate->getInjectedClassNameSpecialization())) {
7585 // C++ [temp.class.spec]p9b3:
7586 //
7587 // -- The argument list of the specialization shall not be identical
7588 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007589 //
7590 // This rule has since been removed, because it's redundant given DR1495,
7591 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007592 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007593 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007594 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007595 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7596 ClassTemplate->getIdentifier(),
7597 TemplateNameLoc,
7598 Attr,
7599 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007600 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007601 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007602 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007603 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007604 }
Douglas Gregor15301382009-07-30 17:40:51 +00007605
Douglas Gregor2373c592009-05-31 09:31:02 +00007606 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007607 ClassTemplatePartialSpecializationDecl *PrevPartial
7608 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007609 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007610 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007611 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007612 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007613 TemplateParams,
7614 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007615 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007616 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007617 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007618 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00007619 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007620 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007621 Partial->setTemplateParameterListsInfo(
7622 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007623 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007624
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007625 if (!PrevPartial)
7626 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007627 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007628
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007629 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007630 // template specialization, make a note of that.
7631 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7632 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007633
Richard Smith57aae072016-12-28 02:37:25 +00007634 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007635 } else {
7636 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007637 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007638 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007639 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007640 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007641 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007642 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007643 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007644 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007645 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007646 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007647 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007648 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007649 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007650
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007651 if (!PrevDecl)
7652 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007653
David Majnemer678f50b2015-11-18 19:49:19 +00007654 if (CurContext->isDependentContext()) {
David Majnemer678f50b2015-11-18 19:49:19 +00007655 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7656 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007657 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007658 } else {
7659 CanonType = Context.getTypeDeclType(Specialization);
7660 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007661 }
7662
Douglas Gregor06db9f52009-10-12 20:18:28 +00007663 // C++ [temp.expl.spec]p6:
7664 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007665 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007666 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007667 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007668 // use occurs; no diagnostic is required.
7669 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007670 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007671 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007672 // Is there any previous explicit specialization declaration?
7673 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7674 Okay = true;
7675 break;
7676 }
7677 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007678
Douglas Gregorc854c662010-02-26 06:03:23 +00007679 if (!Okay) {
7680 SourceRange Range(TemplateNameLoc, RAngleLoc);
7681 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7682 << Context.getTypeDeclType(Specialization) << Range;
7683
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007684 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007685 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007686 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007687 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007688 return true;
7689 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007691
Douglas Gregor2208a292009-09-26 20:57:03 +00007692 // If this is not a friend, note that this is an explicit specialization.
7693 if (TUK != TUK_Friend)
7694 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007695
7696 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007697 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007698 RecordDecl *Def = Specialization->getDefinition();
7699 NamedDecl *Hidden = nullptr;
7700 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7701 SkipBody->ShouldSkip = true;
Richard Smith858e0e02017-05-11 23:11:16 +00007702 makeMergedDefinitionVisible(Hidden);
Richard Smithc7e6ff02015-05-18 20:36:47 +00007703 // From here on out, treat this as just a redeclaration.
7704 TUK = TUK_Declaration;
7705 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007706 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007707 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007708 Diag(Def->getLocation(), diag::note_previous_definition);
7709 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007710 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007711 }
7712 }
7713
Erich Keanec480f302018-07-12 21:09:05 +00007714 ProcessDeclAttributeList(S, Specialization, Attr);
John McCall659a3372010-12-18 03:30:47 +00007715
Richard Smith034b94a2012-08-17 03:20:55 +00007716 // Add alignment attributes if necessary; these attributes are checked when
7717 // the ASTContext lays out the structure.
7718 if (TUK == TUK_Definition) {
7719 AddAlignmentAttributesForRecord(Specialization);
7720 AddMsStructLayoutForRecord(Specialization);
7721 }
7722
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007723 if (ModulePrivateLoc.isValid())
7724 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7725 << (isPartialSpecialization? 1 : 0)
7726 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007727
Douglas Gregord56a91e2009-02-26 22:19:44 +00007728 // Build the fully-sugared type for this class template
7729 // specialization as the user wrote in the specialization
7730 // itself. This means that we'll pretty-print the type retrieved
7731 // from the specialization's declaration the way that the user
7732 // actually wrote the specialization, rather than formatting the
7733 // name based on the "canonical" representation used to store the
7734 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007735 TypeSourceInfo *WrittenTy
7736 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7737 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007738 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007739 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007740 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007741 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007742
Douglas Gregor1e249f82009-02-25 22:18:32 +00007743 // C++ [temp.expl.spec]p9:
7744 // A template explicit specialization is in the scope of the
7745 // namespace in which the template was defined.
7746 //
7747 // We actually implement this paragraph where we set the semantic
7748 // context (in the creation of the ClassTemplateSpecializationDecl),
7749 // but we also maintain the lexical context where the actual
7750 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007751 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007752
Douglas Gregor67a65642009-02-17 23:15:12 +00007753 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007754 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00007755 Specialization->startDefinition();
7756
Douglas Gregor2208a292009-09-26 20:57:03 +00007757 if (TUK == TUK_Friend) {
7758 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7759 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007760 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007761 /*FIXME:*/KWLoc);
7762 Friend->setAccess(AS_public);
7763 CurContext->addDecl(Friend);
7764 } else {
7765 // Add the specialization into its lexical context, so that it can
7766 // be seen when iterating through the list of declarations in that
7767 // context. However, specializations are not found by name lookup.
7768 CurContext->addDecl(Specialization);
7769 }
John McCall48871652010-08-21 09:40:31 +00007770 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007771}
Douglas Gregor333489b2009-03-27 23:10:48 +00007772
John McCall48871652010-08-21 09:40:31 +00007773Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007774 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007775 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007776 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007777 ActOnDocumentableDecl(NewDecl);
7778 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007779}
7780
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007781/// Strips various properties off an implicit instantiation
John McCall4f7ced62010-02-11 01:33:53 +00007782/// that has just been explicitly specialized.
7783static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007784 D->dropAttr<DLLImportAttr>();
7785 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007786
Nico Webere4974382014-12-19 23:52:45 +00007787 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007788 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007789}
7790
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007791/// Compute the diagnostic location for an explicit instantiation
Nico Webera8f80b32012-01-09 19:52:25 +00007792// declaration or definition.
7793static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007794 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007795 // Explicit instantiations following a specialization have no effect and
7796 // hence no PointOfInstantiation. In that case, walk decl backwards
7797 // until a valid name loc is found.
7798 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007799 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7800 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007801 PrevDiagLoc = Prev->getLocation();
7802 }
7803 assert(PrevDiagLoc.isValid() &&
7804 "Explicit instantiation without point of instantiation?");
7805 return PrevDiagLoc;
7806}
7807
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007808/// Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007809/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007810/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007811/// new specialization/instantiation will have any effect.
7812///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007813/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007814/// instantiation.
7815///
7816/// \param NewTSK the kind of the new explicit specialization or instantiation.
7817///
7818/// \param PrevDecl the previous declaration of the entity.
7819///
7820/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7821///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007822/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007823/// declaration was instantiated (either implicitly or explicitly).
7824///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007825/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007826/// specialization or instantiation has no effect and should be ignored.
7827///
7828/// \returns true if there was an error that should prevent the introduction of
7829/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007830bool
7831Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7832 TemplateSpecializationKind NewTSK,
7833 NamedDecl *PrevDecl,
7834 TemplateSpecializationKind PrevTSK,
7835 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007836 bool &HasNoEffect) {
7837 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007838
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007839 switch (NewTSK) {
7840 case TSK_Undeclared:
7841 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007842 assert(
7843 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7844 "previous declaration must be implicit!");
7845 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007846
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007847 case TSK_ExplicitSpecialization:
7848 switch (PrevTSK) {
7849 case TSK_Undeclared:
7850 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007851 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007852 // explicitly specialized or has merely been mentioned without any
7853 // instantiation.
7854 return false;
7855
7856 case TSK_ImplicitInstantiation:
7857 if (PrevPointOfInstantiation.isInvalid()) {
7858 // The declaration itself has not actually been instantiated, so it is
7859 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007860 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007861 return false;
7862 }
7863 // Fall through
Galina Kistanova3779cb32017-06-07 06:25:05 +00007864 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007865
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007866 case TSK_ExplicitInstantiationDeclaration:
7867 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007868 assert((PrevTSK == TSK_ImplicitInstantiation ||
7869 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007870 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007871
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007872 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007873 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007874 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007875 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007876 // implicit instantiation to take place, in every translation unit in
7877 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007878 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007879 // Is there any previous explicit specialization declaration?
7880 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7881 return false;
7882 }
7883
Douglas Gregor1d957a32009-10-27 18:42:08 +00007884 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007885 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007886 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007887 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007888
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007889 return true;
7890 }
Galina Kistanova1d36e832017-06-08 18:20:32 +00007891 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007892
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007893 case TSK_ExplicitInstantiationDeclaration:
7894 switch (PrevTSK) {
7895 case TSK_ExplicitInstantiationDeclaration:
7896 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007897 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007898 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007899
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007900 case TSK_Undeclared:
7901 case TSK_ImplicitInstantiation:
7902 // We're explicitly instantiating something that may have already been
7903 // implicitly instantiated; that's fine.
7904 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007905
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007906 case TSK_ExplicitSpecialization:
7907 // C++0x [temp.explicit]p4:
7908 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007909 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007910 // specialization for that template, the explicit instantiation has no
7911 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007912 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007913 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007914
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007915 case TSK_ExplicitInstantiationDefinition:
7916 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007917 // If an entity is the subject of both an explicit instantiation
7918 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007919 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007920 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007921 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007922
7923 // Explicit instantiations following a specialization have no effect and
7924 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7925 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007926 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7927 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007928 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007929 return false;
7930 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007931
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007932 case TSK_ExplicitInstantiationDefinition:
7933 switch (PrevTSK) {
7934 case TSK_Undeclared:
7935 case TSK_ImplicitInstantiation:
7936 // We're explicitly instantiating something that may have already been
7937 // implicitly instantiated; that's fine.
7938 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007939
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007940 case TSK_ExplicitSpecialization:
7941 // C++ DR 259, C++0x [temp.explicit]p4:
7942 // For a given set of template parameters, if an explicit
7943 // instantiation of a template appears after a declaration of
7944 // an explicit specialization for that template, the explicit
7945 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00007946 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007947 << PrevDecl;
7948 Diag(PrevDecl->getLocation(),
7949 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007950 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007951 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007952
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007953 case TSK_ExplicitInstantiationDeclaration:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007954 // We're explicitly instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007955 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00007956
7957 // C++0x [temp.explicit]p4:
7958 // For a given set of template parameters, if an explicit instantiation
7959 // of a template appears after a declaration of an explicit
7960 // specialization for that template, the explicit instantiation has no
7961 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007962 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00007963 // Is there any previous explicit specialization declaration?
7964 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7965 HasNoEffect = true;
7966 break;
7967 }
7968 }
7969
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007970 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007971
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007972 case TSK_ExplicitInstantiationDefinition:
7973 // C++0x [temp.spec]p5:
7974 // For a given template and a given set of template-arguments,
7975 // - an explicit instantiation definition shall appear at most once
7976 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007977
7978 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7979 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00007980 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007981 : diag::err_explicit_instantiation_duplicate)
7982 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00007983 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00007984 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007985 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007986 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007987 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007988 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007989
David Blaikie83d382b2011-09-23 05:06:16 +00007990 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007991}
7992
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007993/// Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00007994/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00007995///
James Dennettf14a6e52012-06-15 22:23:43 +00007996/// The only possible way to get a dependent function template specialization
7997/// is with a friend declaration, like so:
7998///
7999/// \code
8000/// template \<class T> void foo(T);
8001/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00008002/// friend void foo<>(T);
8003/// };
James Dennettf14a6e52012-06-15 22:23:43 +00008004/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00008005///
8006/// There really isn't any useful analysis we can do here, so we
8007/// just store the information.
8008bool
8009Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8010 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8011 LookupResult &Previous) {
8012 // Remove anything from Previous that isn't a function template in
8013 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00008014 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00008015 LookupResult::Filter F = Previous.makeFilter();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008016 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8017 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
John McCallb9c78482010-04-08 09:05:18 +00008018 while (F.hasNext()) {
8019 NamedDecl *D = F.next()->getUnderlyingDecl();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008020 if (!isa<FunctionTemplateDecl>(D)) {
John McCallb9c78482010-04-08 09:05:18 +00008021 F.erase();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008022 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8023 continue;
8024 }
8025
8026 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8027 D->getDeclContext()->getRedeclContext())) {
8028 F.erase();
8029 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8030 continue;
8031 }
John McCallb9c78482010-04-08 09:05:18 +00008032 }
8033 F.done();
8034
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008035 if (Previous.empty()) {
8036 Diag(FD->getLocation(),
8037 diag::err_dependent_function_template_spec_no_match);
8038 for (auto &P : DiscardedCandidates)
8039 Diag(P.second->getLocation(),
8040 diag::note_dependent_function_template_spec_discard_reason)
8041 << P.first;
8042 return true;
8043 }
John McCallb9c78482010-04-08 09:05:18 +00008044
8045 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8046 ExplicitTemplateArgs);
8047 return false;
8048}
8049
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008050/// Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008051/// specialization.
8052///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008053/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008054/// explicit function template specialization. On successful completion,
8055/// the function declaration \p FD will become a function template
8056/// specialization.
8057///
8058/// \param FD the function declaration, which will be updated to become a
8059/// function template specialization.
8060///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008061/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8062/// if any. Note that this may be valid info even when 0 arguments are
8063/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8064/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008065///
Francois Pichet3a44e432011-07-08 06:21:47 +00008066/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008067/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008068bool Sema::CheckFunctionTemplateSpecialization(
8069 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8070 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008071 // The set of function template specializations that could match this
8072 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00008073 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008074 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8075 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008076
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008077 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8078 ConvertedTemplateArgs;
8079
Sebastian Redl50c68252010-08-31 00:36:30 +00008080 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00008081 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8082 I != E; ++I) {
8083 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8084 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008085 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008086 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00008087 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8088 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008089 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008090
Richard Smith574f4f62013-01-14 05:37:29 +00008091 // When matching a constexpr member function template specialization
8092 // against the primary template, we don't yet know whether the
8093 // specialization has an implicit 'const' (because we don't know whether
8094 // it will be a static member function until we know which template it
8095 // specializes), so adjust it now assuming it specializes this template.
8096 QualType FT = FD->getType();
8097 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008098 CXXMethodDecl *OldMD =
8099 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00008100 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008101 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00008102 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8103 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00008104 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008105 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00008106 }
8107 }
8108
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008109 TemplateArgumentListInfo Args;
8110 if (ExplicitTemplateArgs)
8111 Args = *ExplicitTemplateArgs;
8112
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008113 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008114 // A trailing template-argument can be left unspecified in the
8115 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008116 // provided it can be deduced from the function argument type.
8117 // Perform template argument deduction to determine whether we may be
8118 // specializing this template.
8119 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00008120 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008121 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00008122 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8123 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00008124 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8125 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008126 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008127 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00008128 FailedCandidates.addCandidate().set(
8129 I.getPair(), FunTmpl->getTemplatedDecl(),
8130 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008131 (void)TDK;
8132 continue;
8133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008134
Artem Belevich64135c32016-12-08 19:38:13 +00008135 // Target attributes are part of the cuda function signature, so
8136 // the deduced template's cuda target must match that of the
8137 // specialization. Given that C++ template deduction does not
8138 // take target attributes into account, we reject candidates
8139 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008140 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00008141 IdentifyCUDATarget(Specialization,
8142 /* IgnoreImplicitHDAttributes = */ true) !=
8143 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008144 FailedCandidates.addCandidate().set(
8145 I.getPair(), FunTmpl->getTemplatedDecl(),
8146 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8147 continue;
8148 }
8149
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008150 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008151 if (ExplicitTemplateArgs)
8152 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00008153 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008154 }
8155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008156
Douglas Gregor5de279c2009-09-26 03:41:46 +00008157 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008158 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008159 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008160 FD->getLocation(),
8161 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8162 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00008163 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008164 PDiag(diag::note_function_template_spec_matched));
8165
John McCall58cc69d2010-01-27 01:50:18 +00008166 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008167 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008168
8169 // Ignore access information; it doesn't figure into redeclaration checking.
8170 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00008171
8172 FunctionTemplateSpecializationInfo *SpecInfo
8173 = Specialization->getTemplateSpecializationInfo();
8174 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00008175
8176 // Note: do not overwrite location info if previous template
8177 // specialization kind was explicit.
8178 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00008179 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00008180 Specialization->setLocation(FD->getLocation());
Richard Smith54f04402017-05-18 02:29:20 +00008181 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
Richard Smith5b8b3db2012-02-20 23:28:05 +00008182 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8183 // function can differ from the template declaration with respect to
8184 // the constexpr specifier.
Richard Smith77e9e842017-05-09 23:02:10 +00008185 // FIXME: We need an update record for this AST mutation.
8186 // FIXME: What if there are multiple such prior declarations (for instance,
8187 // from different modules)?
Richard Smith5b8b3db2012-02-20 23:28:05 +00008188 Specialization->setConstexpr(FD->isConstexpr());
8189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008190
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008191 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00008192 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00008193
8194 // If this is a friend declaration, then we're not really declaring
8195 // an explicit specialization.
8196 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008197
Douglas Gregor54888652009-10-07 00:13:32 +00008198 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00008199 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008200 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00008201 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008202 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008203 false))
Douglas Gregor54888652009-10-07 00:13:32 +00008204 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008205
8206 // C++ [temp.expl.spec]p6:
8207 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008208 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008209 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008210 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008211 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008212 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00008213 if (!isFriend &&
8214 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00008215 TSK_ExplicitSpecialization,
8216 Specialization,
8217 SpecInfo->getTemplateSpecializationKind(),
8218 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008219 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008220 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008221
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008222 // Mark the prior declaration as an explicit specialization, so that later
8223 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008224 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00008225 // Since explicit specializations do not inherit '=delete' from their
8226 // primary function template - check if the 'specialization' that was
8227 // implicitly generated (during template argument deduction for partial
8228 // ordering) from the most specialized of all the function templates that
8229 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8230 // first check that it was implicitly generated during template argument
8231 // deduction by making sure it wasn't referenced, and then reset the deleted
8232 // flag to not-deleted, so that we can inherit that information from 'FD'.
8233 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8234 !Specialization->getCanonicalDecl()->isReferenced()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008235 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali81a88be2016-06-14 03:23:15 +00008236 assert(
8237 Specialization->getCanonicalDecl() == Specialization &&
8238 "This must be the only existing declaration of this specialization");
Richard Smith77e9e842017-05-09 23:02:10 +00008239 // FIXME: We need an update record for this AST mutation.
Faisal Vali81a88be2016-06-14 03:23:15 +00008240 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008241 }
Richard Smith54f04402017-05-18 02:29:20 +00008242 // FIXME: We need an update record for this AST mutation.
John McCall816d75b2010-03-24 07:46:06 +00008243 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008244 MarkUnusedFileScopedDecl(Specialization);
8245 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008246
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008247 // Turn the given function declaration into a function template
8248 // specialization, with the template arguments from the previous
8249 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008250 // Take copies of (semantic and syntactic) template argument lists.
8251 const TemplateArgumentList* TemplArgs = new (Context)
8252 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008253 FD->setFunctionTemplateSpecialization(
8254 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8255 SpecInfo->getTemplateSpecializationKind(),
8256 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008257
Artem Belevich64135c32016-12-08 19:38:13 +00008258 // A function template specialization inherits the target attributes
8259 // of its template. (We require the attributes explicitly in the
8260 // code to match, but a template may have implicit attributes by
8261 // virtue e.g. of being constexpr, and it passes these implicit
8262 // attributes on to its specializations.)
8263 if (LangOpts.CUDA)
8264 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8265
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008266 // The "previous declaration" for this function template specialization is
8267 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00008268 Previous.clear();
8269 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008270 return false;
8271}
8272
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008273/// Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008274/// specialization.
8275///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008276/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008277/// explicit member function specialization. On successful completion,
8278/// the function declaration \p FD will become a member function
8279/// specialization.
8280///
Douglas Gregor86d142a2009-10-08 07:24:58 +00008281/// \param Member the member declaration, which will be updated to become a
8282/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008283///
John McCall1f82f242009-11-18 22:49:29 +00008284/// \param Previous the set of declarations, one of which may be specialized
8285/// by this function specialization; the set will be modified to contain the
8286/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008287bool
John McCall1f82f242009-11-18 22:49:29 +00008288Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008289 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00008290
Douglas Gregor86d142a2009-10-08 07:24:58 +00008291 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00008292 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00008293 NamedDecl *Instantiation = nullptr;
8294 NamedDecl *InstantiatedFrom = nullptr;
8295 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008296
John McCall1f82f242009-11-18 22:49:29 +00008297 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008298 // Nowhere to look anyway.
8299 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008300 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8301 I != E; ++I) {
8302 NamedDecl *D = (*I)->getUnderlyingDecl();
8303 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00008304 QualType Adjusted = Function->getType();
8305 if (!hasExplicitCallingConv(Adjusted))
8306 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8307 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008308 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008309 Instantiation = Method;
8310 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008311 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008312 break;
8313 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008314 }
8315 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00008316 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008317 VarDecl *PrevVar;
8318 if (Previous.isSingleResult() &&
8319 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00008320 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008321 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008322 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008323 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008324 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008325 }
8326 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008327 CXXRecordDecl *PrevRecord;
8328 if (Previous.isSingleResult() &&
8329 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008330 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008331 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008332 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008333 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008334 }
Richard Smith7d137e32012-03-23 03:33:32 +00008335 } else if (isa<EnumDecl>(Member)) {
8336 EnumDecl *PrevEnum;
8337 if (Previous.isSingleResult() &&
8338 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008339 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00008340 Instantiation = PrevEnum;
8341 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8342 MSInfo = PrevEnum->getMemberSpecializationInfo();
8343 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008344 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008345
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008346 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008347 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008348 // specializations are always out-of-line, the caller will complain about
8349 // this mismatch later.
8350 return false;
8351 }
John McCalle820e5e2010-04-13 20:37:33 +00008352
Richard Smith77e9e842017-05-09 23:02:10 +00008353 // A member specialization in a friend declaration isn't really declaring
8354 // an explicit specialization, just identifying a specific (possibly implicit)
8355 // specialization. Don't change the template specialization kind.
8356 //
8357 // FIXME: Is this really valid? Other compilers reject.
John McCalle820e5e2010-04-13 20:37:33 +00008358 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8359 // Preserve instantiation information.
8360 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8361 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8362 cast<CXXMethodDecl>(InstantiatedFrom),
8363 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8364 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8365 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8366 cast<CXXRecordDecl>(InstantiatedFrom),
8367 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8368 }
8369
8370 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008371 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00008372 return false;
8373 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008374
Douglas Gregor86d142a2009-10-08 07:24:58 +00008375 // Make sure that this is a specialization of a member.
8376 if (!InstantiatedFrom) {
8377 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8378 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008379 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8380 return true;
8381 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008382
Douglas Gregor06db9f52009-10-12 20:18:28 +00008383 // C++ [temp.expl.spec]p6:
8384 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00008385 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008386 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008387 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008388 // use occurs; no diagnostic is required.
8389 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00008390
Abramo Bagnara8075c852010-06-12 07:44:57 +00008391 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00008392 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8393 TSK_ExplicitSpecialization,
8394 Instantiation,
8395 MSInfo->getTemplateSpecializationKind(),
8396 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008397 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008398 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008399
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008400 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008401 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008402 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008403 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008404 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008405 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008406
Richard Smith77e9e842017-05-09 23:02:10 +00008407 // Note that this member specialization is an "instantiation of" the
8408 // corresponding member of the original template.
8409 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008410 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8411 if (InstantiationFunction->getTemplateSpecializationKind() ==
8412 TSK_ImplicitInstantiation) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008413 // Explicit specializations of member functions of class templates do not
8414 // inherit '=delete' from the member function they are specializing.
8415 if (InstantiationFunction->isDeleted()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008416 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008417 assert(InstantiationFunction->getCanonicalDecl() ==
8418 InstantiationFunction);
Richard Smith77e9e842017-05-09 23:02:10 +00008419 // FIXME: We need an update record for this AST mutation.
Richard Smith5f274382016-09-28 23:55:27 +00008420 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008421 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008423
Richard Smith77e9e842017-05-09 23:02:10 +00008424 MemberFunction->setInstantiationOfMemberFunction(
8425 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8426 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8427 MemberVar->setInstantiationOfStaticDataMember(
Larisse Voufo39a1e502013-08-06 01:03:05 +00008428 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008429 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8430 MemberClass->setInstantiationOfMemberClass(
8431 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8432 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8433 MemberEnum->setInstantiationOfMemberEnum(
Richard Smith7d137e32012-03-23 03:33:32 +00008434 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008435 } else {
8436 llvm_unreachable("unknown member specialization kind");
Douglas Gregor86d142a2009-10-08 07:24:58 +00008437 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008438
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008439 // Save the caller the trouble of having to figure out which declaration
8440 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008441 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008442 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008443 return false;
8444}
8445
Richard Smith77e9e842017-05-09 23:02:10 +00008446/// Complete the explicit specialization of a member of a class template by
8447/// updating the instantiated member to be marked as an explicit specialization.
8448///
8449/// \param OrigD The member declaration instantiated from the template.
8450/// \param Loc The location of the explicit specialization of the member.
8451template<typename DeclT>
8452static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8453 SourceLocation Loc) {
8454 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8455 return;
8456
8457 // FIXME: Inform AST mutation listeners of this AST mutation.
8458 // FIXME: If there are multiple in-class declarations of the member (from
8459 // multiple modules, or a declaration and later definition of a member type),
8460 // should we update all of them?
8461 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8462 OrigD->setLocation(Loc);
8463}
8464
8465void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8466 LookupResult &Previous) {
8467 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8468 if (Instantiation == Member)
8469 return;
8470
8471 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8472 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8473 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8474 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8475 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8476 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8477 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8478 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8479 else
8480 llvm_unreachable("unknown member specialization kind");
8481}
8482
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008483/// Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008484///
8485/// \returns true if a serious error occurs, false otherwise.
8486static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008487 SourceLocation InstLoc,
8488 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008489 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8490 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008491
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008492 if (CurContext->isRecord()) {
8493 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8494 << D;
8495 return true;
8496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008497
Richard Smith050d2612011-10-18 02:28:33 +00008498 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008499 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008500 // template. If the name declared in the explicit instantiation is an
8501 // unqualified name, the explicit instantiation shall appear in the
8502 // namespace where its template is declared or, if that namespace is inline
8503 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008504 //
8505 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008506 if (WasQualifiedName) {
8507 if (CurContext->Encloses(OrigContext))
8508 return false;
8509 } else {
8510 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8511 return false;
8512 }
8513
8514 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8515 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008516 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008517 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008518 diag::err_explicit_instantiation_out_of_scope :
8519 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008520 << D << NS;
8521 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008522 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008523 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008524 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8525 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8526 << D << NS;
8527 } else
8528 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008529 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008530 diag::err_explicit_instantiation_must_be_global :
8531 diag::warn_explicit_instantiation_must_be_global_0x)
8532 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008533 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008534 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008535}
8536
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008537/// Determine whether the given scope specifier has a template-id in it.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008538static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8539 if (!SS.isSet())
8540 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008541
Richard Smith050d2612011-10-18 02:28:33 +00008542 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008543 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008544 // or a static data member of a class template specialization, the name of
8545 // the class template specialization in the qualified-id for the member
8546 // name shall be a simple-template-id.
8547 //
8548 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008549 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8550 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008551 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008552 if (isa<TemplateSpecializationType>(T))
8553 return true;
8554
8555 return false;
8556}
8557
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008558/// Make a dllexport or dllimport attr on a class template specialization take
8559/// effect.
8560static void dllExportImportClassTemplateSpecialization(
8561 Sema &S, ClassTemplateSpecializationDecl *Def) {
8562 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8563 assert(A && "dllExportImportClassTemplateSpecialization called "
8564 "on Def without dllexport or dllimport");
8565
8566 // We reject explicit instantiations in class scope, so there should
8567 // never be any delayed exported classes to worry about.
8568 assert(S.DelayedDllExportClasses.empty() &&
8569 "delayed exports present at explicit instantiation");
8570 S.checkClassLevelDLLAttribute(Def);
8571
8572 // Propagate attribute to base class templates.
8573 for (auto &B : Def->bases()) {
8574 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8575 B.getType()->getAsCXXRecordDecl()))
8576 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8577 }
8578
8579 S.referenceDLLExportedClassMethods();
8580}
8581
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008582// Explicit instantiation of a class template specialization
Erich Keanec480f302018-07-12 21:09:05 +00008583DeclResult Sema::ActOnExplicitInstantiation(
8584 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8585 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8586 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
8587 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
8588 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008589 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008590 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008591 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008592 // Check that the specialization uses the same tag kind as the
8593 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008594 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8595 assert(Kind != TTK_Enum &&
8596 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008597
Richard Trieu265c3442016-04-05 21:13:54 +00008598 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8599
8600 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008601 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8602 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008603 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008604 return true;
8605 }
8606
Douglas Gregord9034f02009-05-14 16:41:31 +00008607 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008608 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008609 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008610 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008611 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008612 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008613 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008614 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008615 diag::note_previous_use);
8616 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8617 }
8618
Douglas Gregore47f5a72009-10-14 23:41:34 +00008619 // C++0x [temp.explicit]p2:
8620 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008621 // definition and an explicit instantiation declaration. An explicit
8622 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008623 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8624 ? TSK_ExplicitInstantiationDefinition
8625 : TSK_ExplicitInstantiationDeclaration;
8626
8627 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8628 // Check for dllexport class template instantiation declarations.
Erich Keanee891aa92018-07-13 15:07:47 +00008629 for (const ParsedAttr &AL : Attr) {
8630 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00008631 Diag(ExternLoc,
8632 diag::warn_attribute_dllexport_explicit_instantiation_decl);
Erich Keanec480f302018-07-12 21:09:05 +00008633 Diag(AL.getLoc(), diag::note_attribute);
Hans Wennborgfd76d912015-01-15 21:18:30 +00008634 break;
8635 }
8636 }
8637
8638 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8639 Diag(ExternLoc,
8640 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8641 Diag(A->getLocation(), diag::note_attribute);
8642 }
8643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008644
Hans Wennborga86a83b2016-05-26 19:42:56 +00008645 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8646 // instantiation declarations for most purposes.
8647 bool DLLImportExplicitInstantiationDef = false;
8648 if (TSK == TSK_ExplicitInstantiationDefinition &&
8649 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8650 // Check for dllimport class template instantiation definitions.
8651 bool DLLImport =
8652 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
Erich Keanee891aa92018-07-13 15:07:47 +00008653 for (const ParsedAttr &AL : Attr) {
8654 if (AL.getKind() == ParsedAttr::AT_DLLImport)
Hans Wennborga86a83b2016-05-26 19:42:56 +00008655 DLLImport = true;
Erich Keanee891aa92018-07-13 15:07:47 +00008656 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborga86a83b2016-05-26 19:42:56 +00008657 // dllexport trumps dllimport here.
8658 DLLImport = false;
8659 break;
8660 }
8661 }
8662 if (DLLImport) {
8663 TSK = TSK_ExplicitInstantiationDeclaration;
8664 DLLImportExplicitInstantiationDef = true;
8665 }
8666 }
8667
Douglas Gregora1f49972009-05-13 00:25:59 +00008668 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008669 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008670 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008671
8672 // Check that the template argument list is well-formed for this
8673 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008674 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008675 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8676 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008677 return true;
8678
Douglas Gregora1f49972009-05-13 00:25:59 +00008679 // Find the class template specialization declaration that
8680 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008681 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008682 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008683 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008684
Abramo Bagnara8075c852010-06-12 07:44:57 +00008685 TemplateSpecializationKind PrevDecl_TSK
8686 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8687
Douglas Gregor54888652009-10-07 00:13:32 +00008688 // C++0x [temp.explicit]p2:
8689 // [...] An explicit instantiation shall appear in an enclosing
8690 // namespace of its template. [...]
8691 //
8692 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008693 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8694 SS.isSet()))
8695 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008696
Craig Topperc3ec1492014-05-26 06:22:03 +00008697 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008698
Abramo Bagnara8075c852010-06-12 07:44:57 +00008699 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008700 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008701 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008702 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008703 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008704 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008705 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008706
Abramo Bagnara8075c852010-06-12 07:44:57 +00008707 // Even though HasNoEffect == true means that this explicit instantiation
8708 // has no effect on semantics, we go on to put its syntax in the AST.
8709
8710 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8711 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008712 // Since the only prior class template specialization with these
8713 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008714 // declaration node as our own, updating the source location
8715 // for the template name to reflect our new declaration.
8716 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008717 Specialization = PrevDecl;
8718 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008719 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008720 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008721
8722 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8723 DLLImportExplicitInstantiationDef) {
8724 // The new specialization might add a dllimport attribute.
8725 HasNoEffect = false;
8726 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008727 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008728
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008729 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008730 // Create a new class template specialization declaration node for
8731 // this explicit specialization.
8732 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008733 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008734 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008735 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008736 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008737 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008738 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00008739 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008740
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008741 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008742 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008743 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008744 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008745 }
8746
8747 // Build the fully-sugared type for this explicit instantiation as
8748 // the user wrote in the explicit instantiation itself. This means
8749 // that we'll pretty-print the type retrieved from the
8750 // specialization's declaration the way that the user actually wrote
8751 // the explicit instantiation, rather than formatting the name based
8752 // on the "canonical" representation used to store the template
8753 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008754 TypeSourceInfo *WrittenTy
8755 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8756 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008757 Context.getTypeDeclType(Specialization));
8758 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008759
Abramo Bagnara8075c852010-06-12 07:44:57 +00008760 // Set source locations for keywords.
8761 Specialization->setExternLoc(ExternLoc);
8762 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008763 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008764
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008765 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Erich Keanec480f302018-07-12 21:09:05 +00008766 ProcessDeclAttributeList(S, Specialization, Attr);
Rafael Espindola0b062072012-01-03 06:04:21 +00008767
Abramo Bagnara8075c852010-06-12 07:44:57 +00008768 // Add the explicit instantiation into its lexical context. However,
8769 // since explicit instantiations are never found by name lookup, we
8770 // just put it into the declaration context directly.
8771 Specialization->setLexicalDeclContext(CurContext);
8772 CurContext->addDecl(Specialization);
8773
8774 // Syntax is now OK, so return if it has no other effect on semantics.
8775 if (HasNoEffect) {
8776 // Set the template specialization kind.
8777 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008778 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008779 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008780
8781 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008782 // A definition of a class template or class member template
8783 // shall be in scope at the point of the explicit instantiation of
8784 // the class template or class member template.
8785 //
8786 // This check comes when we actually try to perform the
8787 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008788 ClassTemplateSpecializationDecl *Def
8789 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008790 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008791 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00008792 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008793 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008794 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008795 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8796 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008797
Douglas Gregor1d957a32009-10-27 18:42:08 +00008798 // Instantiate the members of this class template specialization.
8799 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008800 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00008801 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008802 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008803 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8804 // TSK_ExplicitInstantiationDefinition
8805 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00008806 (TSK == TSK_ExplicitInstantiationDefinition ||
8807 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00008808 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008809 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008810
Hans Wennborgc0875502015-06-09 00:39:05 +00008811 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00008812 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8813 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00008814 // In the MS ABI, an explicit instantiation definition can add a dll
8815 // attribute to a template with a previous instantiation declaration.
8816 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008817 auto *A = cast<InheritableAttr>(
8818 getDLLAttr(Specialization)->clone(getASTContext()));
8819 A->setInherited(true);
8820 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008821 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008822 }
8823 }
8824
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008825 // Fix a TSK_ImplicitInstantiation followed by a
8826 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008827 bool NewlyDLLExported =
8828 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8829 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008830 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8831 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8832 // In the MS ABI, an explicit instantiation definition can add a dll
8833 // attribute to a template with a previous implicit instantiation.
8834 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8835 // avoid potentially strange codegen behavior. For example, if we extend
8836 // this conditional to dllimport, and we have a source file calling a
8837 // method on an implicitly instantiated template class instance and then
8838 // declaring a dllimport explicit instantiation definition for the same
8839 // template class, the codegen for the method call will not respect the
8840 // dllimport, while it will with cl. The Def will already have the DLL
8841 // attribute, since the Def and Specialization will be the same in the
8842 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8843 // attribute to the Specialization; we just need to make it take effect.
8844 assert(Def == Specialization &&
8845 "Def and Specialization should match for implicit instantiation");
8846 dllExportImportClassTemplateSpecialization(*this, Def);
8847 }
8848
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008849 // Set the template specialization kind. Make sure it is set before
8850 // instantiating the members which will trigger ASTConsumer callbacks.
8851 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008852 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008853 } else {
8854
8855 // Set the template specialization kind.
8856 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008857 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008858
John McCall48871652010-08-21 09:40:31 +00008859 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008860}
8861
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008862// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008863DeclResult
Erich Keanec480f302018-07-12 21:09:05 +00008864Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
8865 SourceLocation TemplateLoc, unsigned TagSpec,
8866 SourceLocation KWLoc, CXXScopeSpec &SS,
8867 IdentifierInfo *Name, SourceLocation NameLoc,
8868 const ParsedAttributesView &Attr) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008869
Douglas Gregord6ab8742009-05-28 23:31:59 +00008870 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008871 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008872 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008873 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008874 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008875 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008876 SourceLocation(), false, TypeResult(),
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00008877 /*IsTypeSpecifier*/false,
8878 /*IsTemplateParamOrArg*/false);
John McCall7f41d982009-09-11 04:59:25 +00008879 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8880
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008881 if (!TagD)
8882 return true;
8883
John McCall48871652010-08-21 09:40:31 +00008884 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00008885 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008886
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008887 if (Tag->isInvalidDecl())
8888 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008889
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008890 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8891 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8892 if (!Pattern) {
8893 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8894 << Context.getTypeDeclType(Record);
8895 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8896 return true;
8897 }
8898
Douglas Gregore47f5a72009-10-14 23:41:34 +00008899 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008900 // If the explicit instantiation is for a class or member class, the
8901 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00008902 // simple-template-id.
8903 //
8904 // C++98 has the same restriction, just worded differently.
8905 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00008906 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008907 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008908
Douglas Gregore47f5a72009-10-14 23:41:34 +00008909 // C++0x [temp.explicit]p2:
8910 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008911 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00008912 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00008913 TemplateSpecializationKind TSK
8914 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8915 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008916
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008917 // C++0x [temp.explicit]p2:
8918 // [...] An explicit instantiation shall appear in an enclosing
8919 // namespace of its template. [...]
8920 //
8921 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008922 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008923
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008924 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008925 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00008926 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008927 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00008928 PrevDecl = Record;
8929 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008930 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008931 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008932 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008933 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008934 PrevDecl,
8935 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008936 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008937 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008938 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00008939 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008940 return TagD;
8941 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008942
Douglas Gregor12e49d32009-10-15 22:53:21 +00008943 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008944 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008945 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00008946 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008947 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00008948 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008949 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008950 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00008951 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00008952 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8953 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00008954 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8955 << Pattern;
8956 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008957 } else {
8958 if (InstantiateClass(NameLoc, Record, Def,
8959 getTemplateInstantiationArgs(Record),
8960 TSK))
8961 return true;
8962
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008963 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00008964 if (!RecordDef)
8965 return true;
8966 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008967 }
8968
Douglas Gregor1d957a32009-10-27 18:42:08 +00008969 // Instantiate all of the members of the class.
8970 InstantiateClassMembers(NameLoc, RecordDef,
8971 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008972
Douglas Gregor88d292c2010-05-13 16:44:06 +00008973 if (TSK == TSK_ExplicitInstantiationDefinition)
8974 MarkVTableUsed(NameLoc, RecordDef, true);
8975
Mike Stump87c57ac2009-05-16 07:39:55 +00008976 // FIXME: We don't have any representation for explicit instantiations of
8977 // member classes. Such a representation is not needed for compilation, but it
8978 // should be available for clients that want to see all of the declarations in
8979 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008980 return TagD;
8981}
8982
John McCallfaf5fb42010-08-26 23:41:50 +00008983DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8984 SourceLocation ExternLoc,
8985 SourceLocation TemplateLoc,
8986 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008987 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008988 // TODO: check if/when DNInfo should replace Name.
8989 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8990 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00008991 if (!Name) {
8992 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008993 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008994 diag::err_explicit_instantiation_requires_name)
8995 << D.getDeclSpec().getSourceRange()
8996 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008997
Douglas Gregor450f00842009-09-25 18:43:00 +00008998 return true;
8999 }
9000
9001 // The scope passed in may not be a decl scope. Zip up the scope tree until
9002 // we find one that is.
9003 while ((S->getFlags() & Scope::DeclScope) == 0 ||
9004 (S->getFlags() & Scope::TemplateParamScope) != 0)
9005 S = S->getParent();
9006
9007 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00009008 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9009 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00009010 if (R.isNull())
9011 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009012
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009013 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00009014 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009015 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00009016 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009017 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9018 << Name;
9019 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009020 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009021 != DeclSpec::SCS_unspecified) {
9022 // Complain about then remove the storage class specifier.
9023 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9024 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009025
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009026 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00009027 }
9028
Douglas Gregor3c74d412009-10-14 20:14:33 +00009029 // C++0x [temp.explicit]p1:
9030 // [...] An explicit instantiation of a function template shall not use the
9031 // inline or constexpr specifiers.
9032 // Presumably, this also applies to member functions of class templates as
9033 // well.
Richard Smith83c19292011-10-18 03:44:03 +00009034 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009035 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009036 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00009037 diag::err_explicit_instantiation_inline :
9038 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00009039 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009040 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00009041 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9042 // not already specified.
9043 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9044 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009045
Richard Smith19a311a2017-02-09 22:47:51 +00009046 // A deduction guide is not on the list of entities that can be explicitly
9047 // instantiated.
9048 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9049 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
9050 << /*explicit instantiation*/ 0;
9051 return true;
9052 }
9053
Douglas Gregore47f5a72009-10-14 23:41:34 +00009054 // C++0x [temp.explicit]p2:
9055 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009056 // definition and an explicit instantiation declaration. An explicit
9057 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00009058 TemplateSpecializationKind TSK
9059 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9060 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009061
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009062 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00009063 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00009064
9065 if (!R->isFunctionType()) {
9066 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009067 // A [...] static data member of a class template can be explicitly
9068 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009069 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009070 // C++1y [temp.explicit]p1:
9071 // A [...] variable [...] template specialization can be explicitly
9072 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00009073 if (Previous.isAmbiguous())
9074 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009075
John McCall67c00872009-12-02 08:25:40 +00009076 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00009077 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009078
Larisse Voufo39a1e502013-08-06 01:03:05 +00009079 if (!PrevTemplate) {
9080 if (!Prev || !Prev->isStaticDataMember()) {
9081 // We expect to see a data data member here.
9082 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9083 << Name;
9084 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9085 P != PEnd; ++P)
9086 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9087 return true;
9088 }
9089
9090 if (!Prev->getInstantiatedFromStaticDataMember()) {
9091 // FIXME: Check for explicit specialization?
9092 Diag(D.getIdentifierLoc(),
9093 diag::err_explicit_instantiation_data_member_not_instantiated)
9094 << Prev;
9095 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9096 // FIXME: Can we provide a note showing where this was declared?
9097 return true;
9098 }
9099 } else {
9100 // Explicitly instantiate a variable template.
9101
9102 // C++1y [dcl.spec.auto]p6:
9103 // ... A program that uses auto or decltype(auto) in a context not
9104 // explicitly allowed in this section is ill-formed.
9105 //
9106 // This includes auto-typed variable template instantiations.
9107 if (R->isUndeducedType()) {
9108 Diag(T->getTypeLoc().getLocStart(),
9109 diag::err_auto_not_allowed_var_inst);
9110 return true;
9111 }
9112
Faisal Vali2ab8c152017-12-30 04:15:27 +00009113 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Richard Smithef985ac2013-09-18 02:10:12 +00009114 // C++1y [temp.explicit]p3:
9115 // If the explicit instantiation is for a variable, the unqualified-id
9116 // in the declaration shall be a template-id.
9117 Diag(D.getIdentifierLoc(),
9118 diag::err_explicit_instantiation_without_template_id)
9119 << PrevTemplate;
9120 Diag(PrevTemplate->getLocation(),
9121 diag::note_explicit_instantiation_here);
9122 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00009123 }
9124
Richard Smithef985ac2013-09-18 02:10:12 +00009125 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00009126 TemplateArgumentListInfo TemplateArgs =
9127 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00009128
Larisse Voufo39a1e502013-08-06 01:03:05 +00009129 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9130 D.getIdentifierLoc(), TemplateArgs);
9131 if (Res.isInvalid())
9132 return true;
9133
9134 // Ignore access control bits, we don't need them for redeclaration
9135 // checking.
9136 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00009137 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009138
Douglas Gregore47f5a72009-10-14 23:41:34 +00009139 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009140 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009141 // or a static data member of a class template specialization, the name of
9142 // the class template specialization in the qualified-id for the member
9143 // name shall be a simple-template-id.
9144 //
9145 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009146 //
Richard Smith5977d872013-09-18 21:55:14 +00009147 // This does not apply to variable template specializations, where the
9148 // template-id is in the unqualified-id instead.
9149 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009150 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009151 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009152 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009153
Douglas Gregore47f5a72009-10-14 23:41:34 +00009154 // Check the scope of this explicit instantiation.
9155 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009156
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009157 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00009158 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9159 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009160 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009161 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00009162 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009163 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009164
Larisse Voufo39a1e502013-08-06 01:03:05 +00009165 if (!HasNoEffect) {
9166 // Instantiate static data member or variable template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009167 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9168 if (PrevTemplate) {
9169 // Merge attributes.
Erich Keanec480f302018-07-12 21:09:05 +00009170 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009171 }
9172 if (TSK == TSK_ExplicitInstantiationDefinition)
9173 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9174 }
9175
9176 // Check the new variable specialization against the parsed input.
9177 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9178 Diag(T->getTypeLoc().getLocStart(),
9179 diag::err_invalid_var_template_spec_type)
9180 << 0 << PrevTemplate << R << Prev->getType();
9181 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9182 << 2 << PrevTemplate->getDeclName();
9183 return true;
9184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009185
Douglas Gregor450f00842009-09-25 18:43:00 +00009186 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00009187 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009189
9190 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00009191 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00009192 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00009193 TemplateArgumentListInfo TemplateArgs;
Faisal Vali2ab8c152017-12-30 04:15:27 +00009194 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00009195 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00009196 HasExplicitTemplateArgs = true;
9197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009198
Douglas Gregor450f00842009-09-25 18:43:00 +00009199 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009200 // A [...] function [...] can be explicitly instantiated from its template.
9201 // A member function [...] of a class template can be explicitly
9202 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009203 // template.
John McCall27c11dd2017-06-07 23:00:05 +00009204 UnresolvedSet<8> TemplateMatches;
9205 FunctionDecl *NonTemplateMatch = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009206 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00009207 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9208 P != PEnd; ++P) {
9209 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00009210 if (!HasExplicitTemplateArgs) {
9211 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00009212 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9213 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00009214 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
John McCall27c11dd2017-06-07 23:00:05 +00009215 if (Method->getPrimaryTemplate()) {
9216 TemplateMatches.addDecl(Method, P.getAccess());
9217 } else {
9218 // FIXME: Can this assert ever happen? Needs a test.
9219 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9220 NonTemplateMatch = Method;
9221 }
Douglas Gregord90fd522009-09-25 21:45:23 +00009222 }
Douglas Gregor450f00842009-09-25 18:43:00 +00009223 }
9224 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009225
Douglas Gregor450f00842009-09-25 18:43:00 +00009226 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9227 if (!FunTmpl)
9228 continue;
9229
Larisse Voufo98b20f12013-07-19 23:00:19 +00009230 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00009231 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009232 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009233 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00009234 (HasExplicitTemplateArgs ? &TemplateArgs
9235 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00009236 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009237 // Keep track of almost-matches.
9238 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00009239 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009240 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00009241 (void)TDK;
9242 continue;
9243 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009244
Artem Belevich64135c32016-12-08 19:38:13 +00009245 // Target attributes are part of the cuda function signature, so
9246 // the cuda target of the instantiated function must match that of its
9247 // template. Given that C++ template deduction does not take
9248 // target attributes into account, we reject candidates here that
9249 // have a different target.
9250 if (LangOpts.CUDA &&
9251 IdentifyCUDATarget(Specialization,
9252 /* IgnoreImplicitHDAttributes = */ true) !=
Erich Keanec480f302018-07-12 21:09:05 +00009253 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
Artem Belevich64135c32016-12-08 19:38:13 +00009254 FailedCandidates.addCandidate().set(
9255 P.getPair(), FunTmpl->getTemplatedDecl(),
9256 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9257 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009258 }
9259
John McCall27c11dd2017-06-07 23:00:05 +00009260 TemplateMatches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00009261 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009262
John McCall27c11dd2017-06-07 23:00:05 +00009263 FunctionDecl *Specialization = NonTemplateMatch;
9264 if (!Specialization) {
9265 // Find the most specialized function template specialization.
9266 UnresolvedSetIterator Result = getMostSpecialized(
9267 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9268 D.getIdentifierLoc(),
9269 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9270 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9271 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00009272
John McCall27c11dd2017-06-07 23:00:05 +00009273 if (Result == TemplateMatches.end())
9274 return true;
John McCall58cc69d2010-01-27 01:50:18 +00009275
John McCall27c11dd2017-06-07 23:00:05 +00009276 // Ignore access control bits, we don't need them for redeclaration checking.
9277 Specialization = cast<FunctionDecl>(*Result);
9278 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009279
Alexey Bataev73983912014-11-06 10:10:50 +00009280 // C++11 [except.spec]p4
9281 // In an explicit instantiation an exception-specification may be specified,
9282 // but is not required.
9283 // If an exception-specification is specified in an explicit instantiation
9284 // directive, it shall be compatible with the exception-specifications of
9285 // other declarations of that function.
9286 if (auto *FPT = R->getAs<FunctionProtoType>())
9287 if (FPT->hasExceptionSpec()) {
9288 unsigned DiagID =
9289 diag::err_mismatched_exception_spec_explicit_instantiation;
9290 if (getLangOpts().MicrosoftExt)
9291 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9292 bool Result = CheckEquivalentExceptionSpec(
9293 PDiag(DiagID) << Specialization->getType(),
9294 PDiag(diag::note_explicit_instantiation_here),
9295 Specialization->getType()->getAs<FunctionProtoType>(),
9296 Specialization->getLocation(), FPT, D.getLocStart());
9297 // In Microsoft mode, mismatching exception specifications just cause a
9298 // warning.
9299 if (!getLangOpts().MicrosoftExt && Result)
9300 return true;
9301 }
9302
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009303 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009304 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009305 diag::err_explicit_instantiation_member_function_not_instantiated)
9306 << Specialization
9307 << (Specialization->getTemplateSpecializationKind() ==
9308 TSK_ExplicitSpecialization);
9309 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9310 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009311 }
9312
Douglas Gregorec9fd132012-01-14 16:38:05 +00009313 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00009314 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9315 PrevDecl = Specialization;
9316
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009317 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00009318 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009319 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009320 PrevDecl,
9321 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009322 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009323 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009324 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009325
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009326 // FIXME: We may still want to build some representation of this
9327 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00009328 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00009329 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009330 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00009331
Erich Keanec480f302018-07-12 21:09:05 +00009332 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009333
Hans Wennborgb8304a62017-11-29 23:44:11 +00009334 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9335 // instantiation declarations.
9336 if (TSK == TSK_ExplicitInstantiationDefinition &&
9337 Specialization->hasAttr<DLLImportAttr>() &&
9338 Context.getTargetInfo().getCXXABI().isMicrosoft())
9339 TSK = TSK_ExplicitInstantiationDeclaration;
9340
9341 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9342
Richard Smitheb36ddf2014-04-24 22:45:46 +00009343 if (Specialization->isDefined()) {
9344 // Let the ASTConsumer know that this function has been explicitly
9345 // instantiated now, and its linkage might have changed.
9346 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9347 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00009348 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009349
Douglas Gregore47f5a72009-10-14 23:41:34 +00009350 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009351 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009352 // or a static data member of a class template specialization, the name of
9353 // the class template specialization in the qualified-id for the member
9354 // name shall be a simple-template-id.
9355 //
9356 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009357 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Faisal Vali2ab8c152017-12-30 04:15:27 +00009358 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009359 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00009360 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009361 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009362 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009363 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009364
Douglas Gregore47f5a72009-10-14 23:41:34 +00009365 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009366 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00009367 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009368 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00009369 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009370
Douglas Gregor450f00842009-09-25 18:43:00 +00009371 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00009372 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009373}
9374
John McCallfaf5fb42010-08-26 23:41:50 +00009375TypeResult
Faisal Vali090da2d2018-01-01 18:23:28 +00009376Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
John McCall7f41d982009-09-11 04:59:25 +00009377 const CXXScopeSpec &SS, IdentifierInfo *Name,
9378 SourceLocation TagLoc, SourceLocation NameLoc) {
9379 // This has to hold, because SS is expected to be defined.
9380 assert(Name && "Expected a name in a dependent tag");
9381
Aaron Ballman4a979672014-01-03 13:56:08 +00009382 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009383 if (!NNS)
9384 return true;
9385
Abramo Bagnara6150c882010-05-11 21:36:43 +00009386 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009387
Douglas Gregorba41d012010-04-24 16:38:41 +00009388 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9389 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009390 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009391 return true;
9392 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009393
Douglas Gregore7c20652011-03-02 00:47:37 +00009394 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009395 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009396 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009397
Douglas Gregore7c20652011-03-02 00:47:37 +00009398 // Create type-source location information for this type.
9399 TypeLocBuilder TLB;
9400 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009401 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009402 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9403 TL.setNameLoc(NameLoc);
9404 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009405}
9406
John McCallfaf5fb42010-08-26 23:41:50 +00009407TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009408Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9409 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009410 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009411 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009412 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009413
Richard Smith0bf8a4922011-10-18 20:49:44 +00009414 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9415 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009416 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009417 diag::warn_cxx98_compat_typename_outside_of_template :
9418 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009419 << FixItHint::CreateRemoval(TypenameLoc);
9420
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009421 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009422 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9423 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009424 if (T.isNull())
9425 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009426
9427 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9428 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009429 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009430 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009431 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009432 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009433 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009434 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009435 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009436 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009437 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009438 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009439
John McCallba7bf592010-08-24 05:47:05 +00009440 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009441}
9442
John McCallfaf5fb42010-08-26 23:41:50 +00009443TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009444Sema::ActOnTypenameType(Scope *S,
9445 SourceLocation TypenameLoc,
9446 const CXXScopeSpec &SS,
9447 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009448 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009449 IdentifierInfo *TemplateII,
9450 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009451 SourceLocation LAngleLoc,
9452 ASTTemplateArgsPtr TemplateArgsIn,
9453 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009454 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9455 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009456 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009457 diag::warn_cxx98_compat_typename_outside_of_template :
9458 diag::ext_typename_outside_of_template)
9459 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009460
Richard Smith74f02342017-01-19 21:00:13 +00009461 // Strangely, non-type results are not ignored by this lookup, so the
9462 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009463 if (TypenameLoc.isValid()) {
9464 auto *LookupRD =
9465 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9466 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9467 Diag(TemplateIILoc,
9468 diag::ext_out_of_line_qualified_id_type_names_constructor)
9469 << TemplateII << 0 /*injected-class-name used as template name*/
9470 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9471 }
Richard Smith74f02342017-01-19 21:00:13 +00009472 }
9473
Douglas Gregorb09518c2011-02-27 22:46:49 +00009474 // Translate the parser's template argument list in our AST format.
9475 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9476 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009477
Douglas Gregorb09518c2011-02-27 22:46:49 +00009478 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009479 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9480 // Construct a dependent template specialization type.
9481 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009482 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009483 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9484 DTN->getQualifier(),
9485 DTN->getIdentifier(),
9486 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009487
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009488 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009489 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009490 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009491 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009492 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9493 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009494 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009495 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009496 SpecTL.setLAngleLoc(LAngleLoc);
9497 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009498 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9499 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009500 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009501 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009502
Richard Smith74f02342017-01-19 21:00:13 +00009503 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009504 if (T.isNull())
9505 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009506
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009507 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009508 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009509 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009510 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009511 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009512 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009513 SpecTL.setLAngleLoc(LAngleLoc);
9514 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009515 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9516 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009517
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009518 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9519 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009520 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009521 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009522
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009523 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9524 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009525}
9526
Douglas Gregorb09518c2011-02-27 22:46:49 +00009527
Richard Smith6f8d2c62012-05-09 05:17:00 +00009528/// Determine whether this failed name lookup should be treated as being
9529/// disabled by a usage of std::enable_if.
9530static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009531 SourceRange &CondRange, Expr *&Cond) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009532 // We must be looking for a ::type...
9533 if (!II.isStr("type"))
9534 return false;
9535
9536 // ... within an explicitly-written template specialization...
9537 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9538 return false;
9539 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009540 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9541 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9542 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009543 return false;
George Burgess IV00f70bd2018-03-01 05:43:23 +00009544 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009545
9546 // ... which names a complete class template declaration...
9547 const TemplateDecl *EnableIfDecl =
9548 EnableIfTST->getTemplateName().getAsTemplateDecl();
9549 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9550 return false;
9551
9552 // ... called "enable_if".
9553 const IdentifierInfo *EnableIfII =
9554 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9555 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9556 return false;
9557
9558 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009559 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009560
9561 // Dig out the condition.
9562 Cond = nullptr;
9563 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9564 != TemplateArgument::Expression)
9565 return true;
9566
9567 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9568
9569 // Ignore Boolean literals; they add no value.
9570 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9571 Cond = nullptr;
9572
Richard Smith6f8d2c62012-05-09 05:17:00 +00009573 return true;
9574}
9575
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009576/// Build the type that describes a C++ typename specifier,
Douglas Gregor333489b2009-03-27 23:10:48 +00009577/// e.g., "typename T::type".
9578QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009579Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009580 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009581 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009582 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009583 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009584 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009585 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009586
John McCall0b66eb32010-05-01 00:40:08 +00009587 DeclContext *Ctx = computeDeclContext(SS);
9588 if (!Ctx) {
9589 // If the nested-name-specifier is dependent and couldn't be
9590 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009591 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009592 return Context.getDependentNameType(Keyword,
9593 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009594 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009595 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009596
John McCall0b66eb32010-05-01 00:40:08 +00009597 // If the nested-name-specifier refers to the current instantiation,
9598 // the "typename" keyword itself is superfluous. In C++03, the
9599 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9600 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009601 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009602
John McCall0b66eb32010-05-01 00:40:08 +00009603 if (RequireCompleteDeclContext(SS, Ctx))
9604 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009605
9606 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009607 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009608 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009609 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009610 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009611 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009612 case LookupResult::NotFound: {
9613 // If we're looking up 'type' within a template named 'enable_if', produce
9614 // a more specific diagnostic.
9615 SourceRange CondRange;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009616 Expr *Cond = nullptr;
9617 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9618 // If we have a condition, narrow it down to the specific failed
9619 // condition.
9620 if (Cond) {
9621 Expr *FailedCond;
9622 std::string FailedDescription;
9623 std::tie(FailedCond, FailedDescription) =
Douglas Gregor672281a2017-09-14 23:38:42 +00009624 findFailedBooleanCondition(Cond, /*AllowTopLevelCond=*/true);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009625
9626 Diag(FailedCond->getExprLoc(),
9627 diag::err_typename_nested_not_found_requirement)
9628 << FailedDescription
9629 << FailedCond->getSourceRange();
9630 return QualType();
9631 }
9632
Richard Smith6f8d2c62012-05-09 05:17:00 +00009633 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009634 << Ctx << CondRange;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009635 return QualType();
9636 }
9637
Douglas Gregore40876a2009-10-13 21:16:44 +00009638 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009639 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009640 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009641
9642 case LookupResult::FoundUnresolvedValue: {
9643 // We found a using declaration that is a value. Most likely, the using
9644 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009645 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009646 IILoc);
9647 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9648 << Name << Ctx << FullRange;
9649 if (UnresolvedUsingValueDecl *Using
9650 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009651 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009652 Diag(Loc, diag::note_using_value_decl_missing_typename)
9653 << FixItHint::CreateInsertion(Loc, "typename ");
9654 }
9655 }
9656 // Fall through to create a dependent typename type, from which we can recover
9657 // better.
Galina Kistanova3779cb32017-06-07 06:25:05 +00009658 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009659
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009660 case LookupResult::NotFoundInCurrentInstantiation:
9661 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009662 return Context.getDependentNameType(Keyword,
9663 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009664 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009665
9666 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009667 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009668 // C++ [class.qual]p2:
9669 // In a lookup in which function names are not ignored and the
9670 // nested-name-specifier nominates a class C, if the name specified
9671 // after the nested-name-specifier, when looked up in C, is the
9672 // injected-class-name of C [...] then the name is instead considered
9673 // to name the constructor of class C.
9674 //
9675 // Unlike in an elaborated-type-specifier, function names are not ignored
9676 // in typename-specifier lookup. However, they are ignored in all the
9677 // contexts where we form a typename type with no keyword (that is, in
9678 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9679 //
9680 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9681 // ignore functions, but that appears to be an oversight.
9682 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9683 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9684 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9685 FoundRD->isInjectedClassName() &&
9686 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9687 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9688 << &II << 1 << 0 /*'typename' keyword used*/;
9689
Abramo Bagnara6150c882010-05-11 21:36:43 +00009690 // We found a type. Build an ElaboratedType, since the
9691 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009692 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009693 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009694 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009695 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009696 }
9697
Richard Smithee579842017-01-30 20:39:26 +00009698 // C++ [dcl.type.simple]p2:
9699 // A type-specifier of the form
9700 // typename[opt] nested-name-specifier[opt] template-name
9701 // is a placeholder for a deduced class type [...].
Aaron Ballmanc351fba2017-12-04 20:27:34 +00009702 if (getLangOpts().CPlusPlus17) {
Richard Smithee579842017-01-30 20:39:26 +00009703 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9704 return Context.getElaboratedType(
9705 Keyword, QualifierLoc.getNestedNameSpecifier(),
9706 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9707 QualType(), false));
9708 }
9709 }
Richard Smith600b5262017-01-26 20:40:47 +00009710
Douglas Gregor333489b2009-03-27 23:10:48 +00009711 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009712 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009713 break;
9714
9715 case LookupResult::FoundOverloaded:
9716 DiagID = diag::err_typename_nested_not_type;
9717 Referenced = *Result.begin();
9718 break;
9719
John McCall6538c932009-10-10 05:48:19 +00009720 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009721 return QualType();
9722 }
9723
9724 // If we get here, it's because name lookup did not find a
9725 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009726 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009727 IILoc);
9728 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009729 if (Referenced)
9730 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9731 << Name;
9732 return QualType();
9733}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009734
9735namespace {
9736 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009737 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009738 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009739 SourceLocation Loc;
9740 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009741
Douglas Gregor15acfb92009-08-06 16:20:37 +00009742 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009743 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009744
Mike Stump11289f42009-09-09 15:08:12 +00009745 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009746 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009747 DeclarationName Entity)
9748 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009749 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009750
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009751 /// Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009752 /// transformed.
9753 ///
9754 /// For the purposes of type reconstruction, a type has already been
9755 /// transformed if it is NULL or if it is not dependent.
9756 bool AlreadyTransformed(QualType T) {
9757 return T.isNull() || !T->isDependentType();
9758 }
Mike Stump11289f42009-09-09 15:08:12 +00009759
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009760 /// Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009761 /// rebuilt.
9762 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009763
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009764 /// Returns the name of the entity whose type is being rebuilt.
Douglas Gregor15acfb92009-08-06 16:20:37 +00009765 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009766
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009767 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +00009768 /// information is known based on another transformation.
9769 void setBase(SourceLocation Loc, DeclarationName Entity) {
9770 this->Loc = Loc;
9771 this->Entity = Entity;
9772 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009773
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00009774 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9775 // Lambdas never need to be transformed.
9776 return E;
9777 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00009778 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009779} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00009780
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009781/// Rebuilds a type within the context of the current instantiation.
Douglas Gregor15acfb92009-08-06 16:20:37 +00009782///
Mike Stump11289f42009-09-09 15:08:12 +00009783/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00009784/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00009785/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00009786/// partial specialization thereof). This routine will rebuild that type now
9787/// that we have entered the declarator's scope, which may produce different
9788/// canonical types, e.g.,
9789///
9790/// \code
9791/// template<typename T>
9792/// struct X {
9793/// typedef T* pointer;
9794/// pointer data();
9795/// };
9796///
9797/// template<typename T>
9798/// typename X<T>::pointer X<T>::data() { ... }
9799/// \endcode
9800///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00009801/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009802/// since we do not know that we can look into X<T> when we parsed the type.
9803/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00009804/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00009805/// as the canonical type of T*, allowing the return types of the out-of-line
9806/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00009807TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9808 SourceLocation Loc,
9809 DeclarationName Name) {
9810 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00009811 return T;
Mike Stump11289f42009-09-09 15:08:12 +00009812
Douglas Gregor15acfb92009-08-06 16:20:37 +00009813 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9814 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00009815}
Douglas Gregorbe999392009-09-15 16:23:51 +00009816
John McCalldadc5752010-08-24 06:29:42 +00009817ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00009818 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9819 DeclarationName());
9820 return Rebuilder.TransformExpr(E);
9821}
9822
John McCall99b2fe52010-04-29 23:50:39 +00009823bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00009824 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009825 return true;
John McCall2408e322010-04-27 00:57:59 +00009826
Douglas Gregor10176412011-02-25 16:07:42 +00009827 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009828 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9829 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009830 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009831 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009832 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009833 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009834
Douglas Gregor10176412011-02-25 16:07:42 +00009835 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009836 return false;
John McCall2408e322010-04-27 00:57:59 +00009837}
9838
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009839/// Rebuild the template parameters now that we know we're in a current
Douglas Gregor041b0842011-10-14 15:31:12 +00009840/// instantiation.
9841bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9842 TemplateParameterList *Params) {
9843 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9844 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009845
Douglas Gregor041b0842011-10-14 15:31:12 +00009846 // There is nothing to rebuild in a type parameter.
9847 if (isa<TemplateTypeParmDecl>(Param))
9848 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009849
Douglas Gregor041b0842011-10-14 15:31:12 +00009850 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009851 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009852 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9853 if (RebuildTemplateParamsInCurrentInstantiation(
9854 TTP->getTemplateParameters()))
9855 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009856
Douglas Gregor041b0842011-10-14 15:31:12 +00009857 continue;
9858 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009859
Douglas Gregor041b0842011-10-14 15:31:12 +00009860 // Rebuild the type of a non-type template parameter.
9861 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009862 TypeSourceInfo *NewTSI
9863 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9864 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009865 NTTP->getDeclName());
9866 if (!NewTSI)
9867 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009868
Erik Pilkington9f9462a2018-08-07 22:59:02 +00009869 if (NewTSI->getType()->isUndeducedType()) {
9870 // C++17 [temp.dep.expr]p3:
9871 // An id-expression is type-dependent if it contains
9872 // - an identifier associated by name lookup with a non-type
9873 // template-parameter declared with a type that contains a
9874 // placeholder type (7.1.7.4),
9875 NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
9876 }
9877
Douglas Gregor041b0842011-10-14 15:31:12 +00009878 if (NewTSI != NTTP->getTypeSourceInfo()) {
9879 NTTP->setTypeSourceInfo(NewTSI);
9880 NTTP->setType(NewTSI->getType());
9881 }
9882 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009883
Douglas Gregor041b0842011-10-14 15:31:12 +00009884 return false;
9885}
9886
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009887/// Produces a formatted string that describes the binding of
Douglas Gregorbe999392009-09-15 16:23:51 +00009888/// template parameters to template arguments.
9889std::string
9890Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9891 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009892 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00009893}
9894
9895std::string
9896Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9897 const TemplateArgument *Args,
9898 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009899 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00009900 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00009901
Douglas Gregore62e6a02009-11-11 19:13:48 +00009902 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009903 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009904
Douglas Gregorbe999392009-09-15 16:23:51 +00009905 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00009906 if (I >= NumArgs)
9907 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009908
Douglas Gregorbe999392009-09-15 16:23:51 +00009909 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009910 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00009911 else
Douglas Gregor0192c232010-12-20 16:52:59 +00009912 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009913
Douglas Gregorbe999392009-09-15 16:23:51 +00009914 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00009915 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00009916 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00009917 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00009918 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009919
Douglas Gregor0192c232010-12-20 16:52:59 +00009920 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00009921 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00009922 }
Douglas Gregor0192c232010-12-20 16:52:59 +00009923
9924 Out << ']';
9925 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00009926}
Francois Pichet1c229c02011-04-22 22:18:13 +00009927
Richard Smithe40f2ba2013-08-07 21:41:30 +00009928void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9929 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00009930 if (!FD)
9931 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00009932
Justin Lebar28f09c52016-10-10 16:26:08 +00009933 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00009934
9935 // Take tokens to avoid allocations
9936 LPT->Toks.swap(Toks);
9937 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00009938 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00009939
9940 FD->setLateTemplateParsed(true);
9941}
9942
9943void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9944 if (!FD)
9945 return;
9946 FD->setLateTemplateParsed(false);
9947}
Francois Pichet1c229c02011-04-22 22:18:13 +00009948
9949bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9950 DeclContext *DC = CurContext;
9951
9952 while (DC) {
9953 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9954 const FunctionDecl *FD = RD->isLocalClass();
9955 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9956 } else if (DC->isTranslationUnit() || DC->isNamespace())
9957 return false;
9958
9959 DC = DC->getParent();
9960 }
9961 return false;
9962}
Richard Smith6739a102016-05-05 00:56:12 +00009963
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009964namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009965/// Walk the path from which a declaration was instantiated, and check
Richard Smith6739a102016-05-05 00:56:12 +00009966/// that every explicit specialization along that path is visible. This enforces
9967/// C++ [temp.expl.spec]/6:
9968///
9969/// If a template, a member template or a member of a class template is
9970/// explicitly specialized then that specialization shall be declared before
9971/// the first use of that specialization that would cause an implicit
9972/// instantiation to take place, in every translation unit in which such a
9973/// use occurs; no diagnostic is required.
9974///
9975/// and also C++ [temp.class.spec]/1:
9976///
9977/// A partial specialization shall be declared before the first use of a
9978/// class template specialization that would make use of the partial
9979/// specialization as the result of an implicit or explicit instantiation
9980/// in every translation unit in which such a use occurs; no diagnostic is
9981/// required.
9982class ExplicitSpecializationVisibilityChecker {
9983 Sema &S;
9984 SourceLocation Loc;
9985 llvm::SmallVector<Module *, 8> Modules;
9986
9987public:
9988 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9989 : S(S), Loc(Loc) {}
9990
9991 void check(NamedDecl *ND) {
9992 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9993 return checkImpl(FD);
9994 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9995 return checkImpl(RD);
9996 if (auto *VD = dyn_cast<VarDecl>(ND))
9997 return checkImpl(VD);
9998 if (auto *ED = dyn_cast<EnumDecl>(ND))
9999 return checkImpl(ED);
10000 }
10001
10002private:
10003 void diagnose(NamedDecl *D, bool IsPartialSpec) {
10004 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10005 : Sema::MissingImportKind::ExplicitSpecialization;
10006 const bool Recover = true;
10007
10008 // If we got a custom set of modules (because only a subset of the
10009 // declarations are interesting), use them, otherwise let
10010 // diagnoseMissingImport intelligently pick some.
10011 if (Modules.empty())
10012 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10013 else
10014 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10015 }
10016
10017 // Check a specific declaration. There are three problematic cases:
10018 //
10019 // 1) The declaration is an explicit specialization of a template
10020 // specialization.
10021 // 2) The declaration is an explicit specialization of a member of an
10022 // templated class.
10023 // 3) The declaration is an instantiation of a template, and that template
10024 // is an explicit specialization of a member of a templated class.
10025 //
10026 // We don't need to go any deeper than that, as the instantiation of the
10027 // surrounding class / etc is not triggered by whatever triggered this
10028 // instantiation, and thus should be checked elsewhere.
10029 template<typename SpecDecl>
10030 void checkImpl(SpecDecl *Spec) {
10031 bool IsHiddenExplicitSpecialization = false;
10032 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10033 IsHiddenExplicitSpecialization =
10034 Spec->getMemberSpecializationInfo()
10035 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
Richard Smith54f04402017-05-18 02:29:20 +000010036 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
Richard Smith6739a102016-05-05 00:56:12 +000010037 } else {
10038 checkInstantiated(Spec);
10039 }
10040
10041 if (IsHiddenExplicitSpecialization)
10042 diagnose(Spec->getMostRecentDecl(), false);
10043 }
10044
10045 void checkInstantiated(FunctionDecl *FD) {
10046 if (auto *TD = FD->getPrimaryTemplate())
10047 checkTemplate(TD);
10048 }
10049
10050 void checkInstantiated(CXXRecordDecl *RD) {
10051 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10052 if (!SD)
10053 return;
10054
10055 auto From = SD->getSpecializedTemplateOrPartial();
10056 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10057 checkTemplate(TD);
10058 else if (auto *TD =
10059 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10060 if (!S.hasVisibleDeclaration(TD))
10061 diagnose(TD, true);
10062 checkTemplate(TD);
10063 }
10064 }
10065
10066 void checkInstantiated(VarDecl *RD) {
10067 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10068 if (!SD)
10069 return;
10070
10071 auto From = SD->getSpecializedTemplateOrPartial();
10072 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10073 checkTemplate(TD);
10074 else if (auto *TD =
10075 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10076 if (!S.hasVisibleDeclaration(TD))
10077 diagnose(TD, true);
10078 checkTemplate(TD);
10079 }
10080 }
10081
10082 void checkInstantiated(EnumDecl *FD) {}
10083
10084 template<typename TemplDecl>
10085 void checkTemplate(TemplDecl *TD) {
10086 if (TD->isMemberSpecialization()) {
10087 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10088 diagnose(TD->getMostRecentDecl(), false);
10089 }
10090 }
10091};
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010092} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +000010093
10094void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10095 if (!getLangOpts().Modules)
10096 return;
10097
10098 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10099}
10100
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010101/// Check whether a template partial specialization that we've discovered
Richard Smith6739a102016-05-05 00:56:12 +000010102/// is hidden, and produce suitable diagnostics if so.
10103void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10104 NamedDecl *Spec) {
10105 llvm::SmallVector<Module *, 8> Modules;
10106 if (!hasVisibleDeclaration(Spec, &Modules))
10107 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10108 MissingImportKind::PartialSpecialization,
10109 /*Recover*/true);
10110}