blob: 9d9d1270bf57b5a3d6078277526d9083c8930ef6 [file] [log] [blame]
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +000011
Douglas Gregor15acfb92009-08-06 16:20:37 +000012#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000013#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000015#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000019#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000020#include "clang/AST/TypeVisitor.h"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000021#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedTemplate.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000032#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000034#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000035
Eric Fiselier6ad68552016-07-01 01:24:09 +000036#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000037using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000039
John McCall9b72f892010-11-10 02:40:36 +000040// Exported for use by Parser.
41SourceRange
42clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 unsigned N) {
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46}
47
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000048namespace clang {
49/// \brief [temp.constr.decl]p2: A template's associated constraints are
50/// defined as a single constraint-expression derived from the introduced
51/// constraint-expressions [ ... ].
52///
53/// \param Params The template parameter list and optional requires-clause.
54///
55/// \param FD The underlying templated function declaration for a function
56/// template.
57static Expr *formAssociatedConstraints(TemplateParameterList *Params,
58 FunctionDecl *FD);
59}
60
61static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
62 FunctionDecl *FD) {
63 // FIXME: Concepts: collect additional introduced constraint-expressions
64 assert(!FD && "Cannot collect constraints from function declaration yet.");
65 return Params->getRequiresClause();
66}
67
Douglas Gregorb7bfe792009-09-02 22:59:36 +000068/// \brief Determine whether the declaration found is acceptable as the name
69/// of a template and, if so, return that template declaration. Otherwise,
70/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000071static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000072 NamedDecl *Orig,
73 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000074 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000076 if (isa<TemplateDecl>(D)) {
77 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000078 return nullptr;
79
John McCalle9cccd82010-06-16 08:42:20 +000080 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000081 }
Mike Stump11289f42009-09-09 15:08:12 +000082
Douglas Gregorb7bfe792009-09-02 22:59:36 +000083 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
84 // C++ [temp.local]p1:
85 // Like normal (non-template) classes, class templates have an
86 // injected-class-name (Clause 9). The injected-class-name
87 // can be used with or without a template-argument-list. When
88 // it is used without a template-argument-list, it is
89 // equivalent to the injected-class-name followed by the
90 // template-parameters of the class template enclosed in
91 // <>. When it is used with a template-argument-list, it
92 // refers to the specified class template specialization,
93 // which could be the current specialization or another
94 // specialization.
95 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000096 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000097 if (Record->getDescribedClassTemplate())
98 return Record->getDescribedClassTemplate();
99
100 if (ClassTemplateSpecializationDecl *Spec
101 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
102 return Spec->getSpecializedTemplate();
103 }
Mike Stump11289f42009-09-09 15:08:12 +0000104
Craig Topperc3ec1492014-05-26 06:22:03 +0000105 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106 }
Mike Stump11289f42009-09-09 15:08:12 +0000107
Craig Topperc3ec1492014-05-26 06:22:03 +0000108 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000109}
110
Simon Pilgrim6905d222016-12-30 22:55:33 +0000111void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000112 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000113 // The set of class templates we've already seen.
114 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +0000115 LookupResult::Filter filter = R.makeFilter();
116 while (filter.hasNext()) {
117 NamedDecl *Orig = filter.next();
Simon Pilgrim6905d222016-12-30 22:55:33 +0000118 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000119 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +0000120 if (!Repl)
121 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000122 else if (Repl != Orig) {
123
124 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000125 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000126 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000127 // one base class). If all of the injected-class-names that are found
128 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000129 // is used as a template-name, the reference refers to the class
130 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000131 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000132 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000133 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000134 filter.erase();
135 continue;
136 }
John McCallbd8062d2010-08-13 07:02:08 +0000137
138 // FIXME: we promote access to public here as a workaround to
139 // the fact that LookupResult doesn't let us remember that we
140 // found this template through a particular injected class name,
141 // which means we end up doing nasty things to the invariants.
142 // Pretending that access is public is *much* safer.
143 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000144 }
John McCalle66edc12009-11-24 19:00:30 +0000145 }
146 filter.done();
147}
148
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000149bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
150 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000151 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000152 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000153 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +0000154
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000155 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000156}
157
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000159 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000160 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000161 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000162 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000163 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000164 TemplateTy &TemplateResult,
165 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000166 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000167
Douglas Gregor3cf81312009-11-03 23:16:33 +0000168 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000169 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000170
Douglas Gregor3cf81312009-11-03 23:16:33 +0000171 switch (Name.getKind()) {
172 case UnqualifiedId::IK_Identifier:
173 TName = DeclarationName(Name.Identifier);
174 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000175
Douglas Gregor3cf81312009-11-03 23:16:33 +0000176 case UnqualifiedId::IK_OperatorFunctionId:
177 TName = Context.DeclarationNames.getCXXOperatorName(
178 Name.OperatorFunctionId.Operator);
179 break;
180
Alexis Hunted0530f2009-11-28 08:58:14 +0000181 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000182 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
183 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000184
Douglas Gregor3cf81312009-11-03 23:16:33 +0000185 default:
186 return TNK_Non_template;
187 }
Mike Stump11289f42009-09-09 15:08:12 +0000188
John McCallba7bf592010-08-24 05:47:05 +0000189 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000190
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000191 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000192 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
193 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000194 if (R.empty()) return TNK_Non_template;
195 if (R.isAmbiguous()) {
196 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000197 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000198
199 // FIXME: we might have ambiguous templates, in which case we
200 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000201 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000202 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000203
John McCalld28ae272009-12-02 08:04:21 +0000204 TemplateName Template;
205 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000206
John McCalld28ae272009-12-02 08:04:21 +0000207 unsigned ResultCount = R.end() - R.begin();
208 if (ResultCount > 1) {
209 // We assume that we'll preserve the qualifier from a function
210 // template name in other ways.
211 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
212 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000213
214 // We'll do this lookup again later.
215 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000216 } else {
John McCalld28ae272009-12-02 08:04:21 +0000217 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
218
219 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000220 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000221 Template = Context.getQualifiedTemplateName(Qualifier,
222 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000223 } else {
224 Template = TemplateName(TD);
225 }
226
John McCalldcc71402010-08-13 02:23:42 +0000227 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000228 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000229
230 // We'll do this lookup again later.
231 R.suppressDiagnostics();
232 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000233 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000234 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
235 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000236 TemplateKind =
237 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000238 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000239 }
Mike Stump11289f42009-09-09 15:08:12 +0000240
John McCalld28ae272009-12-02 08:04:21 +0000241 TemplateResult = TemplateTy::make(Template);
242 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000243}
244
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000245bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000246 SourceLocation IILoc,
247 Scope *S,
248 const CXXScopeSpec *SS,
249 TemplateTy &SuggestedTemplate,
250 TemplateNameKind &SuggestedKind) {
251 // We can't recover unless there's a dependent scope specifier preceding the
252 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000253 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000254 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
255 computeDeclContext(*SS))
256 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000257
Douglas Gregor18473f32010-01-12 21:28:44 +0000258 // The code is missing a 'template' keyword prior to the dependent template
259 // name.
260 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
261 Diag(IILoc, diag::err_template_kw_missing)
262 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000263 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000264 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000265 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
266 SuggestedKind = TNK_Dependent_template_name;
267 return true;
268}
269
John McCalle66edc12009-11-24 19:00:30 +0000270void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000271 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000272 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000273 bool EnteringContext,
274 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000275 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000276 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000277 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000278 bool isDependent = false;
279 if (!ObjectType.isNull()) {
280 // This nested-name-specifier occurs in a member access expression, e.g.,
281 // x->B::f, and we are looking into the type of the object.
282 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
283 LookupCtx = computeDeclContext(ObjectType);
284 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000285 assert((isDependent || !ObjectType->isIncompleteType() ||
286 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000287 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000288
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000289 // Template names cannot appear inside an Objective-C class or object type.
290 if (ObjectType->isObjCObjectOrInterfaceType()) {
291 Found.clear();
292 return;
293 }
John McCalle66edc12009-11-24 19:00:30 +0000294 } else if (SS.isSet()) {
295 // This nested-name-specifier occurs after another nested-name-specifier,
296 // so long into the context associated with the prior nested-name-specifier.
297 LookupCtx = computeDeclContext(SS, EnteringContext);
298 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000299
John McCalle66edc12009-11-24 19:00:30 +0000300 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000301 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000302 return;
303 }
304
305 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000306 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000307 if (LookupCtx) {
308 // Perform "qualified" name lookup into the declaration context we
309 // computed, which is either the type of the base of a member access
310 // expression or the declaration context associated with a prior
311 // nested-name-specifier.
312 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000313 if (!ObjectType.isNull() && Found.empty()) {
314 // C++ [basic.lookup.classref]p1:
315 // In a class member access expression (5.2.5), if the . or -> token is
316 // immediately followed by an identifier followed by a <, the
317 // identifier must be looked up to determine whether the < is the
318 // beginning of a template argument list (14.2) or a less-than operator.
319 // The identifier is first looked up in the class of the object
320 // expression. If the identifier is not found, it is then looked up in
321 // the context of the entire postfix-expression and shall name a class
322 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000323 if (S) LookupName(Found, S);
324 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000325 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000326 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000327 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000328 // We cannot look into a dependent object type or nested nme
329 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000330 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000331 return;
332 } else {
333 // Perform unqualified name lookup in the current scope.
334 LookupName(Found, S);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000335
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000336 if (!ObjectType.isNull())
337 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000338 }
339
Douglas Gregorc119dd52010-01-12 17:06:20 +0000340 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000341 // If we did not find any names, attempt to correct any typos.
342 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000343 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000344 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000345 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
346 FilterCCC->WantTypeSpecifiers = false;
347 FilterCCC->WantExpressionKeywords = false;
348 FilterCCC->WantRemainingKeywords = false;
349 FilterCCC->WantCXXNamedCasts = true;
350 if (TypoCorrection Corrected = CorrectTypo(
351 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
352 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000353 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000354 if (auto *ND = Corrected.getFoundDecl())
355 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000356 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000357 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000358 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000359 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
360 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000361 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000362 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
363 << Name << LookupCtx << DroppedSpecifier
364 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000365 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000366 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000367 }
John McCalle9cccd82010-06-16 08:42:20 +0000368 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000369 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000370 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000371 }
372 }
373
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000374 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000375 if (Found.empty()) {
376 if (isDependent)
377 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000378 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000379 }
John McCalle66edc12009-11-24 19:00:30 +0000380
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000381 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000382 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000383 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000384 // [...] If the lookup in the class of the object expression finds a
385 // template, the name is also looked up in the context of the entire
386 // postfix-expression and [...]
387 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000388 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000389 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
390 LookupOrdinaryName);
391 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000392 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000393
John McCalle66edc12009-11-24 19:00:30 +0000394 if (FoundOuter.empty()) {
395 // - if the name is not found, the name found in the class of the
396 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000397 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
398 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000399 // - if the name is found in the context of the entire
400 // postfix-expression and does not name a class template, the name
401 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000402 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000403 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000404 // - if the name found is a class template, it must refer to the same
405 // entity as the one found in the class of the object expression,
406 // otherwise the program is ill-formed.
407 if (!Found.isSingleResult() ||
408 Found.getFoundDecl()->getCanonicalDecl()
409 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000410 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000411 diag::ext_nested_name_member_ref_lookup_ambiguous)
412 << Found.getLookupName()
413 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000414 Diag(Found.getRepresentativeDecl()->getLocation(),
415 diag::note_ambig_member_ref_object_type)
416 << ObjectType;
417 Diag(FoundOuter.getFoundDecl()->getLocation(),
418 diag::note_ambig_member_ref_scope);
419
420 // Recover by taking the template that we found in the object
421 // expression's type.
422 }
423 }
424 }
425}
426
John McCallcd4b4772009-12-02 03:53:29 +0000427/// ActOnDependentIdExpression - Handle a dependent id-expression that
428/// was just parsed. This is only possible with an explicit scope
429/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000430ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000431Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000432 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000433 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000434 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000435 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000436 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437
Reid Kleckner1af391df2016-03-11 18:59:12 +0000438 // C++11 [expr.prim.general]p12:
439 // An id-expression that denotes a non-static data member or non-static
440 // member function of a class can only be used:
441 // (...)
442 // - if that id-expression denotes a non-static data member and it
443 // appears in an unevaluated operand.
444 //
445 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
446 // CXXDependentScopeMemberExpr. The former can instantiate to either
447 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
448 // always a MemberExpr.
449 bool MightBeCxx11UnevalField =
450 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
451
Akira Hatanakad644e022016-12-16 03:19:41 +0000452 // Check if the nested name specifier is an enum type.
453 bool IsEnum = false;
454 if (NestedNameSpecifier *NNS = SS.getScopeRep())
455 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
456
457 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000458 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000459 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000460
John McCalle66edc12009-11-24 19:00:30 +0000461 // Since the 'this' expression is synthesized, we don't need to
462 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000463 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000464
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000465 return CXXDependentScopeMemberExpr::Create(
466 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
467 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
468 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000469 }
470
Abramo Bagnara7945c982012-01-27 09:46:47 +0000471 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000472}
473
John McCalldadc5752010-08-24 06:29:42 +0000474ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000475Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000476 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000477 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000478 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000479 return DependentScopeDeclRefExpr::Create(
480 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
481 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000482}
483
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000484
485/// Determine whether we would be unable to instantiate this template (because
486/// it either has no definition, or is in the process of being instantiated).
487bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
488 NamedDecl *Instantiation,
489 bool InstantiatedFromMember,
490 const NamedDecl *Pattern,
491 const NamedDecl *PatternDef,
492 TemplateSpecializationKind TSK,
493 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000494 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
495 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000496
Richard Smithedbc6e92016-10-14 21:41:24 +0000497 bool IsEntityBeingDefined = false;
498 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
499 IsEntityBeingDefined = TD->isBeingDefined();
500
501 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000502 NamedDecl *SuggestedDef = nullptr;
503 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
504 /*OnlyNeedComplete*/false)) {
505 // If we're allowed to diagnose this and recover, do so.
506 bool Recover = Complain && !isSFINAEContext();
507 if (Complain)
508 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
509 Sema::MissingImportKind::Definition, Recover);
510 return !Recover;
511 }
512 return false;
513 }
514
Richard Smith6f4e2e02016-08-23 19:41:39 +0000515 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
516 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000517
Richard Smithedbc6e92016-10-14 21:41:24 +0000518 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000519 QualType InstantiationTy;
520 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
521 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000522 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000523 Diag(PointOfInstantiation,
524 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000525 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000526 << InstantiationTy;
527 // Not much point in noting the template declaration here, since
528 // we're lexically inside it.
529 Instantiation->setInvalidDecl();
530 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000531 if (isa<FunctionDecl>(Instantiation)) {
532 Diag(PointOfInstantiation,
533 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000534 << /*member function*/ 1 << Instantiation->getDeclName()
535 << Instantiation->getDeclContext();
536 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000537 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000538 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000539 Diag(PointOfInstantiation,
540 diag::err_implicit_instantiate_member_undefined)
541 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000542 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000543 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000544 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000545 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000546 Diag(PointOfInstantiation,
547 diag::err_explicit_instantiation_undefined_func_template)
548 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000549 Note = diag::note_explicit_instantiation_here;
550 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000551 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
552 << (TSK != TSK_ImplicitInstantiation)
553 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000554 Note = diag::note_template_decl_here;
555 } else {
556 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
557 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
558 Diag(PointOfInstantiation,
559 diag::err_explicit_instantiation_undefined_var_template)
560 << Instantiation;
561 Instantiation->setInvalidDecl();
562 } else
563 Diag(PointOfInstantiation,
564 diag::err_explicit_instantiation_undefined_member)
565 << /*static data member*/ 2 << Instantiation->getDeclName()
566 << Instantiation->getDeclContext();
567 Note = diag::note_explicit_instantiation_here;
568 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000569 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000570 if (Note) // Diagnostics were emitted.
571 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000572
573 // In general, Instantiation isn't marked invalid to get more than one
574 // error for multiple undefined instantiations. But the code that does
575 // explicit declaration -> explicit definition conversion can't handle
576 // invalid declarations, so mark as invalid in that case.
577 if (TSK == TSK_ExplicitInstantiationDeclaration)
578 Instantiation->setInvalidDecl();
579 return true;
580}
581
Douglas Gregor5101c242008-12-05 18:15:24 +0000582/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
583/// that the template parameter 'PrevDecl' is being shadowed by a new
584/// declaration at location Loc. Returns true to indicate that this is
585/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000586void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000587 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000588
589 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000590 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000591 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000592
593 // C++ [temp.local]p4:
594 // A template-parameter shall not be redeclared within its
595 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000596 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000597 << cast<NamedDecl>(PrevDecl)->getDeclName();
598 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000599}
600
Douglas Gregor463421d2009-03-03 04:44:36 +0000601/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000602/// the parameter D to reference the templated declaration and return a pointer
603/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000604TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
605 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
606 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000607 return Temp;
608 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000609 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000610}
611
Douglas Gregoreb29d182011-01-05 17:40:24 +0000612ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
613 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000615 "Only template template arguments can be pack expansions here");
616 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
617 "Template template argument pack expansion without packs");
618 ParsedTemplateArgument Result(*this);
619 Result.EllipsisLoc = EllipsisLoc;
620 return Result;
621}
622
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000623static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
624 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000626 switch (Arg.getKind()) {
627 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000628 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000629 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000630 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000631 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000632 return TemplateArgumentLoc(TemplateArgument(T), DI);
633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000635 case ParsedTemplateArgument::NonType: {
636 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
637 return TemplateArgumentLoc(TemplateArgument(E), E);
638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000640 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000641 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000642 TemplateArgument TArg;
643 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000644 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000645 else
646 TArg = Template;
647 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000648 Arg.getScopeSpec().getWithLocInContext(
649 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000650 Arg.getLocation(),
651 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000652 }
653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000654
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000655 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000656}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000657
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000658/// \brief Translates template arguments as provided by the parser
659/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000660void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
661 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000662 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000663 TemplateArgs.addArgument(translateTemplateArgument(*this,
664 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000665}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666
Richard Smithb80d5402013-06-25 22:21:36 +0000667static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
668 SourceLocation Loc,
669 IdentifierInfo *Name) {
670 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
671 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
672 if (PrevDecl && PrevDecl->isTemplateParameter())
673 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
674}
675
Douglas Gregor5101c242008-12-05 18:15:24 +0000676/// ActOnTypeParameter - Called when a C++ template type parameter
677/// (e.g., "typename T") has been parsed. Typename specifies whether
678/// the keyword "typename" was used to declare the type parameter
679/// (otherwise, "class" was used), and KeyLoc is the location of the
680/// "class" or "typename" keyword. ParamName is the name of the
681/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000682/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000683/// If the type parameter has a default argument, it will be added
684/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000685Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000686 SourceLocation EllipsisLoc,
687 SourceLocation KeyLoc,
688 IdentifierInfo *ParamName,
689 SourceLocation ParamNameLoc,
690 unsigned Depth, unsigned Position,
691 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000692 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000693 assert(S->isTemplateParamScope() &&
694 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000695
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000696 SourceLocation Loc = ParamNameLoc;
697 if (!ParamName)
698 Loc = KeyLoc;
699
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000700 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000701 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000702 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000703 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000704 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000705 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000706
707 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000708 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
709
Douglas Gregor5101c242008-12-05 18:15:24 +0000710 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000711 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000712 IdResolver.AddDecl(Param);
713 }
714
Douglas Gregorf5500772011-01-05 15:48:55 +0000715 // C++0x [temp.param]p9:
716 // A default template-argument may be specified for any kind of
717 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000718 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000719 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000720 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000721 }
722
Douglas Gregordc13ded2010-07-01 00:00:45 +0000723 // Handle the default argument, if provided.
724 if (DefaultArg) {
725 TypeSourceInfo *DefaultTInfo;
726 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727
Douglas Gregordc13ded2010-07-01 00:00:45 +0000728 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000729
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000730 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000731 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000732 UPPC_DefaultArgument))
733 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000734
Douglas Gregordc13ded2010-07-01 00:00:45 +0000735 // Check the template argument itself.
736 if (CheckTemplateArgument(Param, DefaultTInfo)) {
737 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000738 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000740
Richard Smith1469b912015-06-10 00:29:03 +0000741 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000742 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000743
John McCall48871652010-08-21 09:40:31 +0000744 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000745}
746
Douglas Gregor463421d2009-03-03 04:44:36 +0000747/// \brief Check that the type of a non-type template parameter is
748/// well-formed.
749///
750/// \returns the (possibly-promoted) parameter type if valid;
751/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000752QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
753 SourceLocation Loc) {
754 if (TSI->getType()->isUndeducedType()) {
755 // C++1z [temp.dep.expr]p3:
756 // An id-expression is type-dependent if it contains
757 // - an identifier associated by name lookup with a non-type
758 // template-parameter declared with a type that contains a
759 // placeholder type (7.1.7.4),
760 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
761 }
762
763 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
764}
765
766QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
767 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000768 // We don't allow variably-modified types as the type of non-type template
769 // parameters.
770 if (T->isVariablyModifiedType()) {
771 Diag(Loc, diag::err_variably_modified_nontype_template_param)
772 << T;
773 return QualType();
774 }
775
Douglas Gregor463421d2009-03-03 04:44:36 +0000776 // C++ [temp.param]p4:
777 //
778 // A non-type template-parameter shall have one of the following
779 // (optionally cv-qualified) types:
780 //
781 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000782 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000783 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000784 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000785 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000786 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000787 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000788 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000789 // -- std::nullptr_t.
790 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000791 // If T is a dependent type, we can't do the check now, so we
792 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +0000793 T->isDependentType() ||
794 // Allow use of auto in template parameter declarations.
795 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +0000796 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
797 // are ignored when determining its type.
798 return T.getUnqualifiedType();
799 }
800
Douglas Gregor463421d2009-03-03 04:44:36 +0000801 // C++ [temp.param]p8:
802 //
803 // A non-type template-parameter of type "array of T" or
804 // "function returning T" is adjusted to be of type "pointer to
805 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000806 else if (T->isArrayType() || T->isFunctionType())
807 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000808
Douglas Gregor463421d2009-03-03 04:44:36 +0000809 Diag(Loc, diag::err_template_nontype_parm_bad_type)
810 << T;
811
812 return QualType();
813}
814
John McCall48871652010-08-21 09:40:31 +0000815Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
816 unsigned Depth,
817 unsigned Position,
818 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000819 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000820 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +0000821
822 if (TInfo->getType()->isUndeducedType()) {
823 Diag(D.getIdentifierLoc(),
824 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
825 << QualType(TInfo->getType()->getContainedAutoType(), 0);
826 }
Douglas Gregor5101c242008-12-05 18:15:24 +0000827
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000828 assert(S->isTemplateParamScope() &&
829 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000830 bool Invalid = false;
831
Richard Smith15361a22016-12-28 06:27:18 +0000832 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000833 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000834 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000835 Invalid = true;
836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000837
Richard Smithb80d5402013-06-25 22:21:36 +0000838 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000839 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000840 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000841 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000842 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000843 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000845 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000846 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000847
Douglas Gregor5101c242008-12-05 18:15:24 +0000848 if (Invalid)
849 Param->setInvalidDecl();
850
Richard Smithb80d5402013-06-25 22:21:36 +0000851 if (ParamName) {
852 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
853 ParamName);
854
Douglas Gregor5101c242008-12-05 18:15:24 +0000855 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000856 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000857 IdResolver.AddDecl(Param);
858 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000859
Douglas Gregorf5500772011-01-05 15:48:55 +0000860 // C++0x [temp.param]p9:
861 // A default template-argument may be specified for any kind of
862 // template-parameter that is not a template parameter pack.
863 if (Default && IsParameterPack) {
864 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000865 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000866 }
867
Douglas Gregordc13ded2010-07-01 00:00:45 +0000868 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000869 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000870 // Check for unexpanded parameter packs.
871 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
872 return Param;
873
Douglas Gregordc13ded2010-07-01 00:00:45 +0000874 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000875 ExprResult DefaultRes =
876 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000877 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000878 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000879 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000880 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000881 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000882
Richard Smith1469b912015-06-10 00:29:03 +0000883 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000884 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000885
John McCall48871652010-08-21 09:40:31 +0000886 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000887}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000888
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000889/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000890/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000891/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000892Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
893 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000894 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000895 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000896 IdentifierInfo *Name,
897 SourceLocation NameLoc,
898 unsigned Depth,
899 unsigned Position,
900 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000901 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000902 assert(S->isTemplateParamScope() &&
903 "Template template parameter not in template parameter scope!");
904
905 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000906 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000907 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000908 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000909 NameLoc.isInvalid()? TmpLoc : NameLoc,
910 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000911 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000912 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000913
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000914 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000915 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000916 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000917 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
918
John McCall48871652010-08-21 09:40:31 +0000919 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000920 IdResolver.AddDecl(Param);
921 }
922
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000923 if (Params->size() == 0) {
924 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
925 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
926 Param->setInvalidDecl();
927 }
928
Douglas Gregorf5500772011-01-05 15:48:55 +0000929 // C++0x [temp.param]p9:
930 // A default template-argument may be specified for any kind of
931 // template-parameter that is not a template parameter pack.
932 if (IsParameterPack && !Default.isInvalid()) {
933 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
934 Default = ParsedTemplateArgument();
935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000936
Douglas Gregordc13ded2010-07-01 00:00:45 +0000937 if (!Default.isInvalid()) {
938 // Check only that we have a template template argument. We don't want to
939 // try to check well-formedness now, because our template template parameter
940 // might have dependent types in its template parameters, which we wouldn't
941 // be able to match now.
942 //
943 // If none of the template template parameter's template arguments mention
944 // other template parameters, we could actually perform more checking here.
945 // However, it isn't worth doing.
946 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
947 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000948 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000949 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000950 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000952
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000953 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000955 DefaultArg.getArgument().getAsTemplate(),
956 UPPC_DefaultArgument))
957 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000958
Richard Smith1469b912015-06-10 00:29:03 +0000959 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000960 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000961
John McCall48871652010-08-21 09:40:31 +0000962 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000963}
964
Hubert Tongf608c052016-04-29 18:05:37 +0000965/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
966/// constrained by RequiresClause, that contains the template parameters in
967/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000968TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000969Sema::ActOnTemplateParameterList(unsigned Depth,
970 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000971 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000972 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000973 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +0000974 SourceLocation RAngleLoc,
975 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000976 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000977 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000978
David Majnemer902f8c62015-12-27 07:16:27 +0000979 return TemplateParameterList::Create(
980 Context, TemplateLoc, LAngleLoc,
981 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000982 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000983}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000984
John McCall3e11ebe2010-03-15 10:12:16 +0000985static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
986 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000987 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000988}
989
John McCallfaf5fb42010-08-26 23:41:50 +0000990DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000991Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000992 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000993 IdentifierInfo *Name, SourceLocation NameLoc,
994 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000995 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000996 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000997 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000998 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000999 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +00001000 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001001 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001002 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001003 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001004 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001005
1006 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001007 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001008 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001009
Abramo Bagnara6150c882010-05-11 21:36:43 +00001010 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1011 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001012
1013 // There is no such thing as an unnamed class template.
1014 if (!Name) {
1015 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001016 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001017 }
1018
Richard Smith6483d222012-04-21 01:27:54 +00001019 // Find any previous declaration with this name. For a friend with no
1020 // scope explicitly specified, we only look for tag declarations (per
1021 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001022 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001023 LookupResult Previous(*this, Name, NameLoc,
1024 (SS.isEmpty() && TUK == TUK_Friend)
1025 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00001026 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001027 if (SS.isNotEmpty() && !SS.isInvalid()) {
1028 SemanticContext = computeDeclContext(SS, true);
1029 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001030 // FIXME: Horrible, horrible hack! We can't currently represent this
1031 // in the AST, and historically we have just ignored such friend
1032 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001033 Diag(NameLoc, TUK == TUK_Friend
1034 ? diag::warn_template_qualified_friend_ignored
1035 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001036 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001037 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001038 }
Mike Stump11289f42009-09-09 15:08:12 +00001039
John McCall0b66eb32010-05-01 00:40:08 +00001040 if (RequireCompleteDeclContext(SS, SemanticContext))
1041 return true;
1042
Simon Pilgrim6905d222016-12-30 22:55:33 +00001043 // If we're adding a template to a dependent context, we may need to
1044 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001045 // now that we know what the current instantiation is.
1046 if (SemanticContext->isDependentContext()) {
1047 ContextRAII SavedContext(*this, SemanticContext);
1048 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1049 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001050 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1051 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +00001052
John McCall27b18f82009-11-17 02:14:36 +00001053 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001054 } else {
1055 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001056
1057 // C++14 [class.mem]p14:
1058 // If T is the name of a class, then each of the following shall have a
1059 // name different from T:
1060 // -- every member template of class T
1061 if (TUK != TUK_Friend &&
1062 DiagnoseClassNameShadow(SemanticContext,
1063 DeclarationNameInfo(Name, NameLoc)))
1064 return true;
1065
John McCall27b18f82009-11-17 02:14:36 +00001066 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001067 }
Mike Stump11289f42009-09-09 15:08:12 +00001068
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001069 if (Previous.isAmbiguous())
1070 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001071
Craig Topperc3ec1492014-05-26 06:22:03 +00001072 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001073 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001074 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001075
Serge Pavlove50bf752016-06-10 04:39:07 +00001076 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1077 // Maybe we will complain about the shadowed template parameter.
1078 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1079 // Just pretend that we didn't see the previous declaration.
1080 PrevDecl = nullptr;
1081 }
1082
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001083 // If there is a previous declaration with the same name, check
1084 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +00001085 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001086 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001087
1088 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001089 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001090 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001091 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001092 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1093 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001094 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001095 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1096 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1097 PrevClassTemplate
1098 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1099 ->getSpecializedTemplate();
1100 }
1101 }
1102
John McCalld43784f2009-12-18 11:25:59 +00001103 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001104 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001105 // [...] When looking for a prior declaration of a class or a function
1106 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001107 // function is neither a qualified name nor a template-id, scopes outside
1108 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001109 if (!SS.isSet()) {
1110 DeclContext *OutermostContext = CurContext;
1111 while (!OutermostContext->isFileContext())
1112 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001113
Richard Smith61e582f2012-04-20 07:12:26 +00001114 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001115 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1116 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1117 SemanticContext = PrevDecl->getDeclContext();
1118 } else {
1119 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001121 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001122 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001123 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001124
1125 // Check that the chosen semantic context doesn't already contain a
1126 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001127 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001128 DeclContext *LookupContext = SemanticContext;
1129 while (LookupContext->isTransparentContext())
1130 LookupContext = LookupContext->getLookupParent();
1131 LookupQualifiedName(Previous, LookupContext);
1132
1133 if (Previous.isAmbiguous())
1134 return true;
1135
1136 if (Previous.begin() != Previous.end())
1137 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001138 }
John McCall90d3bb92009-12-17 23:21:11 +00001139 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001140 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001141 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1142 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001143 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001144
Richard Smithfc805ca2015-07-06 04:43:58 +00001145 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1146 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1147 if (SS.isEmpty() &&
1148 !(PrevClassTemplate &&
1149 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1150 SemanticContext->getRedeclContext()))) {
1151 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1152 Diag(Shadow->getTargetDecl()->getLocation(),
1153 diag::note_using_decl_target);
1154 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1155 // Recover by ignoring the old declaration.
1156 PrevDecl = PrevClassTemplate = nullptr;
1157 }
1158 }
1159
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001160 // TODO Memory management; associated constraints are not always stored.
1161 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1162
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001163 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001164 // Ensure that the template parameter lists are compatible. Skip this check
1165 // for a friend in a dependent context: the template parameter list itself
1166 // could be dependent.
1167 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1168 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001169 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001170 /*Complain=*/true,
1171 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001172 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001173
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001174 // Check for matching associated constraints on redeclarations.
1175 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1176 const bool RedeclACMismatch = [&] {
1177 if (!(CurAC || PrevAC))
1178 return false; // Nothing to check; no mismatch.
1179 if (CurAC && PrevAC) {
1180 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1181 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1182 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1183 if (CurACInfo == PrevACInfo)
1184 return false; // All good; no mismatch.
1185 }
1186 return true;
1187 }();
1188
1189 if (RedeclACMismatch) {
1190 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1191 diag::err_template_different_associated_constraints);
1192 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1193 diag::note_template_prev_declaration) << /*declaration*/0;
1194 return true;
1195 }
1196
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001197 // C++ [temp.class]p4:
1198 // In a redeclaration, partial specialization, explicit
1199 // specialization or explicit instantiation of a class template,
1200 // the class-key shall agree in kind with the original class
1201 // template declaration (7.1.5.3).
1202 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001203 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001204 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001205 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001206 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001207 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001208 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001209 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001210 }
1211
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001212 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001213 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001214 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001215 // If we have a prior definition that is not visible, treat this as
1216 // simply making that previous definition visible.
1217 NamedDecl *Hidden = nullptr;
1218 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001219 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001220 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1221 assert(Tmpl && "original definition of a class template is not a "
1222 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001223 makeMergedDefinitionVisible(Hidden, KWLoc);
1224 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001225 return Def;
1226 }
1227
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001228 Diag(NameLoc, diag::err_redefinition) << Name;
1229 Diag(Def->getLocation(), diag::note_previous_definition);
1230 // FIXME: Would it make sense to try to "forget" the previous
1231 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001232 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001233 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001234 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001235 } else if (PrevDecl) {
1236 // C++ [temp]p5:
1237 // A class template shall not have the same name as any other
1238 // template, class, function, object, enumeration, enumerator,
1239 // namespace, or type in the same scope (3.3), except as specified
1240 // in (14.5.4).
1241 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1242 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001243 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001244 }
1245
Douglas Gregordba32632009-02-10 19:49:53 +00001246 // Check the template parameter list of this declaration, possibly
1247 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001248 // template declaration. Skip this check for a friend in a dependent
1249 // context, because the template parameter list might be dependent.
1250 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001251 CheckTemplateParameterList(
1252 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001253 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1254 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001255 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1256 SemanticContext->isDependentContext())
1257 ? TPC_ClassTemplateMember
1258 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1259 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001260 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001261
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001262 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001263 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001264 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001265 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1266 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001267 : diag::err_member_decl_does_not_match)
1268 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001269 Invalid = true;
1270 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001271 }
1272
Vassil Vassilev352e4412017-01-12 09:16:26 +00001273 // If this is a templated friend in a dependent context we should not put it
1274 // on the redecl chain. In some cases, the templated friend can be the most
1275 // recent declaration tricking the template instantiator to make substitutions
1276 // there.
1277 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1278 bool ShouldAddRedecl
1279 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1280
Mike Stump11289f42009-09-09 15:08:12 +00001281 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001282 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001283 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001284 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001285 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001286 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001287 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001288 NewClass->setTemplateParameterListsInfo(
1289 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1290 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001291
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001292 // Add alignment attributes if necessary; these attributes are checked when
1293 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001294 if (TUK == TUK_Definition) {
1295 AddAlignmentAttributesForRecord(NewClass);
1296 AddMsStructLayoutForRecord(NewClass);
1297 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001298
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001299 // Attach the associated constraints when the declaration will not be part of
1300 // a decl chain.
1301 Expr *const ACtoAttach =
1302 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1303
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001304 ClassTemplateDecl *NewTemplate
1305 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1306 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001307 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001308
1309 if (ShouldAddRedecl)
1310 NewTemplate->setPreviousDecl(PrevClassTemplate);
1311
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001312 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001313
Douglas Gregor21823bf2011-12-20 18:11:52 +00001314 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001315 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001316
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001317 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001318 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001319 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001320 assert(T->isDependentType() && "Class template type is not dependent?");
1321 (void)T;
1322
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001323 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001324 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001325 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001326 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1327 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001328
Anders Carlsson137108d2009-03-26 01:24:28 +00001329 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001330 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001331 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001332
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001333 // Set the lexical context of these templates
1334 NewClass->setLexicalDeclContext(CurContext);
1335 NewTemplate->setLexicalDeclContext(CurContext);
1336
John McCall9bb74a52009-07-31 02:45:11 +00001337 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001338 NewClass->startDefinition();
1339
1340 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001341 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001342
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001343 if (PrevClassTemplate)
1344 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1345
Rafael Espindola385c0422012-07-13 18:04:45 +00001346 AddPushedVisibilityAttribute(NewClass);
1347
Richard Smith234ff472014-08-23 00:49:01 +00001348 if (TUK != TUK_Friend) {
1349 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1350 Scope *Outer = S;
1351 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1352 Outer = Outer->getParent();
1353 PushOnScopeChains(NewTemplate, Outer);
1354 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001355 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001356 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001357 NewClass->setAccess(PrevClassTemplate->getAccess());
1358 }
John McCall27b5c252009-09-14 21:59:20 +00001359
Richard Smith64017682013-07-17 23:53:16 +00001360 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001361
John McCall27b5c252009-09-14 21:59:20 +00001362 // Friend templates are visible in fairly strange ways.
1363 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001364 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001365 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001366 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1367 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001368 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001369 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001370
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001371 FriendDecl *Friend = FriendDecl::Create(
1372 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001373 Friend->setAccess(AS_public);
1374 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001375 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001376
Douglas Gregordba32632009-02-10 19:49:53 +00001377 if (Invalid) {
1378 NewTemplate->setInvalidDecl();
1379 NewClass->setInvalidDecl();
1380 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001381
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001382 ActOnDocumentableDecl(NewTemplate);
1383
John McCall48871652010-08-21 09:40:31 +00001384 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001385}
1386
Douglas Gregored5731f2009-11-25 17:50:39 +00001387/// \brief Diagnose the presence of a default template argument on a
1388/// template parameter, which is ill-formed in certain contexts.
1389///
1390/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001392 Sema::TemplateParamListContext TPC,
1393 SourceLocation ParamLoc,
1394 SourceRange DefArgRange) {
1395 switch (TPC) {
1396 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001397 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001398 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001399 return false;
1400
1401 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001402 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001403 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001404 // A default template-argument shall not be specified in a
1405 // function template declaration or a function template
1406 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00001407 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001408 // template-argument, that declaration shall be a definition and shall be
1409 // the only declaration of the function template in the translation unit.
1410 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001411 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001412 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1413 : diag::ext_template_parameter_default_in_function_template)
1414 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001415 return false;
1416
1417 case Sema::TPC_ClassTemplateMember:
1418 // C++0x [temp.param]p9:
1419 // A default template-argument shall not be specified in the
1420 // template-parameter-lists of the definition of a member of a
1421 // class template that appears outside of the member's class.
1422 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1423 << DefArgRange;
1424 return true;
1425
David Majnemerba8f17a2013-06-25 22:08:55 +00001426 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001427 case Sema::TPC_FriendFunctionTemplate:
1428 // C++ [temp.param]p9:
1429 // A default template-argument shall not be specified in a
1430 // friend template declaration.
1431 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1432 << DefArgRange;
1433 return true;
1434
1435 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1436 // for friend function templates if there is only a single
1437 // declaration (and it is a definition). Strange!
1438 }
1439
David Blaikie8a40f702012-01-17 06:56:22 +00001440 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001441}
1442
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001443/// \brief Check for unexpanded parameter packs within the template parameters
1444/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001445static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1446 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001447 // A template template parameter which is a parameter pack is also a pack
1448 // expansion.
1449 if (TTP->isParameterPack())
1450 return false;
1451
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001452 TemplateParameterList *Params = TTP->getTemplateParameters();
1453 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1454 NamedDecl *P = Params->getParam(I);
1455 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001456 if (!NTTP->isParameterPack() &&
1457 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001458 NTTP->getTypeSourceInfo(),
1459 Sema::UPPC_NonTypeTemplateParameterType))
1460 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001461
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001462 continue;
1463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001464
1465 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001466 = dyn_cast<TemplateTemplateParmDecl>(P))
1467 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1468 return true;
1469 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001471 return false;
1472}
1473
Douglas Gregordba32632009-02-10 19:49:53 +00001474/// \brief Checks the validity of a template parameter list, possibly
1475/// considering the template parameter list from a previous
1476/// declaration.
1477///
1478/// If an "old" template parameter list is provided, it must be
1479/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1480/// template parameter list.
1481///
1482/// \param NewParams Template parameter list for a new template
1483/// declaration. This template parameter list will be updated with any
1484/// default arguments that are carried through from the previous
1485/// template parameter list.
1486///
1487/// \param OldParams If provided, template parameter list from a
1488/// previous declaration of the same template. Default template
1489/// arguments will be merged from the old template parameter list to
1490/// the new template parameter list.
1491///
Douglas Gregored5731f2009-11-25 17:50:39 +00001492/// \param TPC Describes the context in which we are checking the given
1493/// template parameter list.
1494///
Douglas Gregordba32632009-02-10 19:49:53 +00001495/// \returns true if an error occurred, false otherwise.
1496bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001497 TemplateParameterList *OldParams,
1498 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001499 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001500
Douglas Gregordba32632009-02-10 19:49:53 +00001501 // C++ [temp.param]p10:
1502 // The set of default template-arguments available for use with a
1503 // template declaration or definition is obtained by merging the
1504 // default arguments from the definition (if in scope) and all
1505 // declarations in scope in the same way default function
1506 // arguments are (8.3.6).
1507 bool SawDefaultArgument = false;
1508 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001509
Mike Stumpc89c8e32009-02-11 23:03:27 +00001510 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001511 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001512 if (OldParams)
1513 OldParam = OldParams->begin();
1514
Douglas Gregor0693def2011-01-27 01:40:17 +00001515 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001516 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1517 NewParamEnd = NewParams->end();
1518 NewParam != NewParamEnd; ++NewParam) {
1519 // Variables used to diagnose redundant default arguments
1520 bool RedundantDefaultArg = false;
1521 SourceLocation OldDefaultLoc;
1522 SourceLocation NewDefaultLoc;
1523
David Blaikie651c73c2011-10-19 05:19:50 +00001524 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001525 bool MissingDefaultArg = false;
1526
David Blaikie651c73c2011-10-19 05:19:50 +00001527 // Variable used to diagnose non-final parameter packs
1528 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001529
Douglas Gregordba32632009-02-10 19:49:53 +00001530 if (TemplateTypeParmDecl *NewTypeParm
1531 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001532 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001533 if (NewTypeParm->hasDefaultArgument() &&
1534 DiagnoseDefaultTemplateArgument(*this, TPC,
1535 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001536 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001537 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001538 NewTypeParm->removeDefaultArgument();
1539
1540 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001541 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001542 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001543 if (NewTypeParm->isParameterPack()) {
1544 assert(!NewTypeParm->hasDefaultArgument() &&
1545 "Parameter packs can't have a default argument!");
1546 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001547 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001548 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001549 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1550 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1551 SawDefaultArgument = true;
1552 RedundantDefaultArg = true;
1553 PreviousDefaultArgLoc = NewDefaultLoc;
1554 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1555 // Merge the default argument from the old declaration to the
1556 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001557 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001558 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1559 } else if (NewTypeParm->hasDefaultArgument()) {
1560 SawDefaultArgument = true;
1561 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1562 } else if (SawDefaultArgument)
1563 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001564 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001565 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001566 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001567 if (!NewNonTypeParm->isParameterPack() &&
1568 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001569 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001570 UPPC_NonTypeTemplateParameterType)) {
1571 Invalid = true;
1572 continue;
1573 }
1574
Douglas Gregored5731f2009-11-25 17:50:39 +00001575 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001576 if (NewNonTypeParm->hasDefaultArgument() &&
1577 DiagnoseDefaultTemplateArgument(*this, TPC,
1578 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001579 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001580 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001581 }
1582
Mike Stump12b8ce12009-08-04 21:02:39 +00001583 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001584 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001585 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001586 if (NewNonTypeParm->isParameterPack()) {
1587 assert(!NewNonTypeParm->hasDefaultArgument() &&
1588 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001589 if (!NewNonTypeParm->isPackExpansion())
1590 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001591 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001592 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001593 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1594 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1595 SawDefaultArgument = true;
1596 RedundantDefaultArg = true;
1597 PreviousDefaultArgLoc = NewDefaultLoc;
1598 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1599 // Merge the default argument from the old declaration to the
1600 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001601 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001602 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1603 } else if (NewNonTypeParm->hasDefaultArgument()) {
1604 SawDefaultArgument = true;
1605 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1606 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001607 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001608 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001609 TemplateTemplateParmDecl *NewTemplateParm
1610 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001611
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001612 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001613 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001614 Invalid = true;
1615 continue;
1616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001617
David Blaikie651c73c2011-10-19 05:19:50 +00001618 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001619 if (NewTemplateParm->hasDefaultArgument() &&
1620 DiagnoseDefaultTemplateArgument(*this, TPC,
1621 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001622 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001623 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001624
1625 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001626 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001627 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001628 if (NewTemplateParm->isParameterPack()) {
1629 assert(!NewTemplateParm->hasDefaultArgument() &&
1630 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001631 if (!NewTemplateParm->isPackExpansion())
1632 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001633 } else if (OldTemplateParm &&
1634 hasVisibleDefaultArgument(OldTemplateParm) &&
1635 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001636 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1637 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001638 SawDefaultArgument = true;
1639 RedundantDefaultArg = true;
1640 PreviousDefaultArgLoc = NewDefaultLoc;
1641 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1642 // Merge the default argument from the old declaration to the
1643 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001644 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001645 PreviousDefaultArgLoc
1646 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001647 } else if (NewTemplateParm->hasDefaultArgument()) {
1648 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001649 PreviousDefaultArgLoc
1650 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001651 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001652 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001653 }
1654
Richard Smith1fde8ec2012-09-07 02:06:42 +00001655 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001656 // If a template parameter of a primary class template or alias template
1657 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001658 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001659 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1660 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001661 Diag((*NewParam)->getLocation(),
1662 diag::err_template_param_pack_must_be_last_template_parameter);
1663 Invalid = true;
1664 }
1665
Douglas Gregordba32632009-02-10 19:49:53 +00001666 if (RedundantDefaultArg) {
1667 // C++ [temp.param]p12:
1668 // A template-parameter shall not be given default arguments
1669 // by two different declarations in the same scope.
1670 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1671 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1672 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001673 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001674 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675 // If a template-parameter of a class template has a default
1676 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001677 // have a default template-argument supplied or be a template parameter
1678 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001679 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001680 diag::err_template_param_default_arg_missing);
1681 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1682 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001683 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001684 }
1685
1686 // If we have an old template parameter list that we're merging
1687 // in, move on to the next parameter.
1688 if (OldParams)
1689 ++OldParam;
1690 }
1691
Douglas Gregor0693def2011-01-27 01:40:17 +00001692 // We were missing some default arguments at the end of the list, so remove
1693 // all of the default arguments.
1694 if (RemoveDefaultArguments) {
1695 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1696 NewParamEnd = NewParams->end();
1697 NewParam != NewParamEnd; ++NewParam) {
1698 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1699 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001700 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001701 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1702 NTTP->removeDefaultArgument();
1703 else
1704 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1705 }
1706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001707
Douglas Gregordba32632009-02-10 19:49:53 +00001708 return Invalid;
1709}
Douglas Gregord32e0282009-02-09 23:23:08 +00001710
John McCalla020a012010-10-20 05:44:58 +00001711namespace {
1712
1713/// A class which looks for a use of a certain level of template
1714/// parameter.
1715struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1716 typedef RecursiveASTVisitor<DependencyChecker> super;
1717
1718 unsigned Depth;
Richard Smith43a833b2017-01-09 23:54:33 +00001719 bool FindLessThanDepth;
Richard Smith57aae072016-12-28 02:37:25 +00001720
1721 // Whether we're looking for a use of a template parameter that makes the
1722 // overall construct type-dependent / a dependent type. This is strictly
1723 // best-effort for now; we may fail to match at all for a dependent type
1724 // in some cases if this is set.
1725 bool IgnoreNonTypeDependent;
1726
John McCalla020a012010-10-20 05:44:58 +00001727 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001728 SourceLocation MatchLoc;
1729
Richard Smith43a833b2017-01-09 23:54:33 +00001730 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent,
1731 bool FindLessThanDepth = false)
1732 : Depth(Depth), FindLessThanDepth(FindLessThanDepth),
1733 IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001734
Richard Smith57aae072016-12-28 02:37:25 +00001735 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith43a833b2017-01-09 23:54:33 +00001736 : DependencyChecker(Params->getDepth(), IgnoreNonTypeDependent) {}
John McCalla020a012010-10-20 05:44:58 +00001737
Richard Smith6056d5e2014-02-09 00:54:43 +00001738 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith43a833b2017-01-09 23:54:33 +00001739 if (FindLessThanDepth ^ (ParmDepth >= Depth)) {
John McCalla020a012010-10-20 05:44:58 +00001740 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001741 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001742 return true;
1743 }
1744 return false;
1745 }
1746
Richard Smith57aae072016-12-28 02:37:25 +00001747 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
1748 // Prune out non-type-dependent expressions if requested. This can
1749 // sometimes result in us failing to find a template parameter reference
1750 // (if a value-dependent expression creates a dependent type), but this
1751 // mode is best-effort only.
1752 if (auto *E = dyn_cast_or_null<Expr>(S))
1753 if (IgnoreNonTypeDependent && !E->isTypeDependent())
1754 return true;
1755 return super::TraverseStmt(S, Q);
1756 }
1757
1758 bool TraverseTypeLoc(TypeLoc TL) {
1759 if (IgnoreNonTypeDependent && !TL.isNull() &&
1760 !TL.getType()->isDependentType())
1761 return true;
1762 return super::TraverseTypeLoc(TL);
1763 }
1764
Richard Smith6056d5e2014-02-09 00:54:43 +00001765 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1766 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1767 }
1768
John McCalla020a012010-10-20 05:44:58 +00001769 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00001770 // For a best-effort search, keep looking until we find a location.
1771 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00001772 }
1773
1774 bool TraverseTemplateName(TemplateName N) {
1775 if (TemplateTemplateParmDecl *PD =
1776 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001777 if (Matches(PD->getDepth()))
1778 return false;
John McCalla020a012010-10-20 05:44:58 +00001779 return super::TraverseTemplateName(N);
1780 }
1781
1782 bool VisitDeclRefExpr(DeclRefExpr *E) {
1783 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001784 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1785 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001786 return false;
John McCalla020a012010-10-20 05:44:58 +00001787 return super::VisitDeclRefExpr(E);
1788 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001789
1790 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1791 return TraverseType(T->getReplacementType());
1792 }
1793
1794 bool
1795 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1796 return TraverseTemplateArgument(T->getArgumentPack());
1797 }
1798
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001799 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1800 return TraverseType(T->getInjectedSpecializationType());
1801 }
John McCalla020a012010-10-20 05:44:58 +00001802};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001803} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001804
Douglas Gregor972fe532011-05-10 18:27:06 +00001805/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001806/// list.
1807static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001808DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00001809 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00001810 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001811 return Checker.Match;
1812}
1813
Douglas Gregor972fe532011-05-10 18:27:06 +00001814// Find the source range corresponding to the named type in the given
1815// nested-name-specifier, if any.
1816static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1817 QualType T,
1818 const CXXScopeSpec &SS) {
1819 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1820 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1821 if (const Type *CurType = NNS->getAsType()) {
1822 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1823 return NNSLoc.getTypeLoc().getSourceRange();
1824 } else
1825 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001826
Douglas Gregor972fe532011-05-10 18:27:06 +00001827 NNSLoc = NNSLoc.getPrefix();
1828 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001829
Douglas Gregor972fe532011-05-10 18:27:06 +00001830 return SourceRange();
1831}
1832
Mike Stump11289f42009-09-09 15:08:12 +00001833/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001834/// specifier, returning the template parameter list that applies to the
1835/// name.
1836///
1837/// \param DeclStartLoc the start of the declaration that has a scope
1838/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001839///
Douglas Gregor972fe532011-05-10 18:27:06 +00001840/// \param DeclLoc The location of the declaration itself.
1841///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001842/// \param SS the scope specifier that will be matched to the given template
1843/// parameter lists. This scope specifier precedes a qualified name that is
1844/// being declared.
1845///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001846/// \param TemplateId The template-id following the scope specifier, if there
1847/// is one. Used to check for a missing 'template<>'.
1848///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001849/// \param ParamLists the template parameter lists, from the outermost to the
1850/// innermost template parameter lists.
1851///
John McCalle820e5e2010-04-13 20:37:33 +00001852/// \param IsFriend Whether to apply the slightly different rules for
1853/// matching template parameters to scope specifiers in friend
1854/// declarations.
1855///
Richard Smithf445f192017-02-09 21:04:43 +00001856/// \param IsMemberSpecialization will be set true if the scope specifier
1857/// denotes a fully-specialized type, and therefore this is a declaration of
1858/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001859///
Mike Stump11289f42009-09-09 15:08:12 +00001860/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001861/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001862/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001863/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001864/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001865/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001866TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1867 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001868 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001869 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00001870 bool &IsMemberSpecialization, bool &Invalid) {
1871 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001872 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001873
Douglas Gregor972fe532011-05-10 18:27:06 +00001874 // The sequence of nested types to which we will match up the template
1875 // parameter lists. We first build this list by starting with the type named
1876 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001877 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001878 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001879 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00001880 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001881 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1882 T = Context.getTypeDeclType(Record);
1883 else
1884 T = QualType(SS.getScopeRep()->getAsType(), 0);
1885 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001886
Douglas Gregor972fe532011-05-10 18:27:06 +00001887 // If we found an explicit specialization that prevents us from needing
1888 // 'template<>' headers, this will be set to the location of that
1889 // explicit specialization.
1890 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001891
Douglas Gregor972fe532011-05-10 18:27:06 +00001892 while (!T.isNull()) {
1893 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001894
Douglas Gregor972fe532011-05-10 18:27:06 +00001895 // Retrieve the parent of a record type.
1896 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1897 // If this type is an explicit specialization, we're done.
1898 if (ClassTemplateSpecializationDecl *Spec
1899 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00001900 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001901 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1902 ExplicitSpecLoc = Spec->getLocation();
1903 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001904 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001905 } else if (Record->getTemplateSpecializationKind()
1906 == TSK_ExplicitSpecialization) {
1907 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001908 break;
1909 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001910
Douglas Gregor972fe532011-05-10 18:27:06 +00001911 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1912 T = Context.getTypeDeclType(Parent);
1913 else
1914 T = QualType();
1915 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001916 }
1917
Douglas Gregor972fe532011-05-10 18:27:06 +00001918 if (const TemplateSpecializationType *TST
1919 = T->getAs<TemplateSpecializationType>()) {
1920 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1921 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1922 T = Context.getTypeDeclType(Parent);
1923 else
1924 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001925 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001926 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001927 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001928
Douglas Gregor972fe532011-05-10 18:27:06 +00001929 // Look one step prior in a dependent template specialization type.
1930 if (const DependentTemplateSpecializationType *DependentTST
1931 = T->getAs<DependentTemplateSpecializationType>()) {
1932 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1933 T = QualType(NNS->getAsType(), 0);
1934 else
1935 T = QualType();
1936 continue;
1937 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001938
Douglas Gregor972fe532011-05-10 18:27:06 +00001939 // Look one step prior in a dependent name type.
1940 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1941 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1942 T = QualType(NNS->getAsType(), 0);
1943 else
1944 T = QualType();
1945 continue;
1946 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001947
Douglas Gregor972fe532011-05-10 18:27:06 +00001948 // Retrieve the parent of an enumeration type.
1949 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1950 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1951 // check here.
1952 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001953
Douglas Gregor972fe532011-05-10 18:27:06 +00001954 // Get to the parent type.
1955 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1956 T = Context.getTypeDeclType(Parent);
1957 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00001958 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00001959 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001960 }
Mike Stump11289f42009-09-09 15:08:12 +00001961
Douglas Gregor972fe532011-05-10 18:27:06 +00001962 T = QualType();
1963 }
1964 // Reverse the nested types list, since we want to traverse from the outermost
1965 // to the innermost while checking template-parameter-lists.
1966 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001967
Douglas Gregor972fe532011-05-10 18:27:06 +00001968 // C++0x [temp.expl.spec]p17:
1969 // A member or a member template may be nested within many
1970 // enclosing class templates. In an explicit specialization for
1971 // such a member, the member declaration shall be preceded by a
1972 // template<> for each enclosing class template that is
1973 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001974 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001975
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001976 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001977 if (SawNonEmptyTemplateParameterList) {
1978 Diag(DeclLoc, diag::err_specialize_member_of_template)
1979 << !Recovery << Range;
1980 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00001981 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001982 return true;
1983 }
1984
1985 return false;
1986 };
1987
1988 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1989 // Check that we can have an explicit specialization here.
1990 if (CheckExplicitSpecialization(Range, true))
1991 return true;
1992
1993 // We don't have a template header, but we should.
1994 SourceLocation ExpectedTemplateLoc;
1995 if (!ParamLists.empty())
1996 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1997 else
1998 ExpectedTemplateLoc = DeclStartLoc;
1999
2000 Diag(DeclLoc, diag::err_template_spec_needs_header)
2001 << Range
2002 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2003 return false;
2004 };
2005
Douglas Gregor972fe532011-05-10 18:27:06 +00002006 unsigned ParamIdx = 0;
2007 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2008 ++TypeIdx) {
2009 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002010
Douglas Gregor972fe532011-05-10 18:27:06 +00002011 // Whether we expect a 'template<>' header.
2012 bool NeedEmptyTemplateHeader = false;
2013
2014 // Whether we expect a template header with parameters.
2015 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002016
Douglas Gregor972fe532011-05-10 18:27:06 +00002017 // For a dependent type, the set of template parameters that we
2018 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002019 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002020
Douglas Gregor373af9b2011-05-11 23:26:17 +00002021 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002022 // A member or a member template may be nested within many enclosing
2023 // class templates. In an explicit specialization for such a member, the
2024 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002025 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002026 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2027 if (ClassTemplatePartialSpecializationDecl *Partial
2028 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2029 ExpectedTemplateParams = Partial->getTemplateParameters();
2030 NeedNonemptyTemplateHeader = true;
2031 } else if (Record->isDependentType()) {
2032 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002033 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002034 ->getTemplateParameters();
2035 NeedNonemptyTemplateHeader = true;
2036 }
2037 } else if (ClassTemplateSpecializationDecl *Spec
2038 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2039 // C++0x [temp.expl.spec]p4:
2040 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002041 // in the same manner as members of normal classes, and not using
2042 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002043 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2044 NeedEmptyTemplateHeader = true;
2045 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002046 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002047 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002048 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002049 != TSK_ExplicitSpecialization &&
2050 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002051 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002052
Douglas Gregor373af9b2011-05-11 23:26:17 +00002053 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002054 }
2055 } else if (const TemplateSpecializationType *TST
2056 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002057 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002058 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002059 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002060 }
2061 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2062 // FIXME: We actually could/should check the template arguments here
2063 // against the corresponding template parameter list.
2064 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002065 }
2066
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002067 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002068 // In an explicit specialization declaration for a member of a class
2069 // template or a member template that ap- pears in namespace scope, the
2070 // member template and some of its enclosing class templates may remain
2071 // unspecialized, except that the declaration shall not explicitly
2072 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002073 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002074 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002075 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002076 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2077 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002078 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002079 } else
2080 SawNonEmptyTemplateParameterList = true;
2081 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002082
Douglas Gregor972fe532011-05-10 18:27:06 +00002083 if (NeedEmptyTemplateHeader) {
2084 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002085 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002086 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002087 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002088
2089 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002090 if (ParamLists[ParamIdx]->size() > 0) {
2091 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002092 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002093 diag::err_template_param_list_matches_nontemplate)
2094 << T
2095 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2096 ParamLists[ParamIdx]->getRAngleLoc())
2097 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2098 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002099 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002100 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002101
Douglas Gregor972fe532011-05-10 18:27:06 +00002102 // Consume this template header.
2103 ++ParamIdx;
2104 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002105 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002106
2107 if (!IsFriend)
2108 if (DiagnoseMissingExplicitSpecialization(
2109 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002110 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002111
Douglas Gregor972fe532011-05-10 18:27:06 +00002112 continue;
2113 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002114
Douglas Gregor972fe532011-05-10 18:27:06 +00002115 if (NeedNonemptyTemplateHeader) {
2116 // In friend declarations we can have template-ids which don't
2117 // depend on the corresponding template parameter lists. But
2118 // assume that empty parameter lists are supposed to match this
2119 // template-id.
2120 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002121 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002122 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002123 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002124 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002125 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002126 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002127
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002128 if (ParamIdx < ParamLists.size()) {
2129 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002130 if (ExpectedTemplateParams &&
2131 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2132 ExpectedTemplateParams,
2133 true, TPL_TemplateMatch))
2134 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002135
Douglas Gregor972fe532011-05-10 18:27:06 +00002136 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002137 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002138 TPC_ClassTemplateMember))
2139 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002140
Douglas Gregor972fe532011-05-10 18:27:06 +00002141 ++ParamIdx;
2142 continue;
2143 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002144
Douglas Gregor972fe532011-05-10 18:27:06 +00002145 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2146 << T
2147 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2148 Invalid = true;
2149 continue;
2150 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002151 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002152
Douglas Gregord8d297c2009-07-21 23:53:31 +00002153 // If there were at least as many template-ids as there were template
2154 // parameter lists, then there are no template parameter lists remaining for
2155 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002156 if (ParamIdx >= ParamLists.size()) {
2157 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002158 // We don't have a template header for the declaration itself, but we
2159 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002160 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2161 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002162
2163 // Fabricate an empty template parameter list for the invented header.
2164 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002165 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002166 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002167 }
2168
Craig Topperc3ec1492014-05-26 06:22:03 +00002169 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002170 }
Mike Stump11289f42009-09-09 15:08:12 +00002171
Douglas Gregord8d297c2009-07-21 23:53:31 +00002172 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002173 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002174 bool HasAnyExplicitSpecHeader = false;
2175 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002176 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002177 if (ParamLists[I]->size() == 0)
2178 HasAnyExplicitSpecHeader = true;
2179 else
2180 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002181 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002182
Douglas Gregor972fe532011-05-10 18:27:06 +00002183 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002184 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2185 : diag::err_template_spec_extra_headers)
2186 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2187 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002188
2189 // If there was a specialization somewhere, such that 'template<>' is
2190 // not required, and there were any 'template<>' headers, note where the
2191 // specialization occurred.
2192 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002193 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002194 diag::note_explicit_template_spec_does_not_need_header)
2195 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002196
Douglas Gregor972fe532011-05-10 18:27:06 +00002197 // We have a template parameter list with no corresponding scope, which
2198 // means that the resulting template declaration can't be instantiated
2199 // properly (we'll end up with dependent nodes when we shouldn't).
2200 if (!AllExplicitSpecHeaders)
2201 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002202 }
Mike Stump11289f42009-09-09 15:08:12 +00002203
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002204 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002205 // In an explicit specialization declaration for a member of a class
2206 // template or a member template that ap- pears in namespace scope, the
2207 // member template and some of its enclosing class templates may remain
2208 // unspecialized, except that the declaration shall not explicitly
2209 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002210 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002211 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002212 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2213 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002214 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002215
Douglas Gregord8d297c2009-07-21 23:53:31 +00002216 // Return the last template parameter list, which corresponds to the
2217 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002218 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002219}
2220
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002221void Sema::NoteAllFoundTemplates(TemplateName Name) {
2222 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2223 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002224 << (isa<FunctionTemplateDecl>(Template)
2225 ? 0
2226 : isa<ClassTemplateDecl>(Template)
2227 ? 1
2228 : isa<VarTemplateDecl>(Template)
2229 ? 2
2230 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2231 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002232 return;
2233 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002234
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002235 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002236 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002237 IEnd = OST->end();
2238 I != IEnd; ++I)
2239 Diag((*I)->getLocation(), diag::note_template_declared_here)
2240 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002241
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002242 return;
2243 }
2244}
2245
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002246static QualType
2247checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2248 const SmallVectorImpl<TemplateArgument> &Converted,
2249 SourceLocation TemplateLoc,
2250 TemplateArgumentListInfo &TemplateArgs) {
2251 ASTContext &Context = SemaRef.getASTContext();
2252 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002253 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002254 // Specializations of __make_integer_seq<S, T, N> are treated like
2255 // S<T, 0, ..., N-1>.
2256
2257 // C++14 [inteseq.intseq]p1:
2258 // T shall be an integer type.
2259 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2260 SemaRef.Diag(TemplateArgs[1].getLocation(),
2261 diag::err_integer_sequence_integral_element_type);
2262 return QualType();
2263 }
2264
2265 // C++14 [inteseq.make]p1:
2266 // If N is negative the program is ill-formed.
2267 TemplateArgument NumArgsArg = Converted[2];
2268 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2269 if (NumArgs < 0) {
2270 SemaRef.Diag(TemplateArgs[2].getLocation(),
2271 diag::err_integer_sequence_negative_length);
2272 return QualType();
2273 }
2274
2275 QualType ArgTy = NumArgsArg.getIntegralType();
2276 TemplateArgumentListInfo SyntheticTemplateArgs;
2277 // The type argument gets reused as the first template argument in the
2278 // synthetic template argument list.
2279 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2280 // Expand N into 0 ... N-1.
2281 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2282 I < NumArgs; ++I) {
2283 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002284 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2285 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002286 }
2287 // The first template argument will be reused as the template decl that
2288 // our synthetic template arguments will be applied to.
2289 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2290 TemplateLoc, SyntheticTemplateArgs);
2291 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002292
2293 case BTK__type_pack_element:
2294 // Specializations of
2295 // __type_pack_element<Index, T_1, ..., T_N>
2296 // are treated like T_Index.
2297 assert(Converted.size() == 2 &&
2298 "__type_pack_element should be given an index and a parameter pack");
2299
2300 // If the Index is out of bounds, the program is ill-formed.
2301 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2302 llvm::APSInt Index = IndexArg.getAsIntegral();
2303 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2304 "type std::size_t, and hence be non-negative");
2305 if (Index >= Ts.pack_size()) {
2306 SemaRef.Diag(TemplateArgs[0].getLocation(),
2307 diag::err_type_pack_element_out_of_bounds);
2308 return QualType();
2309 }
2310
2311 // We simply return the type at index `Index`.
2312 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2313 return Nth->getAsType();
2314 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002315 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2316}
2317
Douglas Gregordc572a32009-03-30 22:58:21 +00002318QualType Sema::CheckTemplateIdType(TemplateName Name,
2319 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002320 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002321 DependentTemplateName *DTN
2322 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002323 if (DTN && DTN->isIdentifier())
2324 // When building a template-id where the template-name is dependent,
2325 // assume the template is a type template. Either our assumption is
2326 // correct, or the code is ill-formed and will be diagnosed when the
2327 // dependent name is substituted.
2328 return Context.getDependentTemplateSpecializationType(ETK_None,
2329 DTN->getQualifier(),
2330 DTN->getIdentifier(),
2331 TemplateArgs);
2332
Douglas Gregordc572a32009-03-30 22:58:21 +00002333 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002334 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2335 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002336 // We might have a substituted template template parameter pack. If so,
2337 // build a template specialization type for it.
2338 if (Name.getAsSubstTemplateTemplateParmPack())
2339 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002340
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002341 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2342 << Name;
2343 NoteAllFoundTemplates(Name);
2344 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002345 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002346
Douglas Gregorc40290e2009-03-09 23:48:35 +00002347 // Check that the template argument list is well-formed for this
2348 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002349 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002350 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002351 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002352 return QualType();
2353
Douglas Gregorc40290e2009-03-09 23:48:35 +00002354 QualType CanonType;
2355
Douglas Gregor678d76c2011-07-01 01:22:09 +00002356 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002357 if (TypeAliasTemplateDecl *AliasTemplate =
2358 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002359 // Find the canonical type for this type alias template specialization.
2360 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2361 if (Pattern->isInvalidDecl())
2362 return QualType();
2363
2364 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002365 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002366
2367 // Only substitute for the innermost template argument list.
2368 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002369 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002370 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2371 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002372 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002373
Richard Smith802c4b72012-08-23 06:16:52 +00002374 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002375 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002376 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002377 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002378
Richard Smith3f1b5d02011-05-05 21:57:07 +00002379 CanonType = SubstType(Pattern->getUnderlyingType(),
2380 TemplateArgLists, AliasTemplate->getLocation(),
2381 AliasTemplate->getDeclName());
2382 if (CanonType.isNull())
2383 return QualType();
2384 } else if (Name.isDependent() ||
2385 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002386 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002387 // This class template specialization is a dependent
2388 // type. Therefore, its canonical type is another class template
2389 // specialization type that contains all of the converted
2390 // arguments in canonical form. This ensures that, e.g., A<T> and
2391 // A<T, T> have identical types when A is declared as:
2392 //
2393 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00002394 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00002395
2396 // This might work out to be a current instantiation, in which
2397 // case the canonical type needs to be the InjectedClassNameType.
2398 //
2399 // TODO: in theory this could be a simple hashtable lookup; most
2400 // changes to CurContext don't change the set of current
2401 // instantiations.
2402 if (isa<ClassTemplateDecl>(Template)) {
2403 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2404 // If we get out to a namespace, we're done.
2405 if (Ctx->isFileContext()) break;
2406
2407 // If this isn't a record, keep looking.
2408 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2409 if (!Record) continue;
2410
2411 // Look for one of the two cases with InjectedClassNameTypes
2412 // and check whether it's the same template.
2413 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2414 !Record->getDescribedClassTemplate())
2415 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002416
John McCall2408e322010-04-27 00:57:59 +00002417 // Fetch the injected class name type and check whether its
2418 // injected type is equal to the type we just built.
2419 QualType ICNT = Context.getTypeDeclType(Record);
2420 QualType Injected = cast<InjectedClassNameType>(ICNT)
2421 ->getInjectedSpecializationType();
2422
2423 if (CanonType != Injected->getCanonicalTypeInternal())
2424 continue;
2425
2426 // If so, the canonical type of this TST is the injected
2427 // class name type of the record we just found.
2428 assert(ICNT.isCanonical());
2429 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002430 break;
2431 }
2432 }
Mike Stump11289f42009-09-09 15:08:12 +00002433 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002434 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002435 // Find the class template specialization declaration that
2436 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002437 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002438 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002439 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002440 if (!Decl) {
2441 // This is the first time we have referenced this class template
2442 // specialization. Create the canonical declaration and add it to
2443 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002444 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002445 ClassTemplate->getTemplatedDecl()->getTagKind(),
2446 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002447 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002448 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002449 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00002450 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002451 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002452 if (ClassTemplate->isOutOfLine())
2453 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002454 }
2455
Chandler Carruth2acfb222013-09-27 22:14:40 +00002456 // Diagnose uses of this specialization.
2457 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2458
Douglas Gregorc40290e2009-03-09 23:48:35 +00002459 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002460 assert(isa<RecordType>(CanonType) &&
2461 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002462 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2463 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2464 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002465 }
Mike Stump11289f42009-09-09 15:08:12 +00002466
Douglas Gregorc40290e2009-03-09 23:48:35 +00002467 // Build the fully-sugared type for this class template
2468 // specialization, which refers back to the class template
2469 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002470 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002471}
2472
John McCallfaf5fb42010-08-26 23:41:50 +00002473TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002474Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00002475 TemplateTy TemplateD, IdentifierInfo *TemplateII,
2476 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00002477 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002478 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002479 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00002480 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002481 if (SS.isInvalid())
2482 return true;
2483
Richard Smith62559bd2017-02-01 21:36:38 +00002484 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
2485 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
2486
2487 // C++ [temp.res]p3:
2488 // A qualified-id that refers to a type and in which the
2489 // nested-name-specifier depends on a template-parameter (14.6.2)
2490 // shall be prefixed by the keyword typename to indicate that the
2491 // qualified-id denotes a type, forming an
2492 // elaborated-type-specifier (7.1.5.3).
2493 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00002494 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00002495 << SS.getScopeRep() << TemplateII->getName();
2496 // Recover as if 'typename' were specified.
2497 // FIXME: This is not quite correct recovery as we don't transform SS
2498 // into the corresponding dependent form (and we don't diagnose missing
2499 // 'template' keywords within SS as a result).
2500 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
2501 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
2502 TemplateArgsIn, RAngleLoc);
2503 }
2504
2505 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
2506 // it's not actually allowed to be used as a type in most cases. Because
2507 // we annotate it before we know whether it's valid, we have to check for
2508 // this case here.
2509 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00002510 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
2511 Diag(TemplateIILoc,
2512 TemplateKWLoc.isInvalid()
2513 ? diag::err_out_of_line_qualified_id_type_names_constructor
2514 : diag::ext_out_of_line_qualified_id_type_names_constructor)
2515 << TemplateII << 0 /*injected-class-name used as template name*/
2516 << 1 /*if any keyword was present, it was 'template'*/;
2517 }
2518 }
2519
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002520 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002521
Douglas Gregorc40290e2009-03-09 23:48:35 +00002522 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002523 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002524 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002525
Douglas Gregor5a064722011-02-28 17:23:35 +00002526 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002527 QualType T
2528 = Context.getDependentTemplateSpecializationType(ETK_None,
2529 DTN->getQualifier(),
2530 DTN->getIdentifier(),
2531 TemplateArgs);
2532 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002533 TypeLocBuilder TLB;
2534 DependentTemplateSpecializationTypeLoc SpecTL
2535 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002536 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2537 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002538 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00002539 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002540 SpecTL.setLAngleLoc(LAngleLoc);
2541 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002542 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2543 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2544 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2545 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002546
Richard Smith74f02342017-01-19 21:00:13 +00002547 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002548 if (Result.isNull())
2549 return true;
2550
Douglas Gregore7c20652011-03-02 00:47:37 +00002551 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002552 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002553 TemplateSpecializationTypeLoc SpecTL
2554 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002555 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00002556 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002557 SpecTL.setLAngleLoc(LAngleLoc);
2558 SpecTL.setRAngleLoc(RAngleLoc);
2559 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2560 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002561
Abramo Bagnara4244b432012-01-27 08:46:19 +00002562 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2563 // constructor or destructor name (in such a case, the scope specifier
2564 // will be attached to the enclosing Decl or Expr node).
2565 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002566 // Create an elaborated-type-specifier containing the nested-name-specifier.
2567 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2568 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002569 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002570 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2571 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002572
Douglas Gregore7c20652011-03-02 00:47:37 +00002573 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002574}
John McCall06f6fe8d2009-09-04 01:14:41 +00002575
Douglas Gregore7c20652011-03-02 00:47:37 +00002576TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002577 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002578 SourceLocation TagLoc,
2579 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002580 SourceLocation TemplateKWLoc,
2581 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002582 SourceLocation TemplateLoc,
2583 SourceLocation LAngleLoc,
2584 ASTTemplateArgsPtr TemplateArgsIn,
2585 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002586 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002587
Douglas Gregore7c20652011-03-02 00:47:37 +00002588 // Translate the parser's template argument list in our AST format.
2589 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2590 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002591
Douglas Gregore7c20652011-03-02 00:47:37 +00002592 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002593 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002594 ElaboratedTypeKeyword Keyword
2595 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002596
Douglas Gregore7c20652011-03-02 00:47:37 +00002597 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2598 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00002599 DTN->getQualifier(),
2600 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00002601 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002602
2603 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00002604 TypeLocBuilder TLB;
2605 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002606 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2607 SpecTL.setElaboratedKeywordLoc(TagLoc);
2608 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002609 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002610 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002611 SpecTL.setLAngleLoc(LAngleLoc);
2612 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002613 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2614 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2615 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2616 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002617
2618 if (TypeAliasTemplateDecl *TAT =
2619 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2620 // C++0x [dcl.type.elab]p2:
2621 // If the identifier resolves to a typedef-name or the simple-template-id
2622 // resolves to an alias template specialization, the
2623 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00002624 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
2625 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002626 Diag(TAT->getLocation(), diag::note_declared_at);
2627 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002628
Douglas Gregore7c20652011-03-02 00:47:37 +00002629 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2630 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002631 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002632
Douglas Gregore7c20652011-03-02 00:47:37 +00002633 // Check the tag kind
2634 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002635 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002636
John McCalld8fe9af2009-09-08 17:47:29 +00002637 IdentifierInfo *Id = D->getIdentifier();
2638 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00002639
Richard Trieucaa33d32011-06-10 03:11:26 +00002640 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002641 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002642 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002643 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002644 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002645 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002646 }
2647 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002648
Douglas Gregore7c20652011-03-02 00:47:37 +00002649 // Provide source-location information for the template specialization.
2650 TypeLocBuilder TLB;
2651 TemplateSpecializationTypeLoc SpecTL
2652 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002653 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002654 SpecTL.setTemplateNameLoc(TemplateLoc);
2655 SpecTL.setLAngleLoc(LAngleLoc);
2656 SpecTL.setRAngleLoc(RAngleLoc);
2657 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2658 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002659
Douglas Gregore7c20652011-03-02 00:47:37 +00002660 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002661 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002662 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2663 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002664 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002665 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2666 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002667}
2668
Larisse Voufo39a1e502013-08-06 01:03:05 +00002669static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2670 NamedDecl *PrevDecl,
2671 SourceLocation Loc,
2672 bool IsPartialSpecialization);
2673
2674static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002675
Richard Smith300e0c32013-09-24 04:49:23 +00002676static bool isTemplateArgumentTemplateParameter(
2677 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2678 switch (Arg.getKind()) {
2679 case TemplateArgument::Null:
2680 case TemplateArgument::NullPtr:
2681 case TemplateArgument::Integral:
2682 case TemplateArgument::Declaration:
2683 case TemplateArgument::Pack:
2684 case TemplateArgument::TemplateExpansion:
2685 return false;
2686
2687 case TemplateArgument::Type: {
2688 QualType Type = Arg.getAsType();
2689 const TemplateTypeParmType *TPT =
2690 Arg.getAsType()->getAs<TemplateTypeParmType>();
2691 return TPT && !Type.hasQualifiers() &&
2692 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2693 }
2694
2695 case TemplateArgument::Expression: {
2696 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2697 if (!DRE || !DRE->getDecl())
2698 return false;
2699 const NonTypeTemplateParmDecl *NTTP =
2700 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2701 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2702 }
2703
2704 case TemplateArgument::Template:
2705 const TemplateTemplateParmDecl *TTP =
2706 dyn_cast_or_null<TemplateTemplateParmDecl>(
2707 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2708 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2709 }
2710 llvm_unreachable("unexpected kind of template argument");
2711}
2712
2713static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2714 ArrayRef<TemplateArgument> Args) {
2715 if (Params->size() != Args.size())
2716 return false;
2717
2718 unsigned Depth = Params->getDepth();
2719
2720 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2721 TemplateArgument Arg = Args[I];
2722
2723 // If the parameter is a pack expansion, the argument must be a pack
2724 // whose only element is a pack expansion.
2725 if (Params->getParam(I)->isParameterPack()) {
2726 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2727 !Arg.pack_begin()->isPackExpansion())
2728 return false;
2729 Arg = Arg.pack_begin()->getPackExpansionPattern();
2730 }
2731
2732 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2733 return false;
2734 }
2735
2736 return true;
2737}
2738
Richard Smith4b55a9c2014-04-17 03:29:33 +00002739/// Convert the parser's template argument list representation into our form.
2740static TemplateArgumentListInfo
2741makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2742 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2743 TemplateId.RAngleLoc);
2744 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2745 TemplateId.NumArgs);
2746 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2747 return TemplateArgs;
2748}
2749
Richard Smith0e617ec2016-12-27 07:56:27 +00002750template<typename PartialSpecDecl>
2751static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
2752 if (Partial->getDeclContext()->isDependentContext())
2753 return;
2754
2755 // FIXME: Get the TDK from deduction in order to provide better diagnostics
2756 // for non-substitution-failure issues?
2757 TemplateDeductionInfo Info(Partial->getLocation());
2758 if (S.isMoreSpecializedThanPrimary(Partial, Info))
2759 return;
2760
2761 auto *Template = Partial->getSpecializedTemplate();
2762 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00002763 diag::ext_partial_spec_not_more_specialized_than_primary)
2764 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00002765
2766 if (Info.hasSFINAEDiagnostic()) {
2767 PartialDiagnosticAt Diag = {SourceLocation(),
2768 PartialDiagnostic::NullDiagnostic()};
2769 Info.takeSFINAEDiagnostic(Diag);
2770 SmallString<128> SFINAEArgString;
2771 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
2772 S.Diag(Diag.first,
2773 diag::note_partial_spec_not_more_specialized_than_primary)
2774 << SFINAEArgString;
2775 }
2776
2777 S.Diag(Template->getLocation(), diag::note_template_decl_here);
2778}
2779
Richard Smith57aae072016-12-28 02:37:25 +00002780template<typename PartialSpecDecl>
2781static void checkTemplatePartialSpecialization(Sema &S,
2782 PartialSpecDecl *Partial) {
2783 // C++1z [temp.class.spec]p8: (DR1495)
2784 // - The specialization shall be more specialized than the primary
2785 // template (14.5.5.2).
2786 checkMoreSpecializedThanPrimary(S, Partial);
2787
2788 // C++ [temp.class.spec]p8: (DR1315)
2789 // - Each template-parameter shall appear at least once in the
2790 // template-id outside a non-deduced context.
2791 // C++1z [temp.class.spec.match]p3 (P0127R2)
2792 // If the template arguments of a partial specialization cannot be
2793 // deduced because of the structure of its template-parameter-list
2794 // and the template-id, the program is ill-formed.
2795 auto *TemplateParams = Partial->getTemplateParameters();
2796 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2797 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2798 TemplateParams->getDepth(), DeducibleParams);
2799
2800 if (!DeducibleParams.all()) {
2801 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
2802 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
2803 << isa<VarTemplatePartialSpecializationDecl>(Partial)
2804 << (NumNonDeducible > 1)
2805 << SourceRange(Partial->getLocation(),
2806 Partial->getTemplateArgsAsWritten()->RAngleLoc);
2807 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2808 if (!DeducibleParams[I]) {
2809 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2810 if (Param->getDeclName())
2811 S.Diag(Param->getLocation(),
2812 diag::note_partial_spec_unused_parameter)
2813 << Param->getDeclName();
2814 else
2815 S.Diag(Param->getLocation(),
2816 diag::note_partial_spec_unused_parameter)
2817 << "(anonymous)";
2818 }
2819 }
2820 }
2821}
2822
2823void Sema::CheckTemplatePartialSpecialization(
2824 ClassTemplatePartialSpecializationDecl *Partial) {
2825 checkTemplatePartialSpecialization(*this, Partial);
2826}
2827
2828void Sema::CheckTemplatePartialSpecialization(
2829 VarTemplatePartialSpecializationDecl *Partial) {
2830 checkTemplatePartialSpecialization(*this, Partial);
2831}
2832
Larisse Voufo39a1e502013-08-06 01:03:05 +00002833DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002834 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002835 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002836 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002837 // D must be variable template id.
2838 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2839 "Variable template specialization is declared with a template it.");
2840
2841 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002842 TemplateArgumentListInfo TemplateArgs =
2843 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002844 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2845 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2846 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002847
Richard Smithbeef3452014-01-16 23:39:20 +00002848 TemplateName Name = TemplateId->Template.get();
2849
2850 // The template-id must name a variable template.
2851 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002852 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2853 if (!VarTemplate) {
2854 NamedDecl *FnTemplate;
2855 if (auto *OTS = Name.getAsOverloadedTemplate())
2856 FnTemplate = *OTS->begin();
2857 else
2858 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2859 if (FnTemplate)
2860 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2861 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002862 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2863 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002864 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002865
2866 // Check for unexpanded parameter packs in any of the template arguments.
2867 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2868 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2869 UPPC_PartialSpecialization))
2870 return true;
2871
2872 // Check that the template argument list is well-formed for this
2873 // template.
2874 SmallVector<TemplateArgument, 4> Converted;
2875 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2876 false, Converted))
2877 return true;
2878
Larisse Voufo39a1e502013-08-06 01:03:05 +00002879 // Find the variable template (partial) specialization declaration that
2880 // corresponds to these arguments.
2881 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00002882 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
2883 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002884 return true;
2885
Richard Smith57aae072016-12-28 02:37:25 +00002886 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
2887 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002888 bool InstantiationDependent;
2889 if (!Name.isDependent() &&
2890 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00002891 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00002892 InstantiationDependent)) {
2893 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2894 << VarTemplate->getDeclName();
2895 IsPartialSpecialization = false;
2896 }
Richard Smith300e0c32013-09-24 04:49:23 +00002897
2898 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2899 Converted)) {
2900 // C++ [temp.class.spec]p9b3:
2901 //
2902 // -- The argument list of the specialization shall not be identical
2903 // to the implicit argument list of the primary template.
2904 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2905 << /*variable template*/ 1
2906 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2907 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2908 // FIXME: Recover from this by treating the declaration as a redeclaration
2909 // of the primary template.
2910 return true;
2911 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002912 }
2913
Craig Topperc3ec1492014-05-26 06:22:03 +00002914 void *InsertPos = nullptr;
2915 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002916
2917 if (IsPartialSpecialization)
2918 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002919 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002920 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002921 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002922
Craig Topperc3ec1492014-05-26 06:22:03 +00002923 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002924
2925 // Check whether we can declare a variable template specialization in
2926 // the current scope.
2927 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2928 TemplateNameLoc,
2929 IsPartialSpecialization))
2930 return true;
2931
2932 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2933 // Since the only prior variable template specialization with these
2934 // arguments was referenced but not declared, reuse that
2935 // declaration node as our own, updating its source location and
2936 // the list of outer template parameters to reflect our new declaration.
2937 Specialization = PrevDecl;
2938 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002939 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002940 } else if (IsPartialSpecialization) {
2941 // Create a new class template partial specialization declaration node.
2942 VarTemplatePartialSpecializationDecl *PrevPartial =
2943 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002944 VarTemplatePartialSpecializationDecl *Partial =
2945 VarTemplatePartialSpecializationDecl::Create(
2946 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2947 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00002948 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002949
2950 if (!PrevPartial)
2951 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2952 Specialization = Partial;
2953
2954 // If we are providing an explicit specialization of a member variable
2955 // template specialization, make a note of that.
2956 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002957 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002958
Richard Smith57aae072016-12-28 02:37:25 +00002959 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002960 } else {
2961 // Create a new class template specialization declaration node for
2962 // this explicit specialization or friend declaration.
2963 Specialization = VarTemplateSpecializationDecl::Create(
2964 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00002965 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002966 Specialization->setTemplateArgsInfo(TemplateArgs);
2967
2968 if (!PrevDecl)
2969 VarTemplate->AddSpecialization(Specialization, InsertPos);
2970 }
2971
2972 // C++ [temp.expl.spec]p6:
2973 // If a template, a member template or the member of a class template is
2974 // explicitly specialized then that specialization shall be declared
2975 // before the first use of that specialization that would cause an implicit
2976 // instantiation to take place, in every translation unit in which such a
2977 // use occurs; no diagnostic is required.
2978 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2979 bool Okay = false;
2980 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2981 // Is there any previous explicit specialization declaration?
2982 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2983 Okay = true;
2984 break;
2985 }
2986 }
2987
2988 if (!Okay) {
2989 SourceRange Range(TemplateNameLoc, RAngleLoc);
2990 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2991 << Name << Range;
2992
2993 Diag(PrevDecl->getPointOfInstantiation(),
2994 diag::note_instantiation_required_here)
2995 << (PrevDecl->getTemplateSpecializationKind() !=
2996 TSK_ImplicitInstantiation);
2997 return true;
2998 }
2999 }
3000
3001 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3002 Specialization->setLexicalDeclContext(CurContext);
3003
3004 // Add the specialization into its lexical context, so that it can
3005 // be seen when iterating through the list of declarations in that
3006 // context. However, specializations are not found by name lookup.
3007 CurContext->addDecl(Specialization);
3008
3009 // Note that this is an explicit specialization.
3010 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3011
3012 if (PrevDecl) {
3013 // Check that this isn't a redefinition of this specialization,
3014 // merging with previous declarations.
3015 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3016 ForRedeclaration);
3017 PrevSpec.addDecl(PrevDecl);
3018 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003019 } else if (Specialization->isStaticDataMember() &&
3020 Specialization->isOutOfLine()) {
3021 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003022 }
3023
3024 // Link instantiations of static data members back to the template from
3025 // which they were instantiated.
3026 if (Specialization->isStaticDataMember())
3027 Specialization->setInstantiationOfStaticDataMember(
3028 VarTemplate->getTemplatedDecl(),
3029 Specialization->getSpecializationKind());
3030
3031 return Specialization;
3032}
3033
3034namespace {
3035/// \brief A partial specialization whose template arguments have matched
3036/// a given template-id.
3037struct PartialSpecMatchResult {
3038 VarTemplatePartialSpecializationDecl *Partial;
3039 TemplateArgumentList *Args;
3040};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003041} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003042
3043DeclResult
3044Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3045 SourceLocation TemplateNameLoc,
3046 const TemplateArgumentListInfo &TemplateArgs) {
3047 assert(Template && "A variable template id without template?");
3048
3049 // Check that the template argument list is well-formed for this template.
3050 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003051 if (CheckTemplateArgumentList(
3052 Template, TemplateNameLoc,
3053 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003054 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003055 return true;
3056
3057 // Find the variable template specialization declaration that
3058 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003059 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003060 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003061 Converted, InsertPos)) {
3062 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003063 // If we already have a variable template specialization, return it.
3064 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003065 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003066
3067 // This is the first time we have referenced this variable template
3068 // specialization. Create the canonical declaration and add it to
3069 // the set of specializations, based on the closest partial specialization
3070 // that it represents. That is,
3071 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3072 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003073 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003074 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3075 bool AmbiguousPartialSpec = false;
3076 typedef PartialSpecMatchResult MatchResult;
3077 SmallVector<MatchResult, 4> Matched;
3078 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003079 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3080 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003081
3082 // 1. Attempt to find the closest partial specialization that this
3083 // specializes, if any.
3084 // If any of the template arguments is dependent, then this is probably
3085 // a placeholder for an incomplete declarative context; which must be
3086 // complete by instantiation time. Thus, do not search through the partial
3087 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003088 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3089 // Perhaps better after unification of DeduceTemplateArguments() and
3090 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003091 bool InstantiationDependent = false;
3092 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3093 TemplateArgs, InstantiationDependent)) {
3094
3095 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3096 Template->getPartialSpecializations(PartialSpecs);
3097
3098 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3099 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3100 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3101
3102 if (TemplateDeductionResult Result =
3103 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3104 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003105 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003106 FailedCandidates.addCandidate().set(
3107 DeclAccessPair::make(Template, AS_public), Partial,
3108 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003109 (void)Result;
3110 } else {
3111 Matched.push_back(PartialSpecMatchResult());
3112 Matched.back().Partial = Partial;
3113 Matched.back().Args = Info.take();
3114 }
3115 }
3116
Larisse Voufo39a1e502013-08-06 01:03:05 +00003117 if (Matched.size() >= 1) {
3118 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3119 if (Matched.size() == 1) {
3120 // -- If exactly one matching specialization is found, the
3121 // instantiation is generated from that specialization.
3122 // We don't need to do anything for this.
3123 } else {
3124 // -- If more than one matching specialization is found, the
3125 // partial order rules (14.5.4.2) are used to determine
3126 // whether one of the specializations is more specialized
3127 // than the others. If none of the specializations is more
3128 // specialized than all of the other matching
3129 // specializations, then the use of the variable template is
3130 // ambiguous and the program is ill-formed.
3131 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3132 PEnd = Matched.end();
3133 P != PEnd; ++P) {
3134 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3135 PointOfInstantiation) ==
3136 P->Partial)
3137 Best = P;
3138 }
3139
3140 // Determine if the best partial specialization is more specialized than
3141 // the others.
3142 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3143 PEnd = Matched.end();
3144 P != PEnd; ++P) {
3145 if (P != Best && getMoreSpecializedPartialSpecialization(
3146 P->Partial, Best->Partial,
3147 PointOfInstantiation) != Best->Partial) {
3148 AmbiguousPartialSpec = true;
3149 break;
3150 }
3151 }
3152 }
3153
3154 // Instantiate using the best variable template partial specialization.
3155 InstantiationPattern = Best->Partial;
3156 InstantiationArgs = Best->Args;
3157 } else {
3158 // -- If no match is found, the instantiation is generated
3159 // from the primary template.
3160 // InstantiationPattern = Template->getTemplatedDecl();
3161 }
3162 }
3163
Larisse Voufo39a1e502013-08-06 01:03:05 +00003164 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00003165 // Note that we do not instantiate a definition until we see an odr-use
3166 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003167 // FIXME: LateAttrs et al.?
3168 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3169 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3170 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3171 if (!Decl)
3172 return true;
3173
3174 if (AmbiguousPartialSpec) {
3175 // Partial ordering did not produce a clear winner. Complain.
3176 Decl->setInvalidDecl();
3177 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3178 << Decl;
3179
3180 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00003181 for (MatchResult P : Matched)
3182 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3183 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3184 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003185 return true;
3186 }
3187
3188 if (VarTemplatePartialSpecializationDecl *D =
3189 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3190 Decl->setInstantiationOf(D, InstantiationArgs);
3191
Richard Smith6739a102016-05-05 00:56:12 +00003192 checkSpecializationVisibility(TemplateNameLoc, Decl);
3193
Larisse Voufo39a1e502013-08-06 01:03:05 +00003194 assert(Decl && "No variable template specialization?");
3195 return Decl;
3196}
3197
3198ExprResult
3199Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3200 const DeclarationNameInfo &NameInfo,
3201 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3202 const TemplateArgumentListInfo *TemplateArgs) {
3203
3204 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3205 *TemplateArgs);
3206 if (Decl.isInvalid())
3207 return ExprError();
3208
3209 VarDecl *Var = cast<VarDecl>(Decl.get());
3210 if (!Var->getTemplateSpecializationKind())
3211 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3212 NameInfo.getLoc());
3213
3214 // Build an ordinary singleton decl ref.
3215 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003216 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003217}
3218
John McCalldadc5752010-08-24 06:29:42 +00003219ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003220 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003221 LookupResult &R,
3222 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003223 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003224 // FIXME: Can we do any checking at this point? I guess we could check the
3225 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003226 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003227 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003228 // foo<int> could identify a single function unambiguously
3229 // This approach does NOT work, since f<int>(1);
3230 // gets resolved prior to resorting to overload resolution
3231 // i.e., template<class T> void f(double);
3232 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003233
3234 // These should be filtered out by our callers.
3235 assert(!R.empty() && "empty lookup results when building templateid");
3236 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3237
Larisse Voufo39a1e502013-08-06 01:03:05 +00003238 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003239 bool InstantiationDependent;
3240 if (R.getAsSingle<VarTemplateDecl>() &&
3241 !TemplateSpecializationType::anyDependentTemplateArguments(
3242 *TemplateArgs, InstantiationDependent)) {
3243 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3244 R.getAsSingle<VarTemplateDecl>(),
3245 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003246 }
3247
John McCall58cc69d2010-01-27 01:50:18 +00003248 // We don't want lookup warnings at this point.
3249 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003250
John McCalle66edc12009-11-24 19:00:30 +00003251 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003252 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003253 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003254 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003255 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003256 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003257 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003258
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003259 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003260}
3261
John McCalle66edc12009-11-24 19:00:30 +00003262// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003263ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003264Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003265 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003266 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003267 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003268
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003269 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003270 DeclContext *DC;
3271 if (!(DC = computeDeclContext(SS, false)) ||
3272 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003273 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003274 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003275
Douglas Gregor786123d2010-05-21 23:18:07 +00003276 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003277 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003278 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003279 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003280
John McCalle66edc12009-11-24 19:00:30 +00003281 if (R.isAmbiguous())
3282 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003283
John McCalle66edc12009-11-24 19:00:30 +00003284 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003285 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3286 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003287 return ExprError();
3288 }
3289
3290 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003291 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003292 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003293 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003294 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3295 return ExprError();
3296 }
3297
Abramo Bagnara7945c982012-01-27 09:46:47 +00003298 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003299}
3300
Douglas Gregorb67535d2009-03-31 00:43:58 +00003301/// \brief Form a dependent template name.
3302///
3303/// This action forms a dependent template name given the template
3304/// name and its (presumably dependent) scope specifier. For
3305/// example, given "MetaFun::template apply", the scope specifier \p
3306/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3307/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003308TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003309 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003310 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003311 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003312 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003313 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00003314 TemplateTy &Result,
3315 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003316 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3317 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003318 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003319 diag::warn_cxx98_compat_template_outside_of_template :
3320 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003321 << FixItHint::CreateRemoval(TemplateKWLoc);
3322
Craig Topperc3ec1492014-05-26 06:22:03 +00003323 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003324 if (SS.isSet())
3325 LookupCtx = computeDeclContext(SS, EnteringContext);
3326 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003327 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003328 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003329 // C++0x [temp.names]p5:
3330 // If a name prefixed by the keyword template is not the name of
3331 // a template, the program is ill-formed. [Note: the keyword
3332 // template may not be applied to non-template members of class
3333 // templates. -end note ] [ Note: as is the case with the
3334 // typename prefix, the template prefix is allowed in cases
3335 // where it is not strictly necessary; i.e., when the
3336 // nested-name-specifier or the expression on the left of the ->
3337 // or . is not dependent on a template-parameter, or the use
3338 // does not appear in the scope of a template. -end note]
3339 //
3340 // Note: C++03 was more strict here, because it banned the use of
3341 // the "template" keyword prior to a template-name that was not a
3342 // dependent name. C++ DR468 relaxed this requirement (the
3343 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003344 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003345 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003346 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003347 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003348 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003349 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3350 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003351 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3352 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003353 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003354 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003355 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003356 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003357 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003358 << Name.getSourceRange()
3359 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003360 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003361 } else {
3362 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00003363 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
3364 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
3365 Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
3366 LookupRD->getIdentifier() == Name.Identifier) {
3367 // C++14 [class.qual]p2:
3368 // In a lookup in which function names are not ignored and the
3369 // nested-name-specifier nominates a class C, if the name specified
3370 // [...] is the injected-class-name of C, [...] the name is instead
3371 // considered to name the constructor
3372 //
3373 // We don't get here if naming the constructor would be valid, so we
3374 // just reject immediately and recover by treating the
3375 // injected-class-name as naming the template.
3376 Diag(Name.getLocStart(),
3377 diag::ext_out_of_line_qualified_id_type_names_constructor)
3378 << Name.Identifier << 0 /*injected-class-name used as template name*/
3379 << 1 /*'template' keyword was used*/;
3380 }
Douglas Gregorbb119652010-06-16 23:00:59 +00003381 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003382 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003383 }
3384
Aaron Ballman4a979672014-01-03 13:56:08 +00003385 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003386
Douglas Gregor3cf81312009-11-03 23:16:33 +00003387 switch (Name.getKind()) {
3388 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003389 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003390 Name.Identifier));
3391 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392
Douglas Gregor71395fa2009-11-04 00:56:37 +00003393 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003394 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003395 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003396 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003397
3398 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003399 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003400
Douglas Gregor3cf81312009-11-03 23:16:33 +00003401 default:
3402 break;
3403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003404
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003405 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003406 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003407 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003408 << Name.getSourceRange()
3409 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003410 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003411}
3412
Mike Stump11289f42009-09-09 15:08:12 +00003413bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003414 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003415 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003416 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003417 QualType ArgType;
3418 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003419
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003420 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003421 switch(Arg.getKind()) {
3422 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003423 // C++ [temp.arg.type]p1:
3424 // A template-argument for a template-parameter which is a
3425 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003426 ArgType = Arg.getAsType();
3427 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003428 break;
3429 case TemplateArgument::Template: {
3430 // We have a template type parameter but the template argument
3431 // is a template without any arguments.
3432 SourceRange SR = AL.getSourceRange();
3433 TemplateName Name = Arg.getAsTemplate();
3434 Diag(SR.getBegin(), diag::err_template_missing_args)
Richard Smith0c062b42017-01-14 02:19:59 +00003435 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003436 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3437 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003438
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003439 return true;
3440 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003441 case TemplateArgument::Expression: {
3442 // We have a template type parameter but the template argument is an
3443 // expression; see if maybe it is missing the "typename" keyword.
3444 CXXScopeSpec SS;
3445 DeclarationNameInfo NameInfo;
3446
3447 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3448 SS.Adopt(ArgExpr->getQualifierLoc());
3449 NameInfo = ArgExpr->getNameInfo();
3450 } else if (DependentScopeDeclRefExpr *ArgExpr =
3451 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3452 SS.Adopt(ArgExpr->getQualifierLoc());
3453 NameInfo = ArgExpr->getNameInfo();
3454 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3455 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003456 if (ArgExpr->isImplicitAccess()) {
3457 SS.Adopt(ArgExpr->getQualifierLoc());
3458 NameInfo = ArgExpr->getMemberNameInfo();
3459 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003460 }
3461
Reid Kleckner377c1592014-06-10 23:29:48 +00003462 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003463 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3464 LookupParsedName(Result, CurScope, &SS);
3465
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003466 if (Result.getAsSingle<TypeDecl>() ||
3467 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003468 LookupResult::NotFoundInCurrentInstantiation) {
3469 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003470 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003471 Diag(Loc, getLangOpts().MSVCCompat
3472 ? diag::ext_ms_template_type_arg_missing_typename
3473 : diag::err_template_arg_must_be_type_suggest)
3474 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003475 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003476
3477 // Recover by synthesizing a type using the location information that we
3478 // already have.
3479 ArgType =
3480 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3481 TypeLocBuilder TLB;
3482 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3483 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3484 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3485 TL.setNameLoc(NameInfo.getLoc());
3486 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3487
3488 // Overwrite our input TemplateArgumentLoc so that we can recover
3489 // properly.
3490 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3491 TemplateArgumentLocInfo(TSI));
3492
3493 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003494 }
3495 }
3496 // fallthrough
3497 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003498 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003499 // We have a template type parameter but the template argument
3500 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003501 SourceRange SR = AL.getSourceRange();
3502 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003503 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003504
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003505 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003506 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003507 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003508
Reid Kleckner377c1592014-06-10 23:29:48 +00003509 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003510 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003511
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003512 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003513 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003514
Douglas Gregore46db902011-06-17 22:11:49 +00003515 // Objective-C ARC:
3516 // If an explicitly-specified template argument type is a lifetime type
3517 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003518 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003519 ArgType->isObjCLifetimeType() &&
3520 !ArgType.getObjCLifetime()) {
3521 Qualifiers Qs;
3522 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3523 ArgType = Context.getQualifiedType(ArgType, Qs);
3524 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003525
Douglas Gregore46db902011-06-17 22:11:49 +00003526 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003527 return false;
3528}
3529
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003530/// \brief Substitute template arguments into the default template argument for
3531/// the given template type parameter.
3532///
3533/// \param SemaRef the semantic analysis object for which we are performing
3534/// the substitution.
3535///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003536/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003537/// for.
3538///
3539/// \param TemplateLoc the location of the template name that started the
3540/// template-id we are checking.
3541///
3542/// \param RAngleLoc the location of the right angle bracket ('>') that
3543/// terminates the template-id.
3544///
3545/// \param Param the template template parameter whose default we are
3546/// substituting into.
3547///
3548/// \param Converted the list of template arguments provided for template
3549/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003550/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003551static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003552SubstDefaultTemplateArgument(Sema &SemaRef,
3553 TemplateDecl *Template,
3554 SourceLocation TemplateLoc,
3555 SourceLocation RAngleLoc,
3556 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003557 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003558 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003559
3560 // If the argument type is dependent, instantiate it now based
3561 // on the previously-computed template arguments.
3562 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003563 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003564 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003565 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003566 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003567 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003568
David Majnemer8b622692016-07-03 21:17:51 +00003569 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003570
3571 // Only substitute for the innermost template argument list.
3572 MultiLevelTemplateArgumentList TemplateArgLists;
3573 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3574 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3575 TemplateArgLists.addOuterTemplateArguments(None);
3576
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003577 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003578 ArgType =
3579 SemaRef.SubstType(ArgType, TemplateArgLists,
3580 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003581 }
3582
3583 return ArgType;
3584}
3585
3586/// \brief Substitute template arguments into the default template argument for
3587/// the given non-type template parameter.
3588///
3589/// \param SemaRef the semantic analysis object for which we are performing
3590/// the substitution.
3591///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003592/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003593/// for.
3594///
3595/// \param TemplateLoc the location of the template name that started the
3596/// template-id we are checking.
3597///
3598/// \param RAngleLoc the location of the right angle bracket ('>') that
3599/// terminates the template-id.
3600///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003601/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003602/// substituting into.
3603///
3604/// \param Converted the list of template arguments provided for template
3605/// parameters that precede \p Param in the template parameter list.
3606///
3607/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003608static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003609SubstDefaultTemplateArgument(Sema &SemaRef,
3610 TemplateDecl *Template,
3611 SourceLocation TemplateLoc,
3612 SourceLocation RAngleLoc,
3613 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003614 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003615 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003616 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003617 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003618 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003619 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003620
David Majnemer8b622692016-07-03 21:17:51 +00003621 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003622
3623 // Only substitute for the innermost template argument list.
3624 MultiLevelTemplateArgumentList TemplateArgLists;
3625 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3626 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3627 TemplateArgLists.addOuterTemplateArguments(None);
3628
Faisal Vali48401eb2015-11-19 19:20:17 +00003629 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3630 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003631 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003632}
3633
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003634/// \brief Substitute template arguments into the default template argument for
3635/// the given template template parameter.
3636///
3637/// \param SemaRef the semantic analysis object for which we are performing
3638/// the substitution.
3639///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003641/// for.
3642///
3643/// \param TemplateLoc the location of the template name that started the
3644/// template-id we are checking.
3645///
3646/// \param RAngleLoc the location of the right angle bracket ('>') that
3647/// terminates the template-id.
3648///
3649/// \param Param the template template parameter whose default we are
3650/// substituting into.
3651///
3652/// \param Converted the list of template arguments provided for template
3653/// parameters that precede \p Param in the template parameter list.
3654///
Simon Pilgrim6905d222016-12-30 22:55:33 +00003655/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00003656/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003657///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003658/// \returns the substituted template argument, or NULL if an error occurred.
3659static TemplateName
3660SubstDefaultTemplateArgument(Sema &SemaRef,
3661 TemplateDecl *Template,
3662 SourceLocation TemplateLoc,
3663 SourceLocation RAngleLoc,
3664 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003665 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003666 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00003667 Sema::InstantiatingTemplate Inst(
3668 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
3669 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003670 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003671 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003672
David Majnemer8b622692016-07-03 21:17:51 +00003673 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003674
3675 // Only substitute for the innermost template argument list.
3676 MultiLevelTemplateArgumentList TemplateArgLists;
3677 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3678 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3679 TemplateArgLists.addOuterTemplateArguments(None);
3680
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003681 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003682 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003683 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003684 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003685 QualifierLoc =
3686 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003687 if (!QualifierLoc)
3688 return TemplateName();
3689 }
David Majnemer89189202013-08-28 23:48:32 +00003690
3691 return SemaRef.SubstTemplateName(
3692 QualifierLoc,
3693 Param->getDefaultArgument().getArgument().getAsTemplate(),
3694 Param->getDefaultArgument().getTemplateNameLoc(),
3695 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003696}
3697
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003698/// \brief If the given template parameter has a default template
3699/// argument, substitute into that default template argument and
3700/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003701TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003702Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3703 SourceLocation TemplateLoc,
3704 SourceLocation RAngleLoc,
3705 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003706 SmallVectorImpl<TemplateArgument>
3707 &Converted,
3708 bool &HasDefaultArg) {
3709 HasDefaultArg = false;
3710
3711 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003712 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003713 return TemplateArgumentLoc();
3714
Richard Smithc87b9382013-07-04 01:01:24 +00003715 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003716 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003717 TemplateLoc,
3718 RAngleLoc,
3719 TypeParm,
3720 Converted);
3721 if (DI)
3722 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3723
3724 return TemplateArgumentLoc();
3725 }
3726
3727 if (NonTypeTemplateParmDecl *NonTypeParm
3728 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003729 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003730 return TemplateArgumentLoc();
3731
Richard Smithc87b9382013-07-04 01:01:24 +00003732 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003733 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003734 TemplateLoc,
3735 RAngleLoc,
3736 NonTypeParm,
3737 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003738 if (Arg.isInvalid())
3739 return TemplateArgumentLoc();
3740
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003741 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003742 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3743 }
3744
3745 TemplateTemplateParmDecl *TempTempParm
3746 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003747 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003748 return TemplateArgumentLoc();
3749
Richard Smithc87b9382013-07-04 01:01:24 +00003750 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003751 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003752 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003753 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003754 RAngleLoc,
3755 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003756 Converted,
3757 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003758 if (TName.isNull())
3759 return TemplateArgumentLoc();
3760
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003762 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003763 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3764}
3765
Richard Smith11255ec2017-01-18 19:19:22 +00003766/// Convert a template-argument that we parsed as a type into a template, if
3767/// possible. C++ permits injected-class-names to perform dual service as
3768/// template template arguments and as template type arguments.
3769static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
3770 // Extract and step over any surrounding nested-name-specifier.
3771 NestedNameSpecifierLoc QualLoc;
3772 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
3773 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
3774 return TemplateArgumentLoc();
3775
3776 QualLoc = ETLoc.getQualifierLoc();
3777 TLoc = ETLoc.getNamedTypeLoc();
3778 }
3779
3780 // If this type was written as an injected-class-name, it can be used as a
3781 // template template argument.
3782 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
3783 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
3784 QualLoc, InjLoc.getNameLoc());
3785
3786 // If this type was written as an injected-class-name, it may have been
3787 // converted to a RecordType during instantiation. If the RecordType is
3788 // *not* wrapped in a TemplateSpecializationType and denotes a class
3789 // template specialization, it must have come from an injected-class-name.
3790 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
3791 if (auto *CTSD =
3792 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
3793 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
3794 QualLoc, RecLoc.getNameLoc());
3795
3796 return TemplateArgumentLoc();
3797}
3798
Douglas Gregorda0fb532009-11-11 19:31:23 +00003799/// \brief Check that the given template argument corresponds to the given
3800/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003801///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003802/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003803/// checked.
3804///
Richard Trieu15b66532015-01-24 02:48:32 +00003805/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003806///
3807/// \param Template The template in which the template argument resides.
3808///
3809/// \param TemplateLoc The location of the template name for the template
3810/// whose argument list we're matching.
3811///
3812/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3813/// the template argument list.
3814///
3815/// \param ArgumentPackIndex The index into the argument pack where this
3816/// argument will be placed. Only valid if the parameter is a parameter pack.
3817///
3818/// \param Converted The checked, converted argument will be added to the
3819/// end of this small vector.
3820///
3821/// \param CTAK Describes how we arrived at this particular template argument:
3822/// explicitly written, deduced, etc.
3823///
3824/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003825bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003826 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003827 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003828 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003829 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003830 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003831 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003832 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003833 // Check template type parameters.
3834 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003835 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003836
Douglas Gregoreebed722009-11-11 19:41:09 +00003837 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003838 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003839 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003840 // with the template arguments we've seen thus far. But if the
3841 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003842 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003843 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3844 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003845
Peter Collingbourne01687632010-12-10 17:08:53 +00003846 if (NTTPType->isDependentType() &&
3847 !isa<TemplateTemplateParmDecl>(Template) &&
3848 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003849 // Do substitution on the type of the non-type template parameter.
3850 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003851 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003852 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003853 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003854 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003855
3856 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003857 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003858 NTTPType = SubstType(NTTPType,
3859 MultiLevelTemplateArgumentList(TemplateArgs),
3860 NTTP->getLocation(),
3861 NTTP->getDeclName());
3862 // If that worked, check the non-type template parameter type
3863 // for validity.
3864 if (!NTTPType.isNull())
3865 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3866 NTTP->getLocation());
3867 if (NTTPType.isNull())
3868 return true;
3869 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003870
Douglas Gregorda0fb532009-11-11 19:31:23 +00003871 switch (Arg.getArgument().getKind()) {
3872 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003873 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003874
Douglas Gregorda0fb532009-11-11 19:31:23 +00003875 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003876 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003877 ExprResult Res =
3878 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3879 Result, CTAK);
3880 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003881 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003882
Richard Trieu15b66532015-01-24 02:48:32 +00003883 // If the resulting expression is new, then use it in place of the
3884 // old expression in the template argument.
3885 if (Res.get() != Arg.getArgument().getAsExpr()) {
3886 TemplateArgument TA(Res.get());
3887 Arg = TemplateArgumentLoc(TA, Res.get());
3888 }
3889
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003890 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003891 break;
3892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893
Douglas Gregorda0fb532009-11-11 19:31:23 +00003894 case TemplateArgument::Declaration:
3895 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003896 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003897 // We've already checked this template argument, so just copy
3898 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003899 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003900 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003901
Douglas Gregorda0fb532009-11-11 19:31:23 +00003902 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003903 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003904 // We were given a template template argument. It may not be ill-formed;
3905 // see below.
3906 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003907 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3908 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003909 // We have a template argument such as \c T::template X, which we
3910 // parsed as a template template argument. However, since we now
3911 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003912 // template name into an expression.
3913
3914 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3915 Arg.getTemplateNameLoc());
3916
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003917 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003918 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003919 // FIXME: the template-template arg was a DependentTemplateName,
3920 // so it was provided with a template keyword. However, its source
3921 // location is not stored in the template argument structure.
3922 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003923 ExprResult E = DependentScopeDeclRefExpr::Create(
3924 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3925 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003926
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003927 // If we parsed the template argument as a pack expansion, create a
3928 // pack expansion expression.
3929 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003930 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003931 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003932 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003933 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003934
Douglas Gregorda0fb532009-11-11 19:31:23 +00003935 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003936 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003937 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003938 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003939
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003940 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003941 break;
3942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943
Douglas Gregorda0fb532009-11-11 19:31:23 +00003944 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003945 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003946 // therefore cannot be a non-type template argument.
3947 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3948 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003949
Douglas Gregorda0fb532009-11-11 19:31:23 +00003950 Diag(Param->getLocation(), diag::note_template_param_here);
3951 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003952
Douglas Gregorda0fb532009-11-11 19:31:23 +00003953 case TemplateArgument::Type: {
3954 // We have a non-type template parameter but the template
3955 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003956
Douglas Gregorda0fb532009-11-11 19:31:23 +00003957 // C++ [temp.arg]p2:
3958 // In a template-argument, an ambiguity between a type-id and
3959 // an expression is resolved to a type-id, regardless of the
3960 // form of the corresponding template-parameter.
3961 //
3962 // We warn specifically about this case, since it can be rather
3963 // confusing for users.
3964 QualType T = Arg.getArgument().getAsType();
3965 SourceRange SR = Arg.getSourceRange();
3966 if (T->isFunctionType())
3967 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3968 else
3969 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3970 Diag(Param->getLocation(), diag::note_template_param_here);
3971 return true;
3972 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003973
Douglas Gregorda0fb532009-11-11 19:31:23 +00003974 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003975 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003976 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003977
Douglas Gregorda0fb532009-11-11 19:31:23 +00003978 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003979 }
3980
3981
Douglas Gregorda0fb532009-11-11 19:31:23 +00003982 // Check template template parameters.
3983 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003984
Douglas Gregorda0fb532009-11-11 19:31:23 +00003985 // Substitute into the template parameter list of the template
3986 // template parameter, since previously-supplied template arguments
3987 // may appear within the template template parameter.
3988 {
3989 // Set up a template instantiation context.
3990 LocalInstantiationScope Scope(*this);
3991 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003992 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003993 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003994 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003995 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003996
David Majnemer8b622692016-07-03 21:17:51 +00003997 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003998 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003999 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004000 MultiLevelTemplateArgumentList(TemplateArgs)));
4001 if (!TempParm)
4002 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004003 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004004
Richard Smith11255ec2017-01-18 19:19:22 +00004005 // C++1z [temp.local]p1: (DR1004)
4006 // When [the injected-class-name] is used [...] as a template-argument for
4007 // a template template-parameter [...] it refers to the class template
4008 // itself.
4009 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4010 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4011 Arg.getTypeSourceInfo()->getTypeLoc());
4012 if (!ConvertedArg.getArgument().isNull())
4013 Arg = ConvertedArg;
4014 }
4015
Douglas Gregorda0fb532009-11-11 19:31:23 +00004016 switch (Arg.getArgument().getKind()) {
4017 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004018 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004019
Douglas Gregorda0fb532009-11-11 19:31:23 +00004020 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004021 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00004022 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004023 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004024
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004025 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004026 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004027
Douglas Gregorda0fb532009-11-11 19:31:23 +00004028 case TemplateArgument::Expression:
4029 case TemplateArgument::Type:
4030 // We have a template template parameter but the template
4031 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004032 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004033 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004034 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004035
Douglas Gregorda0fb532009-11-11 19:31:23 +00004036 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004037 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004038 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004039 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004040 case TemplateArgument::NullPtr:
4041 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004042
Douglas Gregorda0fb532009-11-11 19:31:23 +00004043 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004044 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004046
Douglas Gregorda0fb532009-11-11 19:31:23 +00004047 return false;
4048}
4049
Simon Pilgrim6905d222016-12-30 22:55:33 +00004050/// \brief Diagnose an arity mismatch in the
Douglas Gregor8e072612012-02-03 07:34:46 +00004051static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4052 SourceLocation TemplateLoc,
4053 TemplateArgumentListInfo &TemplateArgs) {
4054 TemplateParameterList *Params = Template->getTemplateParameters();
4055 unsigned NumParams = Params->size();
4056 unsigned NumArgs = TemplateArgs.size();
4057
4058 SourceRange Range;
4059 if (NumArgs > NumParams)
Simon Pilgrim6905d222016-12-30 22:55:33 +00004060 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
Douglas Gregor8e072612012-02-03 07:34:46 +00004061 TemplateArgs.getRAngleLoc());
4062 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4063 << (NumArgs > NumParams)
Richard Smith0c062b42017-01-14 02:19:59 +00004064 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
Douglas Gregor8e072612012-02-03 07:34:46 +00004065 << Template << Range;
4066 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4067 << Params->getSourceRange();
4068 return true;
4069}
4070
Richard Smith1fde8ec2012-09-07 02:06:42 +00004071/// \brief Check whether the template parameter is a pack expansion, and if so,
4072/// determine the number of parameters produced by that expansion. For instance:
4073///
4074/// \code
4075/// template<typename ...Ts> struct A {
4076/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4077/// };
4078/// \endcode
4079///
4080/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4081/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004082static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004083 if (NonTypeTemplateParmDecl *NTTP
4084 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4085 if (NTTP->isExpandedParameterPack())
4086 return NTTP->getNumExpansionTypes();
4087 }
4088
4089 if (TemplateTemplateParmDecl *TTP
4090 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4091 if (TTP->isExpandedParameterPack())
4092 return TTP->getNumExpansionTemplateParameters();
4093 }
4094
David Blaikie7a30dc52013-02-21 01:47:18 +00004095 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00004096}
4097
Richard Smith35c1df52015-06-17 20:16:32 +00004098/// Diagnose a missing template argument.
4099template<typename TemplateParmDecl>
4100static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4101 TemplateDecl *TD,
4102 const TemplateParmDecl *D,
4103 TemplateArgumentListInfo &Args) {
4104 // Dig out the most recent declaration of the template parameter; there may be
4105 // declarations of the template that are more recent than TD.
4106 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4107 ->getTemplateParameters()
4108 ->getParam(D->getIndex()));
4109
4110 // If there's a default argument that's not visible, diagnose that we're
4111 // missing a module import.
4112 llvm::SmallVector<Module*, 8> Modules;
4113 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4114 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4115 D->getDefaultArgumentLoc(), Modules,
4116 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00004117 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00004118 return true;
4119 }
4120
4121 // FIXME: If there's a more recent default argument that *is* visible,
4122 // diagnose that it was declared too late.
4123
4124 return diagnoseArityMismatch(S, TD, Loc, Args);
4125}
4126
Douglas Gregord32e0282009-02-09 23:23:08 +00004127/// \brief Check that the given template argument list is well-formed
4128/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00004129bool Sema::CheckTemplateArgumentList(
4130 TemplateDecl *Template, SourceLocation TemplateLoc,
4131 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4132 SmallVectorImpl<TemplateArgument> &Converted,
4133 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00004134 // Make a copy of the template arguments for processing. Only make the
4135 // changes at the end when successful in matching the arguments to the
4136 // template.
4137 TemplateArgumentListInfo NewArgs = TemplateArgs;
4138
Douglas Gregord32e0282009-02-09 23:23:08 +00004139 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00004140
Richard Trieu15b66532015-01-24 02:48:32 +00004141 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00004142
Mike Stump11289f42009-09-09 15:08:12 +00004143 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00004144 // [...] The type and form of each template-argument specified in
4145 // a template-id shall match the type and form specified for the
4146 // corresponding parameter declared by the template in its
4147 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00004148 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004149 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00004150 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00004151 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00004152 for (TemplateParameterList::iterator Param = Params->begin(),
4153 ParamEnd = Params->end();
4154 Param != ParamEnd; /* increment in loop */) {
4155 // If we have an expanded parameter pack, make sure we don't have too
4156 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00004157 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004158 if (*Expansions == ArgumentPack.size()) {
4159 // We're done with this parameter pack. Pack up its arguments and add
4160 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00004161 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00004162 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004163 ArgumentPack.clear();
4164
Richard Smith1fde8ec2012-09-07 02:06:42 +00004165 // This argument is assigned to the next parameter.
4166 ++Param;
4167 continue;
4168 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4169 // Not enough arguments for this parameter pack.
4170 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4171 << false
Richard Smith0c062b42017-01-14 02:19:59 +00004172 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00004173 << Template;
4174 Diag(Template->getLocation(), diag::note_template_decl_here)
4175 << Params->getSourceRange();
4176 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004177 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004179
Richard Smith1fde8ec2012-09-07 02:06:42 +00004180 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00004181 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00004182 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004183 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004184 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00004185 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004186
Richard Smith96d71c32014-11-12 23:38:38 +00004187 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00004188 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00004189 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4190 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00004191 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00004192 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00004193 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00004194 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00004195 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00004196 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00004197 Diag((*Param)->getLocation(), diag::note_template_param_here);
4198 return true;
4199 }
4200
Richard Smith1fde8ec2012-09-07 02:06:42 +00004201 // We're now done with this argument.
4202 ++ArgIdx;
4203
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004204 if ((*Param)->isTemplateParameterPack()) {
4205 // The template parameter was a template parameter pack, so take the
4206 // deduced argument and place it on the argument pack. Note that we
4207 // stay on the same template parameter so that we can deduce more
4208 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004209 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004210 } else {
4211 // Move to the next template parameter.
4212 ++Param;
4213 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004214
Richard Smith96d71c32014-11-12 23:38:38 +00004215 // If we just saw a pack expansion into a non-pack, then directly convert
4216 // the remaining arguments, because we don't know what parameters they'll
4217 // match up with.
4218 if (PackExpansionIntoNonPack) {
4219 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004220 // If we were part way through filling in an expanded parameter pack,
4221 // fall back to just producing individual arguments.
4222 Converted.insert(Converted.end(),
4223 ArgumentPack.begin(), ArgumentPack.end());
4224 ArgumentPack.clear();
4225 }
4226
4227 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00004228 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00004229 ++ArgIdx;
4230 }
4231
Richard Smith1fde8ec2012-09-07 02:06:42 +00004232 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00004233 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004234
Douglas Gregor84d49a22009-11-11 21:54:23 +00004235 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004237
Douglas Gregor2f157c92011-06-03 02:59:40 +00004238 // If we're checking a partial template argument list, we're done.
4239 if (PartialTemplateArgs) {
4240 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00004241 Converted.push_back(
4242 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4243
Richard Smith1fde8ec2012-09-07 02:06:42 +00004244 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00004245 }
4246
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004248 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00004249 if ((*Param)->isTemplateParameterPack()) {
4250 assert(!getExpandedPackSize(*Param) &&
4251 "Should have dealt with this already");
4252
4253 // A non-expanded parameter pack before the end of the parameter list
4254 // only occurs for an ill-formed template parameter list, unless we've
4255 // got a partial argument list for a function template, so just bail out.
4256 if (Param + 1 != ParamEnd)
4257 return true;
4258
Benjamin Kramercce63472015-08-05 09:40:22 +00004259 Converted.push_back(
4260 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004261 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00004262
4263 ++Param;
4264 continue;
4265 }
4266
Douglas Gregor8e072612012-02-03 07:34:46 +00004267 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00004268 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004269
Douglas Gregor84d49a22009-11-11 21:54:23 +00004270 // Retrieve the default template argument from the template
4271 // parameter. For each kind of template parameter, we substitute the
4272 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004273 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004274 // the default argument.
4275 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004276 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004277 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4278 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004279
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004280 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004281 Template,
4282 TemplateLoc,
4283 RAngleLoc,
4284 TTP,
4285 Converted);
4286 if (!ArgType)
4287 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004288
Douglas Gregor84d49a22009-11-11 21:54:23 +00004289 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4290 ArgType);
4291 } else if (NonTypeTemplateParmDecl *NTTP
4292 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004293 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004294 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4295 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004296
John McCalldadc5752010-08-24 06:29:42 +00004297 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004298 TemplateLoc,
4299 RAngleLoc,
4300 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004301 Converted);
4302 if (E.isInvalid())
4303 return true;
4304
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004305 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004306 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4307 } else {
4308 TemplateTemplateParmDecl *TempParm
4309 = cast<TemplateTemplateParmDecl>(*Param);
4310
Richard Smith95d83952015-06-10 20:36:34 +00004311 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004312 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4313 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004314
Douglas Gregordf846d12011-03-02 18:46:51 +00004315 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004316 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004317 TemplateLoc,
4318 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004319 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004320 Converted,
4321 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004322 if (Name.isNull())
4323 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004324
Douglas Gregor9d802122011-03-02 17:09:35 +00004325 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4326 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004328
Douglas Gregor84d49a22009-11-11 21:54:23 +00004329 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00004330 // the default template argument. We're not actually instantiating a
4331 // template here, we just create this object to put a note into the
4332 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004333 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4334 SourceRange(TemplateLoc, RAngleLoc));
4335 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004336 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004337
Douglas Gregor84d49a22009-11-11 21:54:23 +00004338 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004339 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004340 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004341 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004342
Richard Trieu15b66532015-01-24 02:48:32 +00004343 // Core issue 150 (assumed resolution): if this is a template template
4344 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004345 // template definition.
4346 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004347 NewArgs.addArgument(Arg);
4348
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004349 // Move to the next template parameter and argument.
4350 ++Param;
4351 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004352 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004353
Richard Smith07f79912014-06-06 16:00:50 +00004354 // If we're performing a partial argument substitution, allow any trailing
4355 // pack expansions; they might be empty. This can happen even if
4356 // PartialTemplateArgs is false (the list of arguments is complete but
4357 // still dependent).
4358 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4359 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004360 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4361 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004362 }
4363
Douglas Gregor8e072612012-02-03 07:34:46 +00004364 // If we have any leftover arguments, then there were too many arguments.
4365 // Complain and fail.
4366 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004367 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4368
4369 // No problems found with the new argument list, propagate changes back
4370 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00004371 if (UpdateArgsWithConversions)
4372 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004373
Richard Smith1fde8ec2012-09-07 02:06:42 +00004374 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004375}
4376
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004377namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004378 class UnnamedLocalNoLinkageFinder
4379 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004380 {
4381 Sema &S;
4382 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004384 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004385
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004386 public:
4387 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4388
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004389 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00004390 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004391 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004392
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004393#define TYPE(Class, Parent) \
4394 bool Visit##Class##Type(const Class##Type *);
4395#define ABSTRACT_TYPE(Class, Parent) \
4396 bool Visit##Class##Type(const Class##Type *) { return false; }
4397#define NON_CANONICAL_TYPE(Class, Parent) \
4398 bool Visit##Class##Type(const Class##Type *) { return false; }
4399#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004400
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004401 bool VisitTagDecl(const TagDecl *Tag);
4402 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4403 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004404} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004405
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004406bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004407 return false;
4408}
4409
4410bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4411 return Visit(T->getElementType());
4412}
4413
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004414bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004415 return Visit(T->getPointeeType());
4416}
4417
4418bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004420 return Visit(T->getPointeeType());
4421}
4422
4423bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004424 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004425 return Visit(T->getPointeeType());
4426}
4427
4428bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004429 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004430 return Visit(T->getPointeeType());
4431}
4432
4433bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004434 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004435 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4436}
4437
4438bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004440 return Visit(T->getElementType());
4441}
4442
4443bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004445 return Visit(T->getElementType());
4446}
4447
4448bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004450 return Visit(T->getElementType());
4451}
4452
4453bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004454 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004455 return Visit(T->getElementType());
4456}
4457
4458bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004459 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004460 return Visit(T->getElementType());
4461}
4462
4463bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4464 return Visit(T->getElementType());
4465}
4466
4467bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4468 return Visit(T->getElementType());
4469}
4470
4471bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4472 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004473 for (const auto &A : T->param_types()) {
4474 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004475 return true;
4476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004477
Alp Toker314cc812014-01-25 16:55:45 +00004478 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004479}
4480
4481bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4482 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004483 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004484}
4485
4486bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4487 const UnresolvedUsingType*) {
4488 return false;
4489}
4490
4491bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4492 return false;
4493}
4494
4495bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4496 return Visit(T->getUnderlyingType());
4497}
4498
4499bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4500 return false;
4501}
4502
Alexis Hunte852b102011-05-24 22:41:36 +00004503bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4504 const UnaryTransformType*) {
4505 return false;
4506}
4507
Richard Smith30482bc2011-02-20 03:19:35 +00004508bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4509 return Visit(T->getDeducedType());
4510}
4511
Richard Smith600b5262017-01-26 20:40:47 +00004512bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
4513 const DeducedTemplateSpecializationType *T) {
4514 return Visit(T->getDeducedType());
4515}
4516
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004517bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4518 return VisitTagDecl(T->getDecl());
4519}
4520
4521bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4522 return VisitTagDecl(T->getDecl());
4523}
4524
4525bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4526 const TemplateTypeParmType*) {
4527 return false;
4528}
4529
Douglas Gregorada4b792011-01-14 02:55:32 +00004530bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4531 const SubstTemplateTypeParmPackType *) {
4532 return false;
4533}
4534
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004535bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4536 const TemplateSpecializationType*) {
4537 return false;
4538}
4539
4540bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4541 const InjectedClassNameType* T) {
4542 return VisitTagDecl(T->getDecl());
4543}
4544
4545bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4546 const DependentNameType* T) {
4547 return VisitNestedNameSpecifier(T->getQualifier());
4548}
4549
4550bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4551 const DependentTemplateSpecializationType* T) {
4552 return VisitNestedNameSpecifier(T->getQualifier());
4553}
4554
Douglas Gregord2fa7662010-12-20 02:24:11 +00004555bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4556 const PackExpansionType* T) {
4557 return Visit(T->getPattern());
4558}
4559
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004560bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4561 return false;
4562}
4563
4564bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4565 const ObjCInterfaceType *) {
4566 return false;
4567}
4568
4569bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4570 const ObjCObjectPointerType *) {
4571 return false;
4572}
4573
Eli Friedman0dfb8892011-10-06 23:00:33 +00004574bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4575 return Visit(T->getValueType());
4576}
4577
Xiuli Pan9c14e282016-01-09 12:53:17 +00004578bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4579 return false;
4580}
4581
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004582bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4583 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004584 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004585 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004586 diag::warn_cxx98_compat_template_arg_local_type :
4587 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004588 << S.Context.getTypeDeclType(Tag) << SR;
4589 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004590 }
4591
John McCall5ea95772013-03-09 00:54:27 +00004592 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004593 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004594 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004595 diag::warn_cxx98_compat_template_arg_unnamed_type :
4596 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004597 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4598 return true;
4599 }
4600
4601 return false;
4602}
4603
4604bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4605 NestedNameSpecifier *NNS) {
4606 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4607 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004608
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004609 switch (NNS->getKind()) {
4610 case NestedNameSpecifier::Identifier:
4611 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004612 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004613 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004614 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004615 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004616
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004617 case NestedNameSpecifier::TypeSpec:
4618 case NestedNameSpecifier::TypeSpecWithTemplate:
4619 return Visit(QualType(NNS->getAsType(), 0));
4620 }
David Blaikie8a40f702012-01-17 06:56:22 +00004621 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004622}
4623
Douglas Gregord32e0282009-02-09 23:23:08 +00004624/// \brief Check a template argument against its corresponding
4625/// template type parameter.
4626///
4627/// This routine implements the semantics of C++ [temp.arg.type]. It
4628/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004629bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004630 TypeSourceInfo *ArgInfo) {
4631 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004632 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004633 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004634
4635 if (Arg->isVariablyModifiedType()) {
4636 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004637 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004638 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004639 }
4640
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004641 // C++03 [temp.arg.type]p2:
4642 // A local type, a type with no linkage, an unnamed type or a type
4643 // compounded from any of these types shall not be used as a
4644 // template-argument for a template type-parameter.
4645 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004646 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004647 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00004648 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004649 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4650 (void)Finder.Visit(Context.getCanonicalType(Arg));
4651 }
4652
Douglas Gregord32e0282009-02-09 23:23:08 +00004653 return false;
4654}
4655
Douglas Gregor20fdef32012-04-10 17:08:25 +00004656enum NullPointerValueKind {
4657 NPV_NotNullPointer,
4658 NPV_NullPointer,
4659 NPV_Error
4660};
4661
4662/// \brief Determine whether the given template argument is a null pointer
4663/// value of the appropriate type.
4664static NullPointerValueKind
4665isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4666 QualType ParamType, Expr *Arg) {
4667 if (Arg->isValueDependent() || Arg->isTypeDependent())
4668 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004669
Richard Smithdb0ac552015-12-18 22:40:25 +00004670 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004671 llvm_unreachable(
4672 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004673
David Majnemer5c734ad2014-08-14 00:49:23 +00004674 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004675 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00004676
Douglas Gregor20fdef32012-04-10 17:08:25 +00004677 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004678 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4679 if (ArgRV.isInvalid())
4680 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004681 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00004682
Douglas Gregor20fdef32012-04-10 17:08:25 +00004683 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004684 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004685 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004686 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004687 EvalResult.HasSideEffects) {
4688 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00004689
Douglas Gregor350880c2012-04-10 19:03:30 +00004690 // If our only note is the usual "invalid subexpression" note, just point
4691 // the caret at its location rather than producing an essentially
4692 // redundant note.
4693 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4694 diag::note_invalid_subexpr_in_const_expr) {
4695 DiagLoc = Notes[0].first;
4696 Notes.clear();
4697 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004698
Douglas Gregor350880c2012-04-10 19:03:30 +00004699 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4700 << Arg->getType() << Arg->getSourceRange();
4701 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4702 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004703
Douglas Gregor350880c2012-04-10 19:03:30 +00004704 S.Diag(Param->getLocation(), diag::note_template_param_here);
4705 return NPV_Error;
4706 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004707
Douglas Gregor20fdef32012-04-10 17:08:25 +00004708 // C++11 [temp.arg.nontype]p1:
4709 // - an address constant expression of type std::nullptr_t
4710 if (Arg->getType()->isNullPtrType())
4711 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00004712
Douglas Gregor20fdef32012-04-10 17:08:25 +00004713 // - a constant expression that evaluates to a null pointer value (4.10); or
4714 // - a constant expression that evaluates to a null member pointer value
4715 // (4.11); or
4716 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4717 (EvalResult.Val.isMemberPointer() &&
4718 !EvalResult.Val.getMemberPointerDecl())) {
4719 // If our expression has an appropriate type, we've succeeded.
4720 bool ObjCLifetimeConversion;
4721 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4722 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4723 ObjCLifetimeConversion))
4724 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00004725
Douglas Gregor20fdef32012-04-10 17:08:25 +00004726 // The types didn't match, but we know we got a null pointer; complain,
4727 // then recover as if the types were correct.
4728 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4729 << Arg->getType() << ParamType << Arg->getSourceRange();
4730 S.Diag(Param->getLocation(), diag::note_template_param_here);
4731 return NPV_NullPointer;
4732 }
4733
4734 // If we don't have a null pointer value, but we do have a NULL pointer
4735 // constant, suggest a cast to the appropriate type.
4736 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4737 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4738 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004739 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4740 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4741 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004742 S.Diag(Param->getLocation(), diag::note_template_param_here);
4743 return NPV_NullPointer;
4744 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004745
Douglas Gregor20fdef32012-04-10 17:08:25 +00004746 // FIXME: If we ever want to support general, address-constant expressions
4747 // as non-type template arguments, we should return the ExprResult here to
4748 // be interpreted by the caller.
4749 return NPV_NotNullPointer;
4750}
4751
David Majnemer61c39a12013-08-23 05:39:39 +00004752/// \brief Checks whether the given template argument is compatible with its
4753/// template parameter.
4754static bool CheckTemplateArgumentIsCompatibleWithParameter(
4755 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4756 Expr *Arg, QualType ArgType) {
4757 bool ObjCLifetimeConversion;
4758 if (ParamType->isPointerType() &&
4759 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4760 S.IsQualificationConversion(ArgType, ParamType, false,
4761 ObjCLifetimeConversion)) {
4762 // For pointer-to-object types, qualification conversions are
4763 // permitted.
4764 } else {
4765 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4766 if (!ParamRef->getPointeeType()->isFunctionType()) {
4767 // C++ [temp.arg.nontype]p5b3:
4768 // For a non-type template-parameter of type reference to
4769 // object, no conversions apply. The type referred to by the
4770 // reference may be more cv-qualified than the (otherwise
4771 // identical) type of the template- argument. The
4772 // template-parameter is bound directly to the
4773 // template-argument, which shall be an lvalue.
4774
4775 // FIXME: Other qualifiers?
4776 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4777 unsigned ArgQuals = ArgType.getCVRQualifiers();
4778
4779 if ((ParamQuals | ArgQuals) != ParamQuals) {
4780 S.Diag(Arg->getLocStart(),
4781 diag::err_template_arg_ref_bind_ignores_quals)
4782 << ParamType << Arg->getType() << Arg->getSourceRange();
4783 S.Diag(Param->getLocation(), diag::note_template_param_here);
4784 return true;
4785 }
4786 }
4787 }
4788
4789 // At this point, the template argument refers to an object or
4790 // function with external linkage. We now need to check whether the
4791 // argument and parameter types are compatible.
4792 if (!S.Context.hasSameUnqualifiedType(ArgType,
4793 ParamType.getNonReferenceType())) {
4794 // We can't perform this conversion or binding.
4795 if (ParamType->isReferenceType())
4796 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4797 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4798 else
4799 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4800 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4801 S.Diag(Param->getLocation(), diag::note_template_param_here);
4802 return true;
4803 }
4804 }
4805
4806 return false;
4807}
4808
Douglas Gregorccb07762009-02-11 19:52:55 +00004809/// \brief Checks whether the given template argument is the address
4810/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004811static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004812CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4813 NonTypeTemplateParmDecl *Param,
4814 QualType ParamType,
4815 Expr *ArgIn,
4816 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004817 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004818 Expr *Arg = ArgIn;
4819 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004820
Douglas Gregorb242683d2010-04-01 18:32:35 +00004821 bool AddressTaken = false;
4822 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004823 if (S.getLangOpts().MicrosoftExt) {
4824 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4825 // dereference and address-of operators.
4826 Arg = Arg->IgnoreParenCasts();
4827
4828 bool ExtWarnMSTemplateArg = false;
4829 UnaryOperatorKind FirstOpKind;
4830 SourceLocation FirstOpLoc;
4831 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4832 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4833 if (UnOpKind == UO_Deref)
4834 ExtWarnMSTemplateArg = true;
4835 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4836 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4837 if (!AddrOpLoc.isValid()) {
4838 FirstOpKind = UnOpKind;
4839 FirstOpLoc = UnOp->getOperatorLoc();
4840 }
4841 } else
4842 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004843 }
David Majnemer61c39a12013-08-23 05:39:39 +00004844 if (FirstOpLoc.isValid()) {
4845 if (ExtWarnMSTemplateArg)
4846 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4847 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004848
David Majnemer61c39a12013-08-23 05:39:39 +00004849 if (FirstOpKind == UO_AddrOf)
4850 AddressTaken = true;
4851 else if (Arg->getType()->isPointerType()) {
4852 // We cannot let pointers get dereferenced here, that is obviously not a
4853 // constant expression.
4854 assert(FirstOpKind == UO_Deref);
4855 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4856 << Arg->getSourceRange();
4857 }
4858 }
4859 } else {
4860 // See through any implicit casts we added to fix the type.
4861 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004862
David Majnemer61c39a12013-08-23 05:39:39 +00004863 // C++ [temp.arg.nontype]p1:
4864 //
4865 // A template-argument for a non-type, non-template
4866 // template-parameter shall be one of: [...]
4867 //
4868 // -- the address of an object or function with external
4869 // linkage, including function templates and function
4870 // template-ids but excluding non-static class members,
4871 // expressed as & id-expression where the & is optional if
4872 // the name refers to a function or array, or if the
4873 // corresponding template-parameter is a reference; or
4874
4875 // In C++98/03 mode, give an extension warning on any extra parentheses.
4876 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4877 bool ExtraParens = false;
4878 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4879 if (!Invalid && !ExtraParens) {
4880 S.Diag(Arg->getLocStart(),
4881 S.getLangOpts().CPlusPlus11
4882 ? diag::warn_cxx98_compat_template_arg_extra_parens
4883 : diag::ext_template_arg_extra_parens)
4884 << Arg->getSourceRange();
4885 ExtraParens = true;
4886 }
4887
4888 Arg = Parens->getSubExpr();
4889 }
4890
4891 while (SubstNonTypeTemplateParmExpr *subst =
4892 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4893 Arg = subst->getReplacement()->IgnoreImpCasts();
4894
4895 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4896 if (UnOp->getOpcode() == UO_AddrOf) {
4897 Arg = UnOp->getSubExpr();
4898 AddressTaken = true;
4899 AddrOpLoc = UnOp->getOperatorLoc();
4900 }
4901 }
4902
4903 while (SubstNonTypeTemplateParmExpr *subst =
4904 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4905 Arg = subst->getReplacement()->IgnoreImpCasts();
4906 }
John McCall7c454bb2011-07-15 05:09:51 +00004907
David Majnemer07910d62014-06-26 07:48:46 +00004908 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4909 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4910
4911 // If our parameter has pointer type, check for a null template value.
4912 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4913 NullPointerValueKind NPV;
4914 // dllimport'd entities aren't constant but are available inside of template
4915 // arguments.
4916 if (Entity && Entity->hasAttr<DLLImportAttr>())
4917 NPV = NPV_NotNullPointer;
4918 else
4919 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4920 switch (NPV) {
4921 case NPV_NullPointer:
4922 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004923 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4924 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004925 return false;
4926
4927 case NPV_Error:
4928 return true;
4929
4930 case NPV_NotNullPointer:
4931 break;
4932 }
4933 }
4934
Chandler Carruth724a8a12010-01-31 10:01:20 +00004935 // Stop checking the precise nature of the argument if it is value dependent,
4936 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004937 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004938 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004939 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004940 }
David Majnemer61c39a12013-08-23 05:39:39 +00004941
4942 if (isa<CXXUuidofExpr>(Arg)) {
4943 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4944 ArgIn, Arg, ArgType))
4945 return true;
4946
4947 Converted = TemplateArgument(ArgIn);
4948 return false;
4949 }
4950
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004951 if (!DRE) {
4952 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4953 << Arg->getSourceRange();
4954 S.Diag(Param->getLocation(), diag::note_template_param_here);
4955 return true;
4956 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004957
Douglas Gregorccb07762009-02-11 19:52:55 +00004958 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004959 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004960 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004961 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004962 S.Diag(Param->getLocation(), diag::note_template_param_here);
4963 return true;
4964 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004965
4966 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004967 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004968 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004969 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004970 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004971 S.Diag(Param->getLocation(), diag::note_template_param_here);
4972 return true;
4973 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004974 }
Mike Stump11289f42009-09-09 15:08:12 +00004975
Richard Smith9380e0e2012-04-04 21:11:30 +00004976 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4977 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004978
Richard Smith9380e0e2012-04-04 21:11:30 +00004979 // A non-type template argument must refer to an object or function.
4980 if (!Func && !Var) {
4981 // We found something, but we don't know specifically what it is.
4982 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4983 << Arg->getSourceRange();
4984 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4985 return true;
4986 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004987
Richard Smith9380e0e2012-04-04 21:11:30 +00004988 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004989 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004990 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004991 diag::warn_cxx98_compat_template_arg_object_internal :
4992 diag::ext_template_arg_object_internal)
4993 << !Func << Entity << Arg->getSourceRange();
4994 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4995 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004996 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004997 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4998 << !Func << Entity << Arg->getSourceRange();
4999 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5000 << !Func;
5001 return true;
5002 }
5003
5004 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005005 // If the template parameter has pointer type, the function decays.
5006 if (ParamType->isPointerType() && !AddressTaken)
5007 ArgType = S.Context.getPointerType(Func->getType());
5008 else if (AddressTaken && ParamType->isReferenceType()) {
5009 // If we originally had an address-of operator, but the
5010 // parameter has reference type, complain and (if things look
5011 // like they will work) drop the address-of operator.
5012 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5013 ParamType.getNonReferenceType())) {
5014 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5015 << ParamType;
5016 S.Diag(Param->getLocation(), diag::note_template_param_here);
5017 return true;
5018 }
5019
5020 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5021 << ParamType
5022 << FixItHint::CreateRemoval(AddrOpLoc);
5023 S.Diag(Param->getLocation(), diag::note_template_param_here);
5024
5025 ArgType = Func->getType();
5026 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005027 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005028 // A value of reference type is not an object.
5029 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005030 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00005031 diag::err_template_arg_reference_var)
5032 << Var->getType() << Arg->getSourceRange();
5033 S.Diag(Param->getLocation(), diag::note_template_param_here);
5034 return true;
5035 }
5036
Richard Smith9380e0e2012-04-04 21:11:30 +00005037 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005038 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005039 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5040 << Arg->getSourceRange();
5041 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5042 return true;
5043 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005044
5045 // If the template parameter has pointer type, we must have taken
5046 // the address of this object.
5047 if (ParamType->isReferenceType()) {
5048 if (AddressTaken) {
5049 // If we originally had an address-of operator, but the
5050 // parameter has reference type, complain and (if things look
5051 // like they will work) drop the address-of operator.
5052 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5053 ParamType.getNonReferenceType())) {
5054 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5055 << ParamType;
5056 S.Diag(Param->getLocation(), diag::note_template_param_here);
5057 return true;
5058 }
5059
5060 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5061 << ParamType
5062 << FixItHint::CreateRemoval(AddrOpLoc);
5063 S.Diag(Param->getLocation(), diag::note_template_param_here);
5064
5065 ArgType = Var->getType();
5066 }
5067 } else if (!AddressTaken && ParamType->isPointerType()) {
5068 if (Var->getType()->isArrayType()) {
5069 // Array-to-pointer decay.
5070 ArgType = S.Context.getArrayDecayedType(Var->getType());
5071 } else {
5072 // If the template parameter has pointer type but the address of
5073 // this object was not taken, complain and (possibly) recover by
5074 // taking the address of the entity.
5075 ArgType = S.Context.getPointerType(Var->getType());
5076 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5077 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5078 << ParamType;
5079 S.Diag(Param->getLocation(), diag::note_template_param_here);
5080 return true;
5081 }
5082
5083 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5084 << ParamType
5085 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5086
5087 S.Diag(Param->getLocation(), diag::note_template_param_here);
5088 }
5089 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005090 }
Mike Stump11289f42009-09-09 15:08:12 +00005091
David Majnemer61c39a12013-08-23 05:39:39 +00005092 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5093 Arg, ArgType))
5094 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005095
5096 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00005097 Converted =
5098 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00005099 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00005100 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005101}
5102
5103/// \brief Checks whether the given template argument is a pointer to
5104/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005105static bool CheckTemplateArgumentPointerToMember(Sema &S,
5106 NonTypeTemplateParmDecl *Param,
5107 QualType ParamType,
5108 Expr *&ResultArg,
5109 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005110 bool Invalid = false;
5111
Douglas Gregor20fdef32012-04-10 17:08:25 +00005112 // Check for a null pointer value.
5113 Expr *Arg = ResultArg;
5114 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
5115 case NPV_Error:
5116 return true;
5117 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005118 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005119 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5120 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00005121 return false;
5122 case NPV_NotNullPointer:
5123 break;
5124 }
5125
5126 bool ObjCLifetimeConversion;
5127 if (S.IsQualificationConversion(Arg->getType(),
5128 ParamType.getNonReferenceType(),
5129 false, ObjCLifetimeConversion)) {
5130 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005131 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00005132 ResultArg = Arg;
5133 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
5134 ParamType.getNonReferenceType())) {
5135 // We can't perform this conversion.
5136 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5137 << Arg->getType() << ParamType << Arg->getSourceRange();
5138 S.Diag(Param->getLocation(), diag::note_template_param_here);
5139 return true;
5140 }
5141
Douglas Gregorccb07762009-02-11 19:52:55 +00005142 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00005143 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00005144 Arg = Cast->getSubExpr();
5145
5146 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005147 //
Douglas Gregorccb07762009-02-11 19:52:55 +00005148 // A template-argument for a non-type, non-template
5149 // template-parameter shall be one of: [...]
5150 //
5151 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00005152 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00005153
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005154 // In C++98/03 mode, give an extension warning on any extra parentheses.
5155 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5156 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005157 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005158 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005159 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005160 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00005161 diag::warn_cxx98_compat_template_arg_extra_parens :
5162 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00005163 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005164 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00005165 }
5166
5167 Arg = Parens->getSubExpr();
5168 }
5169
John McCall7c454bb2011-07-15 05:09:51 +00005170 while (SubstNonTypeTemplateParmExpr *subst =
5171 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5172 Arg = subst->getReplacement()->IgnoreImpCasts();
5173
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005174 // A pointer-to-member constant written &Class::member.
5175 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00005176 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005177 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5178 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005179 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005180 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005181 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005182 // A constant of pointer-to-member type.
5183 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5184 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5185 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00005186 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005187 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005188 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005189 } else {
5190 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005191 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005192 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005193 return Invalid;
5194 }
5195 }
5196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005197
Craig Topperc3ec1492014-05-26 06:22:03 +00005198 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005200
Douglas Gregorccb07762009-02-11 19:52:55 +00005201 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005202 return S.Diag(Arg->getLocStart(),
5203 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00005204 << Arg->getSourceRange();
5205
David Majnemer3ac84e62013-10-22 21:56:38 +00005206 if (isa<FieldDecl>(DRE->getDecl()) ||
5207 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5208 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005209 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00005210 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00005211 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5212 "Only non-static member pointers can make it here");
5213
5214 // Okay: this is the address of a non-static member, and therefore
5215 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00005216 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005217 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005218 } else {
5219 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005220 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005221 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005222 return Invalid;
5223 }
5224
5225 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005226 S.Diag(Arg->getLocStart(),
5227 diag::err_template_arg_not_pointer_to_member_form)
5228 << Arg->getSourceRange();
5229 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00005230 return true;
5231}
5232
Douglas Gregord32e0282009-02-09 23:23:08 +00005233/// \brief Check a template argument against its corresponding
5234/// non-type template parameter.
5235///
Douglas Gregor463421d2009-03-03 04:44:36 +00005236/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00005237/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00005238/// returns the converted template argument. \p ParamType is the
5239/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00005240ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00005241 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00005242 TemplateArgument &Converted,
5243 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005244 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00005245
Richard Smith5f274382016-09-28 23:55:27 +00005246 // If the parameter type somehow involves auto, deduce the type now.
5247 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
Richard Smith87d263e2016-12-25 08:05:23 +00005248 // When checking a deduced template argument, deduce from its type even if
5249 // the type is dependent, in order to check the types of non-type template
5250 // arguments line up properly in partial ordering.
5251 Optional<unsigned> Depth;
5252 if (CTAK != CTAK_Specified)
5253 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00005254 if (DeduceAutoType(
5255 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00005256 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00005257 Diag(Arg->getExprLoc(),
5258 diag::err_non_type_template_parm_type_deduction_failure)
5259 << Param->getDeclName() << Param->getType() << Arg->getType()
5260 << Arg->getSourceRange();
5261 Diag(Param->getLocation(), diag::note_template_param_here);
5262 return ExprError();
5263 }
5264 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5265 // an error. The error message normally references the parameter
5266 // declaration, but here we'll pass the argument location because that's
5267 // where the parameter type is deduced.
5268 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5269 if (ParamType.isNull()) {
5270 Diag(Param->getLocation(), diag::note_template_param_here);
5271 return ExprError();
5272 }
5273 }
5274
Richard Smithd663fdd2014-12-17 20:42:37 +00005275 // We should have already dropped all cv-qualifiers by now.
5276 assert(!ParamType.hasQualifiers() &&
5277 "non-type template parameter type cannot be qualified");
5278
5279 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00005280 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00005281 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00005282 // FIXME: If either type is dependent, we skip the check. This isn't
5283 // correct, since during deduction we're supposed to have replaced each
5284 // template parameter with some unique (non-dependent) placeholder.
5285 // FIXME: If the argument type contains 'auto', we carry on and fail the
5286 // type check in order to force specific types to be more specialized than
5287 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5288 // work.
5289 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5290 !Arg->getType()->getContainedAutoType()) {
5291 Converted = TemplateArgument(Arg);
5292 return Arg;
5293 }
5294 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5295 // we should actually be checking the type of the template argument in P,
5296 // not the type of the template argument deduced from A, against the
5297 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00005298 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00005299 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00005300 << ParamType.getUnqualifiedType();
5301 Diag(Param->getLocation(), diag::note_template_param_here);
5302 return ExprError();
5303 }
5304
Richard Smith87d263e2016-12-25 08:05:23 +00005305 // If either the parameter has a dependent type or the argument is
5306 // type-dependent, there's nothing we can check now.
5307 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5308 // FIXME: Produce a cloned, canonical expression?
5309 Converted = TemplateArgument(Arg);
5310 return Arg;
5311 }
5312
Richard Smithe5945872017-01-06 22:52:53 +00005313 // The initialization of the parameter from the argument is
5314 // a constant-evaluated context.
5315 EnterExpressionEvaluationContext ConstantEvaluated(*this,
5316 Sema::ConstantEvaluated);
5317
Richard Smith410cc892014-11-26 03:26:53 +00005318 if (getLangOpts().CPlusPlus1z) {
Richard Smith410cc892014-11-26 03:26:53 +00005319 // C++1z [temp.arg.nontype]p1:
5320 // A template-argument for a non-type template parameter shall be
5321 // a converted constant expression of the type of the template-parameter.
5322 APValue Value;
5323 ExprResult ArgResult = CheckConvertedConstantExpression(
5324 Arg, ParamType, Value, CCEK_TemplateArg);
5325 if (ArgResult.isInvalid())
5326 return ExprError();
5327
Richard Smith52e624f2016-12-21 21:42:57 +00005328 // For a value-dependent argument, CheckConvertedConstantExpression is
5329 // permitted (and expected) to be unable to determine a value.
5330 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00005331 Converted = TemplateArgument(ArgResult.get());
5332 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00005333 }
5334
Richard Smithd663fdd2014-12-17 20:42:37 +00005335 QualType CanonParamType = Context.getCanonicalType(ParamType);
5336
Richard Smith410cc892014-11-26 03:26:53 +00005337 // Convert the APValue to a TemplateArgument.
5338 switch (Value.getKind()) {
5339 case APValue::Uninitialized:
5340 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005341 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005342 break;
5343 case APValue::Int:
5344 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005345 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005346 break;
5347 case APValue::MemberPointer: {
5348 assert(ParamType->isMemberPointerType());
5349
5350 // FIXME: We need TemplateArgument representation and mangling for these.
5351 if (!Value.getMemberPointerPath().empty()) {
5352 Diag(Arg->getLocStart(),
5353 diag::err_template_arg_member_ptr_base_derived_not_supported)
5354 << Value.getMemberPointerDecl() << ParamType
5355 << Arg->getSourceRange();
5356 return ExprError();
5357 }
5358
5359 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005360 Converted = VD ? TemplateArgument(VD, CanonParamType)
5361 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005362 break;
5363 }
5364 case APValue::LValue: {
5365 // For a non-type template-parameter of pointer or reference type,
5366 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00005367 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5368 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00005369 // -- a temporary object
5370 // -- a string literal
5371 // -- the result of a typeid expression, or
5372 // -- a predefind __func__ variable
5373 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5374 if (isa<CXXUuidofExpr>(E)) {
5375 Converted = TemplateArgument(const_cast<Expr*>(E));
5376 break;
5377 }
5378 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5379 << Arg->getSourceRange();
5380 return ExprError();
5381 }
5382 auto *VD = const_cast<ValueDecl *>(
5383 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5384 // -- a subobject
5385 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5386 VD && VD->getType()->isArrayType() &&
5387 Value.getLValuePath()[0].ArrayIndex == 0 &&
5388 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5389 // Per defect report (no number yet):
5390 // ... other than a pointer to the first element of a complete array
5391 // object.
5392 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5393 Value.isLValueOnePastTheEnd()) {
5394 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5395 << Value.getAsString(Context, ParamType);
5396 return ExprError();
5397 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005398 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005399 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005400 assert((!VD || !ParamType->isNullPtrType()) &&
5401 "non-null value of type nullptr_t?");
5402 Converted = VD ? TemplateArgument(VD, CanonParamType)
5403 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005404 break;
5405 }
5406 case APValue::AddrLabelDiff:
5407 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5408 case APValue::Float:
5409 case APValue::ComplexInt:
5410 case APValue::ComplexFloat:
5411 case APValue::Vector:
5412 case APValue::Array:
5413 case APValue::Struct:
5414 case APValue::Union:
5415 llvm_unreachable("invalid kind for template argument");
5416 }
5417
5418 return ArgResult.get();
5419 }
5420
Douglas Gregor86560402009-02-10 23:36:10 +00005421 // C++ [temp.arg.nontype]p5:
5422 // The following conversions are performed on each expression used
5423 // as a non-type template-argument. If a non-type
5424 // template-argument cannot be converted to the type of the
5425 // corresponding template-parameter then the program is
5426 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005427 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005428 // C++11:
5429 // -- for a non-type template-parameter of integral or
5430 // enumeration type, conversions permitted in a converted
5431 // constant expression are applied.
5432 //
5433 // C++98:
5434 // -- for a non-type template-parameter of integral or
5435 // enumeration type, integral promotions (4.5) and integral
5436 // conversions (4.7) are applied.
5437
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005438 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005439 // C++ [temp.arg.nontype]p1:
5440 // A template-argument for a non-type, non-template template-parameter
5441 // shall be one of:
5442 //
5443 // -- for a non-type template-parameter of integral or enumeration
5444 // type, a converted constant expression of the type of the
5445 // template-parameter; or
5446 llvm::APSInt Value;
5447 ExprResult ArgResult =
5448 CheckConvertedConstantExpression(Arg, ParamType, Value,
5449 CCEK_TemplateArg);
5450 if (ArgResult.isInvalid())
5451 return ExprError();
5452
Richard Smith01bfa682016-12-27 02:02:09 +00005453 // We can't check arbitrary value-dependent arguments.
5454 if (ArgResult.get()->isValueDependent()) {
5455 Converted = TemplateArgument(ArgResult.get());
5456 return ArgResult;
5457 }
5458
Richard Smithf8379a02012-01-18 23:55:52 +00005459 // Widen the argument value to sizeof(parameter type). This is almost
5460 // always a no-op, except when the parameter type is bool. In
5461 // that case, this may extend the argument from 1 bit to 8 bits.
5462 QualType IntegerType = ParamType;
5463 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5464 IntegerType = Enum->getDecl()->getIntegerType();
5465 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5466
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005467 Converted = TemplateArgument(Context, Value,
5468 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005469 return ArgResult;
5470 }
5471
Richard Smith08b12f12011-10-27 22:11:44 +00005472 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5473 if (ArgResult.isInvalid())
5474 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005475 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005476
5477 QualType ArgType = Arg->getType();
5478
Douglas Gregor86560402009-02-10 23:36:10 +00005479 // C++ [temp.arg.nontype]p1:
5480 // A template-argument for a non-type, non-template
5481 // template-parameter shall be one of:
5482 //
5483 // -- an integral constant-expression of integral or enumeration
5484 // type; or
5485 // -- the name of a non-type template-parameter; or
5486 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005487 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005488 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005489 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005490 diag::err_template_arg_not_integral_or_enumeral)
5491 << ArgType << Arg->getSourceRange();
5492 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005493 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005494 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005495 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5496 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005497
Douglas Gregore2b37442012-05-04 22:38:52 +00005498 public:
5499 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005500
5501 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5502 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005503 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5504 }
5505 } Diagnoser(ArgType);
5506
5507 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005508 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005509 if (!Arg)
5510 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005511 }
5512
Richard Smithd663fdd2014-12-17 20:42:37 +00005513 // From here on out, all we care about is the unqualified form
5514 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005515 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005516
5517 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005518 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005519 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005520 } else if (ParamType->isBooleanType()) {
5521 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005522 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005523 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5524 !ParamType->isEnumeralType()) {
5525 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005526 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005527 } else {
5528 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005529 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005530 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005531 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005532 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005533 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005534 }
5535
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005536 // Add the value of this argument to the list of converted
5537 // arguments. We use the bitwidth and signedness of the template
5538 // parameter.
5539 if (Arg->isValueDependent()) {
5540 // The argument is value-dependent. Create a new
5541 // TemplateArgument with the converted expression.
5542 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005543 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005544 }
5545
Douglas Gregor52aba872009-03-14 00:20:21 +00005546 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005547 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005548 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005549
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005550 if (ParamType->isBooleanType()) {
5551 // Value must be zero or one.
5552 Value = Value != 0;
5553 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5554 if (Value.getBitWidth() != AllowedBits)
5555 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005556 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005557 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005558 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005559
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005560 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005561 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005562 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005563 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005564 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005565 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00005566
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005567 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005568 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005569 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005570 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005571 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5572 << Arg->getSourceRange();
5573 Diag(Param->getLocation(), diag::note_template_param_here);
5574 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005575
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005576 // Complain if we overflowed the template parameter's type.
5577 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005578 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005579 RequiredBits = OldValue.getActiveBits();
5580 else if (OldValue.isUnsigned())
5581 RequiredBits = OldValue.getActiveBits() + 1;
5582 else
5583 RequiredBits = OldValue.getMinSignedBits();
5584 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005585 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005586 diag::warn_template_arg_too_large)
5587 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5588 << Arg->getSourceRange();
5589 Diag(Param->getLocation(), diag::note_template_param_here);
5590 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005591 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005592
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005593 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00005594 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005595 ? Context.getCanonicalType(ParamType)
5596 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005597 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005598 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005599
Richard Smith08b12f12011-10-27 22:11:44 +00005600 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005601 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5602
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005603 // Handle pointer-to-function, reference-to-function, and
5604 // pointer-to-member-function all in (roughly) the same way.
5605 if (// -- For a non-type template-parameter of type pointer to
5606 // function, only the function-to-pointer conversion (4.3) is
5607 // applied. If the template-argument represents a set of
5608 // overloaded functions (or a pointer to such), the matching
5609 // function is selected from the set (13.4).
5610 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005611 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005612 // -- For a non-type template-parameter of type reference to
5613 // function, no conversions apply. If the template-argument
5614 // represents a set of overloaded functions, the matching
5615 // function is selected from the set (13.4).
5616 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005617 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005618 // -- For a non-type template-parameter of type pointer to
5619 // member function, no conversions apply. If the
5620 // template-argument represents a set of overloaded member
5621 // functions, the matching member function is selected from
5622 // the set (13.4).
5623 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005624 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005625 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005626
Douglas Gregor064fdb22010-04-14 23:11:21 +00005627 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005628 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005629 true,
5630 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005631 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005632 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005633
5634 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5635 ArgType = Arg->getType();
5636 } else
John Wiegley01296292011-04-08 18:41:53 +00005637 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005639
John Wiegley01296292011-04-08 18:41:53 +00005640 if (!ParamType->isMemberPointerType()) {
5641 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5642 ParamType,
5643 Arg, Converted))
5644 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005645 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005646 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005647
Douglas Gregor20fdef32012-04-10 17:08:25 +00005648 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5649 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005650 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005651 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005652 }
5653
Chris Lattner696197c2009-02-20 21:37:53 +00005654 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005655 // -- for a non-type template-parameter of type pointer to
5656 // object, qualification conversions (4.4) and the
5657 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005658 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005659 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005660 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005661
John Wiegley01296292011-04-08 18:41:53 +00005662 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5663 ParamType,
5664 Arg, Converted))
5665 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005666 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005667 }
Mike Stump11289f42009-09-09 15:08:12 +00005668
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005669 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005670 // -- For a non-type template-parameter of type reference to
5671 // object, no conversions apply. The type referred to by the
5672 // reference may be more cv-qualified than the (otherwise
5673 // identical) type of the template-argument. The
5674 // template-parameter is bound directly to the
5675 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005676 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005677 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005678
Douglas Gregor064fdb22010-04-14 23:11:21 +00005679 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005680 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5681 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005682 true,
5683 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005684 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005685 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005686
5687 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5688 ArgType = Arg->getType();
5689 } else
John Wiegley01296292011-04-08 18:41:53 +00005690 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005691 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005692
John Wiegley01296292011-04-08 18:41:53 +00005693 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5694 ParamType,
5695 Arg, Converted))
5696 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005697 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005698 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005699
Douglas Gregor20fdef32012-04-10 17:08:25 +00005700 // Deal with parameters of type std::nullptr_t.
5701 if (ParamType->isNullPtrType()) {
5702 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5703 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005704 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005705 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005706
Douglas Gregor20fdef32012-04-10 17:08:25 +00005707 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5708 case NPV_NotNullPointer:
5709 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5710 << Arg->getType() << ParamType;
5711 Diag(Param->getLocation(), diag::note_template_param_here);
5712 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005713
Douglas Gregor20fdef32012-04-10 17:08:25 +00005714 case NPV_Error:
5715 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005716
Douglas Gregor20fdef32012-04-10 17:08:25 +00005717 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005718 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005719 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5720 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005721 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005722 }
5723 }
5724
Douglas Gregor0e558532009-02-11 16:16:59 +00005725 // -- For a non-type template-parameter of type pointer to data
5726 // member, qualification conversions (4.4) are applied.
5727 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5728
Douglas Gregor20fdef32012-04-10 17:08:25 +00005729 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5730 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005731 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005732 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005733}
5734
Richard Smith26b86ea2016-12-31 21:41:23 +00005735static void DiagnoseTemplateParameterListArityMismatch(
5736 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
5737 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
5738
Douglas Gregord32e0282009-02-09 23:23:08 +00005739/// \brief Check a template argument against its corresponding
5740/// template template parameter.
5741///
5742/// This routine implements the semantics of C++ [temp.arg.template].
5743/// It returns true if an error occurred, and false otherwise.
5744bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005745 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005746 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005747 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005748 TemplateDecl *Template = Name.getAsTemplateDecl();
5749 if (!Template) {
5750 // Any dependent template name is fine.
5751 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5752 return false;
5753 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005754
Richard Smith26b86ea2016-12-31 21:41:23 +00005755 if (Template->isInvalidDecl())
5756 return true;
5757
Richard Smith3f1b5d02011-05-05 21:57:07 +00005758 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005759 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005760 // the name of a class template or an alias template, expressed as an
5761 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005762 // primary class templates are considered when matching the
5763 // template template argument with the corresponding parameter;
5764 // partial specializations are not considered even if their
5765 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005766 //
5767 // Note that we also allow template template parameters here, which
5768 // will happen when we are dealing with, e.g., class template
5769 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005770 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005771 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00005772 !isa<TypeAliasTemplateDecl>(Template) &&
5773 !isa<BuiltinTemplateDecl>(Template)) {
5774 assert(isa<FunctionTemplateDecl>(Template) &&
5775 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00005776 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00005777 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5778 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00005779 }
5780
Richard Smith1fde8ec2012-09-07 02:06:42 +00005781 TemplateParameterList *Params = Param->getTemplateParameters();
5782 if (Param->isExpandedParameterPack())
5783 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5784
Richard Smith26b86ea2016-12-31 21:41:23 +00005785 // C++1z [temp.arg.template]p3: (DR 150)
5786 // A template-argument matches a template template-parameter P when P
5787 // is at least as specialized as the template-argument A.
5788 if (getLangOpts().RelaxedTemplateTemplateArgs) {
5789 // Quick check for the common case:
5790 // If P contains a parameter pack, then A [...] matches P if each of A's
5791 // template parameters matches the corresponding template parameter in
5792 // the template-parameter-list of P.
5793 if (TemplateParameterListsAreEqual(
5794 Template->getTemplateParameters(), Params, false,
5795 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
5796 return false;
5797
5798 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
5799 Arg.getLocation()))
5800 return false;
5801 // FIXME: Produce better diagnostics for deduction failures.
5802 }
5803
Douglas Gregor85e0f662009-02-10 00:24:35 +00005804 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005805 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005806 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005807 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005808 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005809}
5810
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005811/// \brief Given a non-type template argument that refers to a
5812/// declaration and the type of its corresponding non-type template
5813/// parameter, produce an expression that properly refers to that
5814/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005815ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005816Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5817 QualType ParamType,
5818 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005819 // C++ [temp.param]p8:
5820 //
5821 // A non-type template-parameter of type "array of T" or
5822 // "function returning T" is adjusted to be of type "pointer to
5823 // T" or "pointer to function returning T", respectively.
5824 if (ParamType->isArrayType())
5825 ParamType = Context.getArrayDecayedType(ParamType);
5826 else if (ParamType->isFunctionType())
5827 ParamType = Context.getPointerType(ParamType);
5828
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005829 // For a NULL non-type template argument, return nullptr casted to the
5830 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005831 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005832 return ImpCastExprToType(
5833 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5834 ParamType,
5835 ParamType->getAs<MemberPointerType>()
5836 ? CK_NullToMemberPointer
5837 : CK_NullToPointer);
5838 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005839 assert(Arg.getKind() == TemplateArgument::Declaration &&
5840 "Only declaration template arguments permitted here");
5841
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005842 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5843
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005844 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005845 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5846 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005847 // If the value is a class member, we might have a pointer-to-member.
5848 // Determine whether the non-type template template parameter is of
5849 // pointer-to-member type. If so, we need to build an appropriate
5850 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5851 // would refer to the member itself.
5852 if (ParamType->isMemberPointerType()) {
5853 QualType ClassType
5854 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5855 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005856 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005857 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005858 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005859 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005860
5861 // The actual value-ness of this is unimportant, but for
5862 // internal consistency's sake, references to instance methods
5863 // are r-values.
5864 ExprValueKind VK = VK_LValue;
5865 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5866 VK = VK_RValue;
5867
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005868 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005869 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005870 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005871 Loc,
5872 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005873 if (RefExpr.isInvalid())
5874 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005875
John McCalle3027922010-08-25 11:45:40 +00005876 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005877
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005878 // We might need to perform a trailing qualification conversion, since
5879 // the element type on the parameter could be more qualified than the
5880 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005881 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005882 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005883 ParamType.getUnqualifiedType(), false,
5884 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005885 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005886
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005887 assert(!RefExpr.isInvalid() &&
5888 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005889 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005890 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005891 }
5892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005893
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005894 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005895
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005896 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005897 // When the non-type template parameter is a pointer, take the
5898 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005899 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005900 if (RefExpr.isInvalid())
5901 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005902
Richard Smithfc6fca12017-01-28 00:38:35 +00005903 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
5904 (T->isFunctionType() || T->isArrayType())) {
5905 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005906 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005907 if (RefExpr.isInvalid())
5908 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005909
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005910 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005911 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005912
Douglas Gregorb242683d2010-04-01 18:32:35 +00005913 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005914 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005915 }
5916
John McCall7decc9e2010-11-18 06:31:45 +00005917 ExprValueKind VK = VK_RValue;
5918
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005919 // If the non-type template parameter has reference type, qualify the
5920 // resulting declaration reference with the extra qualifiers on the
5921 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005922 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5923 VK = VK_LValue;
5924 T = Context.getQualifiedType(T,
5925 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005926 } else if (isa<FunctionDecl>(VD)) {
5927 // References to functions are always lvalues.
5928 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005929 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005930
John McCall7decc9e2010-11-18 06:31:45 +00005931 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005932}
5933
5934/// \brief Construct a new expression that refers to the given
5935/// integral template argument with the given source-location
5936/// information.
5937///
5938/// This routine takes care of the mapping from an integral template
5939/// argument (which may have any integral type) to the appropriate
5940/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005941ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005942Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5943 SourceLocation Loc) {
5944 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005945 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005946 QualType OrigT = Arg.getIntegralType();
5947
5948 // If this is an enum type that we're instantiating, we need to use an integer
5949 // type the same size as the enumerator. We don't want to build an
5950 // IntegerLiteral with enum type. The integer type of an enum type can be of
5951 // any integral type with C++11 enum classes, make sure we create the right
5952 // type of literal for it.
5953 QualType T = OrigT;
5954 if (const EnumType *ET = OrigT->getAs<EnumType>())
5955 T = ET->getDecl()->getIntegerType();
5956
5957 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005958 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005959 // This does not need to handle u8 character literals because those are
5960 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005961 CharacterLiteral::CharacterKind Kind;
5962 if (T->isWideCharType())
5963 Kind = CharacterLiteral::Wide;
5964 else if (T->isChar16Type())
5965 Kind = CharacterLiteral::UTF16;
5966 else if (T->isChar32Type())
5967 Kind = CharacterLiteral::UTF32;
5968 else
5969 Kind = CharacterLiteral::Ascii;
5970
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005971 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5972 Kind, T, Loc);
5973 } else if (T->isBooleanType()) {
5974 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5975 T, Loc);
5976 } else if (T->isNullPtrType()) {
5977 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5978 } else {
5979 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005980 }
5981
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005982 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005983 // FIXME: This is a hack. We need a better way to handle substituted
5984 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005985 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5986 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005987 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005988 Loc, Loc);
5989 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005990
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005991 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005992}
5993
Richard Smith43a833b2017-01-09 23:54:33 +00005994static bool isDependentOnOuter(NonTypeTemplateParmDecl *NTTP) {
5995 if (NTTP->getDepth() == 0 || !NTTP->getType()->isDependentType())
5996 return false;
5997 DependencyChecker Checker(NTTP->getDepth(), /*IgnoreNonTypeDependent*/ false,
5998 /*FindLessThanDepth*/ true);
5999 Checker.TraverseType(NTTP->getType());
6000 return Checker.Match;
6001}
6002
Douglas Gregor641040a2011-01-12 23:45:44 +00006003/// \brief Match two template parameters within template parameter lists.
6004static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6005 bool Complain,
6006 Sema::TemplateParameterListEqualKind Kind,
6007 SourceLocation TemplateArgLoc) {
6008 // Check the actual kind (type, non-type, template).
6009 if (Old->getKind() != New->getKind()) {
6010 if (Complain) {
6011 unsigned NextDiag = diag::err_template_param_different_kind;
6012 if (TemplateArgLoc.isValid()) {
6013 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6014 NextDiag = diag::note_template_param_different_kind;
6015 }
6016 S.Diag(New->getLocation(), NextDiag)
6017 << (Kind != Sema::TPL_TemplateMatch);
6018 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6019 << (Kind != Sema::TPL_TemplateMatch);
6020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006021
Douglas Gregor641040a2011-01-12 23:45:44 +00006022 return false;
6023 }
6024
Richard Smith26b86ea2016-12-31 21:41:23 +00006025 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006026 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006027 // template template parameter, the template template parameter can have
6028 // a parameter pack where the template template argument does not.
6029 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6030 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6031 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006032 if (Complain) {
6033 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6034 if (TemplateArgLoc.isValid()) {
6035 S.Diag(TemplateArgLoc,
6036 diag::err_template_arg_template_params_mismatch);
6037 NextDiag = diag::note_template_parameter_pack_non_pack;
6038 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006039
Douglas Gregor641040a2011-01-12 23:45:44 +00006040 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6041 : isa<NonTypeTemplateParmDecl>(New)? 1
6042 : 2;
6043 S.Diag(New->getLocation(), NextDiag)
6044 << ParamKind << New->isParameterPack();
6045 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6046 << ParamKind << Old->isParameterPack();
6047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006048
Douglas Gregor641040a2011-01-12 23:45:44 +00006049 return false;
6050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006051
Douglas Gregor641040a2011-01-12 23:45:44 +00006052 // For non-type template parameters, check the type of the parameter.
6053 if (NonTypeTemplateParmDecl *OldNTTP
6054 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6055 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006056
Douglas Gregor641040a2011-01-12 23:45:44 +00006057 // If we are matching a template template argument to a template
6058 // template parameter and one of the non-type template parameter types
Richard Smith43a833b2017-01-09 23:54:33 +00006059 // is dependent on an outer template's parameter, then we must wait until
6060 // template instantiation time to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00006061 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith43a833b2017-01-09 23:54:33 +00006062 (isDependentOnOuter(OldNTTP) || isDependentOnOuter(NewNTTP)))
Douglas Gregor641040a2011-01-12 23:45:44 +00006063 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006064
Douglas Gregor641040a2011-01-12 23:45:44 +00006065 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6066 if (Complain) {
6067 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6068 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006069 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00006070 diag::err_template_arg_template_params_mismatch);
6071 NextDiag = diag::note_template_nontype_parm_different_type;
6072 }
6073 S.Diag(NewNTTP->getLocation(), NextDiag)
6074 << NewNTTP->getType()
6075 << (Kind != Sema::TPL_TemplateMatch);
6076 S.Diag(OldNTTP->getLocation(),
6077 diag::note_template_nontype_parm_prev_declaration)
6078 << OldNTTP->getType();
6079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006080
Douglas Gregor641040a2011-01-12 23:45:44 +00006081 return false;
6082 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006083
Douglas Gregor641040a2011-01-12 23:45:44 +00006084 return true;
6085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006086
Douglas Gregor641040a2011-01-12 23:45:44 +00006087 // For template template parameters, check the template parameter types.
6088 // The template parameter lists of template template
6089 // parameters must agree.
6090 if (TemplateTemplateParmDecl *OldTTP
6091 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006092 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00006093 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6094 OldTTP->getTemplateParameters(),
6095 Complain,
6096 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006097 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00006098 : Kind),
6099 TemplateArgLoc);
6100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006101
Douglas Gregor641040a2011-01-12 23:45:44 +00006102 return true;
6103}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006104
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006105/// \brief Diagnose a known arity mismatch when comparing template argument
6106/// lists.
6107static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006108void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006109 TemplateParameterList *New,
6110 TemplateParameterList *Old,
6111 Sema::TemplateParameterListEqualKind Kind,
6112 SourceLocation TemplateArgLoc) {
6113 unsigned NextDiag = diag::err_template_param_list_different_arity;
6114 if (TemplateArgLoc.isValid()) {
6115 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6116 NextDiag = diag::note_template_param_list_different_arity;
6117 }
6118 S.Diag(New->getTemplateLoc(), NextDiag)
6119 << (New->size() > Old->size())
6120 << (Kind != Sema::TPL_TemplateMatch)
6121 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6122 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6123 << (Kind != Sema::TPL_TemplateMatch)
6124 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6125}
6126
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006127/// \brief Determine whether the given template parameter lists are
6128/// equivalent.
6129///
Mike Stump11289f42009-09-09 15:08:12 +00006130/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006131/// source code as part of a new template declaration.
6132///
6133/// \param Old The old template parameter list, typically found via
6134/// name lookup of the template declared with this template parameter
6135/// list.
6136///
6137/// \param Complain If true, this routine will produce a diagnostic if
6138/// the template parameter lists are not equivalent.
6139///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006140/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00006141///
6142/// \param TemplateArgLoc If this source location is valid, then we
6143/// are actually checking the template parameter list of a template
6144/// argument (New) against the template parameter list of its
6145/// corresponding template template parameter (Old). We produce
6146/// slightly different diagnostics in this scenario.
6147///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006148/// \returns True if the template parameter lists are equal, false
6149/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00006150bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006151Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6152 TemplateParameterList *Old,
6153 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006154 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00006155 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006156 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6157 if (Complain)
6158 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6159 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006160
6161 return false;
6162 }
6163
Douglas Gregor641040a2011-01-12 23:45:44 +00006164 // C++0x [temp.arg.template]p3:
6165 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006166 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00006167 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006168 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006169 // template-parameter-list of P. [...]
6170 TemplateParameterList::iterator NewParm = New->begin();
6171 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006172 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006173 OldParmEnd = Old->end();
6174 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00006175 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6176 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006177 if (NewParm == NewParmEnd) {
6178 if (Complain)
6179 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6180 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006181
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006182 return false;
6183 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006184
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006185 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6186 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006187 return false;
6188
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006189 ++NewParm;
6190 continue;
6191 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006192
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006193 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006194 // [...] When P's template- parameter-list contains a template parameter
6195 // pack (14.5.3), the template parameter pack will match zero or more
6196 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006197 // template-parameter-list of A with the same type and form as the
6198 // template parameter pack in P (ignoring whether those template
6199 // parameters are template parameter packs).
6200 for (; NewParm != NewParmEnd; ++NewParm) {
6201 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6202 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006203 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006204 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006205 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006206
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006207 // Make sure we exhausted all of the arguments.
6208 if (NewParm != NewParmEnd) {
6209 if (Complain)
6210 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6211 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006212
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006213 return false;
6214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006215
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006216 return true;
6217}
6218
6219/// \brief Check whether a template can be declared within this scope.
6220///
6221/// If the template declaration is valid in this scope, returns
6222/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00006223bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006224Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00006225 if (!S)
6226 return false;
6227
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006228 // Find the nearest enclosing declaration scope.
6229 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6230 (S->getFlags() & Scope::TemplateParamScope) != 0)
6231 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006232
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006233 // C++ [temp]p4:
6234 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00006235 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00006236 if (Ctx && Ctx->isExternCContext()) {
6237 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6238 << TemplateParams->getSourceRange();
6239 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6240 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6241 return true;
6242 }
Richard Smith8df390f2016-09-08 23:14:54 +00006243 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006244
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006245 // C++ [temp]p2:
6246 // A template-declaration can appear only as a namespace scope or
6247 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00006248 if (Ctx) {
6249 if (Ctx->isFileContext())
6250 return false;
6251 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6252 // C++ [temp.mem]p2:
6253 // A local class shall not have member templates.
6254 if (RD->isLocalClass())
6255 return Diag(TemplateParams->getTemplateLoc(),
6256 diag::err_template_inside_local_class)
6257 << TemplateParams->getSourceRange();
6258 else
6259 return false;
6260 }
6261 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006262
Mike Stump11289f42009-09-09 15:08:12 +00006263 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006264 diag::err_template_outside_namespace_or_class_scope)
6265 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006266}
Douglas Gregor67a65642009-02-17 23:15:12 +00006267
Douglas Gregor54888652009-10-07 00:13:32 +00006268/// \brief Determine what kind of template specialization the given declaration
6269/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006270static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00006271 if (!D)
6272 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006273
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006274 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6275 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00006276 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6277 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006278 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6279 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006280
Douglas Gregor54888652009-10-07 00:13:32 +00006281 return TSK_Undeclared;
6282}
6283
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006284/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006285/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00006286///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006287/// This routine determines whether a template specialization can be declared
6288/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00006289///
6290/// \param S the semantic analysis object for which this check is being
6291/// performed.
6292///
6293/// \param Specialized the entity being specialized or instantiated, which
6294/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006295/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00006296/// member class).
6297///
6298/// \param PrevDecl the previous declaration of this entity, if any.
6299///
6300/// \param Loc the location of the explicit specialization or instantiation of
6301/// this entity.
6302///
6303/// \param IsPartialSpecialization whether this is a partial specialization of
6304/// a class template.
6305///
Douglas Gregor54888652009-10-07 00:13:32 +00006306/// \returns true if there was an error that we cannot recover from, false
6307/// otherwise.
6308static bool CheckTemplateSpecializationScope(Sema &S,
6309 NamedDecl *Specialized,
6310 NamedDecl *PrevDecl,
6311 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006312 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00006313 // Keep these "kind" numbers in sync with the %select statements in the
6314 // various diagnostics emitted by this routine.
6315 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006316 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006317 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006318 else if (isa<VarTemplateDecl>(Specialized))
6319 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006320 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006321 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006322 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006323 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006324 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00006325 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006326 else if (isa<RecordDecl>(Specialized))
6327 EntityKind = 7;
6328 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6329 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00006330 else {
Richard Smith7d137e32012-03-23 03:33:32 +00006331 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006332 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006333 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00006334 return true;
6335 }
6336
Douglas Gregorf47b9112009-02-25 22:02:03 +00006337 // C++ [temp.expl.spec]p2:
6338 // An explicit specialization shall be declared in the namespace
6339 // of which the template is a member, or, for member templates, in
6340 // the namespace of which the enclosing class or enclosing class
6341 // template is a member. An explicit specialization of a member
6342 // function, member class or static data member of a class
6343 // template shall be declared in the namespace of which the class
6344 // template is a member. Such a declaration may also be a
6345 // definition. If the declaration is not a definition, the
6346 // specialization may be defined later in the name- space in which
6347 // the explicit specialization was declared, or in a namespace
6348 // that encloses the one in which the explicit specialization was
6349 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00006350 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00006351 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006352 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006353 return true;
6354 }
Douglas Gregore4b05162009-10-07 17:21:34 +00006355
Douglas Gregor40fb7442009-10-07 17:30:37 +00006356 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006357 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006358 // Do not warn for class scope explicit specialization during
6359 // instantiation, warning was already emitted during pattern
6360 // semantic analysis.
6361 if (!S.ActiveTemplateInstantiations.size())
6362 S.Diag(Loc, diag::ext_function_specialization_in_class)
6363 << Specialized;
6364 } else {
6365 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6366 << Specialized;
6367 return true;
6368 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006369 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006370
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006371 if (S.CurContext->isRecord() &&
6372 !S.CurContext->Equals(Specialized->getDeclContext())) {
6373 // Make sure that we're specializing in the right record context.
6374 // Otherwise, things can go horribly wrong.
6375 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6376 << Specialized;
6377 return true;
6378 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006379
Douglas Gregore4b05162009-10-07 17:21:34 +00006380 // C++ [temp.class.spec]p6:
6381 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006382 // in any namespace scope in which its definition may be defined (14.5.1
6383 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00006384 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00006385 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00006386 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00006387
6388 // Make sure that this redeclaration (or definition) occurs in an enclosing
6389 // namespace.
6390 // Note that HandleDeclarator() performs this check for explicit
6391 // specializations of function templates, static data members, and member
6392 // functions, so we skip the check here for those kinds of entities.
6393 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6394 // Should we refactor that check, so that it occurs later?
6395 if (!DC->Encloses(SpecializedContext) &&
6396 !(isa<FunctionTemplateDecl>(Specialized) ||
6397 isa<FunctionDecl>(Specialized) ||
6398 isa<VarTemplateDecl>(Specialized) ||
6399 isa<VarDecl>(Specialized))) {
6400 if (isa<TranslationUnitDecl>(SpecializedContext))
6401 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6402 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00006403 else if (isa<NamespaceDecl>(SpecializedContext)) {
6404 int Diag = diag::err_template_spec_redecl_out_of_scope;
6405 if (S.getLangOpts().MicrosoftExt)
6406 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6407 S.Diag(Loc, Diag) << EntityKind << Specialized
6408 << cast<NamedDecl>(SpecializedContext);
6409 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00006410 llvm_unreachable("unexpected namespace context for specialization");
6411
6412 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6413 } else if ((!PrevDecl ||
6414 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6415 getTemplateSpecializationKind(PrevDecl) ==
6416 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006417 // C++ [temp.exp.spec]p2:
6418 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006419 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006420 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006421 // An explicit specialization of a member function, member class or
6422 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006423 // namespace of which the class template is a member.
6424 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006425 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006426 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006427 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006428 // C++11 [temp.explicit]p3:
6429 // An explicit instantiation shall appear in an enclosing namespace of its
6430 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006431 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006432 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006433 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006434 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006435 "DC encloses TU but isn't in enclosing namespace set");
6436 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006437 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006438 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6439 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006440 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006441 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006442 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006443 Diag = diag::ext_template_spec_decl_out_of_scope;
6444 else
6445 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6446 S.Diag(Loc, Diag)
6447 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6448 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006449
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006450 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006451 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006452 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006453
Douglas Gregorf47b9112009-02-25 22:02:03 +00006454 return false;
6455}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006456
Richard Smith57aae072016-12-28 02:37:25 +00006457static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
6458 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00006459 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006460 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006461 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00006462 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006463 return E->getSourceRange();
6464 return Checker.MatchLoc;
6465}
6466
6467static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6468 if (!TL.getType()->isDependentType())
6469 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006470 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006471 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00006472 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006473 return TL.getSourceRange();
6474 return Checker.MatchLoc;
6475}
6476
Larisse Voufo39a1e502013-08-06 01:03:05 +00006477/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006478/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006479static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006480 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6481 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006482 for (unsigned I = 0; I != NumArgs; ++I) {
6483 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006484 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006485 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6486 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006487 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006488
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006489 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006490 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006491
Eli Friedmanb826a002012-09-26 02:36:12 +00006492 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006493 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006494
6495 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006496
Douglas Gregor98318c22011-01-03 21:37:45 +00006497 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006498 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6499 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006500
6501 // Strip off any implicit casts we added as part of type checking.
6502 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6503 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006504
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006505 // C++ [temp.class.spec]p8:
6506 // A non-type argument is non-specialized if it is the name of a
6507 // non-type parameter. All other non-type arguments are
6508 // specialized.
6509 //
6510 // Below, we check the two conditions that only apply to
6511 // specialized non-type arguments, so skip any non-specialized
6512 // arguments.
6513 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006514 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006515 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006516
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006517 // C++ [temp.class.spec]p9:
6518 // Within the argument list of a class template partial
6519 // specialization, the following restrictions apply:
6520 // -- A partially specialized non-type argument expression
6521 // shall not involve a template parameter of the partial
6522 // specialization except when the argument expression is a
6523 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00006524 // -- The type of a template parameter corresponding to a
6525 // specialized non-type argument shall not be dependent on a
6526 // parameter of the specialization.
6527 // DR1315 removes the first bullet, leaving an incoherent set of rules.
6528 // We implement a compromise between the original rules and DR1315:
6529 // -- A specialized non-type template argument shall not be
6530 // type-dependent and the corresponding template parameter
6531 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00006532 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00006533 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00006534 if (ParamUseRange.isValid()) {
6535 if (IsDefaultArgument) {
6536 S.Diag(TemplateNameLoc,
6537 diag::err_dependent_non_type_arg_in_partial_spec);
6538 S.Diag(ParamUseRange.getBegin(),
6539 diag::note_dependent_non_type_default_arg_in_partial_spec)
6540 << ParamUseRange;
6541 } else {
6542 S.Diag(ParamUseRange.getBegin(),
6543 diag::err_dependent_non_type_arg_in_partial_spec)
6544 << ParamUseRange;
6545 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006546 return true;
6547 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006548
Richard Smith6056d5e2014-02-09 00:54:43 +00006549 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00006550 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00006551 if (ParamUseRange.isValid()) {
6552 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6553 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Richard Smith57aae072016-12-28 02:37:25 +00006554 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00006555 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00006556 << (IsDefaultArgument ? ParamUseRange : SourceRange())
6557 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006558 return true;
6559 }
6560 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006561
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006562 return false;
6563}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006564
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006565/// \brief Check the non-type template arguments of a class template
6566/// partial specialization according to C++ [temp.class.spec]p9.
6567///
Richard Smith6056d5e2014-02-09 00:54:43 +00006568/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00006569/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006570/// template.
6571/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006572/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006573/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006574///
Richard Smith6056d5e2014-02-09 00:54:43 +00006575/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00006576bool Sema::CheckTemplatePartialSpecializationArgs(
6577 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
6578 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
6579 // We have to be conservative when checking a template in a dependent
6580 // context.
6581 if (PrimaryTemplate->getDeclContext()->isDependentContext())
6582 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006583
Richard Smith57aae072016-12-28 02:37:25 +00006584 TemplateParameterList *TemplateParams =
6585 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006586 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6587 NonTypeTemplateParmDecl *Param
6588 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6589 if (!Param)
6590 continue;
6591
Richard Smith57aae072016-12-28 02:37:25 +00006592 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
6593 Param, &TemplateArgs[I],
6594 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006595 return true;
6596 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006597
6598 return false;
6599}
6600
John McCall48871652010-08-21 09:40:31 +00006601DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006602Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6603 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006604 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006605 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006606 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006607 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006608 MultiTemplateParamsArg
6609 TemplateParameterLists,
6610 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006611 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006612
Richard Smith4b55a9c2014-04-17 03:29:33 +00006613 CXXScopeSpec &SS = TemplateId.SS;
6614
Abramo Bagnara60804e12011-03-18 15:16:37 +00006615 // NOTE: KWLoc is the location of the tag keyword. This will instead
6616 // store the location of the outermost template keyword in the declaration.
6617 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006618 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6619 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6620 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6621 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006622
Douglas Gregor67a65642009-02-17 23:15:12 +00006623 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006624 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006625 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006626 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6627
6628 if (!ClassTemplate) {
6629 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006630 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006631 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6632 return true;
6633 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006634
Richard Smithf445f192017-02-09 21:04:43 +00006635 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006636 bool isPartialSpecialization = false;
6637
Douglas Gregorf47b9112009-02-25 22:02:03 +00006638 // Check the validity of the template headers that introduce this
6639 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006640 // FIXME: We probably shouldn't complain about these headers for
6641 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006642 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006643 TemplateParameterList *TemplateParams =
6644 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006645 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00006646 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006647 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006648 if (Invalid)
6649 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006650
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006651 if (TemplateParams && TemplateParams->size() > 0) {
6652 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006653
Douglas Gregorec9518b2010-12-21 08:14:57 +00006654 if (TUK == TUK_Friend) {
6655 Diag(KWLoc, diag::err_partial_specialization_friend)
6656 << SourceRange(LAngleLoc, RAngleLoc);
6657 return true;
6658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006659
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006660 // C++ [temp.class.spec]p10:
6661 // The template parameter list of a specialization shall not
6662 // contain default template argument values.
6663 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6664 Decl *Param = TemplateParams->getParam(I);
6665 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6666 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006667 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006668 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006669 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006670 }
6671 } else if (NonTypeTemplateParmDecl *NTTP
6672 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6673 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006674 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006675 diag::err_default_arg_in_partial_spec)
6676 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006677 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006678 }
6679 } else {
6680 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006681 if (TTP->hasDefaultArgument()) {
6682 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006683 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006684 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006685 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006686 }
6687 }
6688 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006689 } else if (TemplateParams) {
6690 if (TUK == TUK_Friend)
6691 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006692 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006693 SourceRange(TemplateParams->getTemplateLoc(),
6694 TemplateParams->getRAngleLoc()))
6695 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00006696 } else {
6697 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006698 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006699
Douglas Gregor67a65642009-02-17 23:15:12 +00006700 // Check that the specialization uses the same tag kind as the
6701 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006702 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6703 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006704 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006705 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006706 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006707 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006708 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006709 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006710 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006711 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006712 diag::note_previous_use);
6713 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6714 }
6715
Douglas Gregorc40290e2009-03-09 23:48:35 +00006716 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006717 TemplateArgumentListInfo TemplateArgs =
6718 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006719
Douglas Gregor14406932011-01-03 20:35:03 +00006720 // Check for unexpanded parameter packs in any of the template arguments.
6721 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006722 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006723 UPPC_PartialSpecialization))
6724 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006725
Douglas Gregor67a65642009-02-17 23:15:12 +00006726 // Check that the template argument list is well-formed for this
6727 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006728 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006729 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6730 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006731 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006732
Douglas Gregor2373c592009-05-31 09:31:02 +00006733 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006734 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006735 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00006736 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
6737 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006738 return true;
6739
Richard Smith57aae072016-12-28 02:37:25 +00006740 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
6741 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00006742 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006743 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006744 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00006745 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006746 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6747 << ClassTemplate->getDeclName();
6748 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006749 }
6750 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006751
Craig Topperc3ec1492014-05-26 06:22:03 +00006752 void *InsertPos = nullptr;
6753 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006754
6755 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006756 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006757 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006758 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006759 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006760
Craig Topperc3ec1492014-05-26 06:22:03 +00006761 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006762
Douglas Gregorf47b9112009-02-25 22:02:03 +00006763 // Check whether we can declare a class template specialization in
6764 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006765 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006766 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6767 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006768 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006769 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770
Douglas Gregor15301382009-07-30 17:40:51 +00006771 // The canonical type
6772 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006773 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006774 // Build the canonical type that describes the converted template
6775 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006776 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6777 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00006778 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006779
6780 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006781 ClassTemplate->getInjectedClassNameSpecialization())) {
6782 // C++ [temp.class.spec]p9b3:
6783 //
6784 // -- The argument list of the specialization shall not be identical
6785 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00006786 //
6787 // This rule has since been removed, because it's redundant given DR1495,
6788 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006789 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006790 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006791 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006792 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6793 ClassTemplate->getIdentifier(),
6794 TemplateNameLoc,
6795 Attr,
6796 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006797 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006798 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006799 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006800 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006801 }
Douglas Gregor15301382009-07-30 17:40:51 +00006802
Douglas Gregor2373c592009-05-31 09:31:02 +00006803 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006804 ClassTemplatePartialSpecializationDecl *PrevPartial
6805 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006806 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006807 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006808 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006809 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006810 TemplateParams,
6811 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006812 Converted,
John McCall6b51f282009-11-23 01:53:49 +00006813 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006814 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006815 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006816 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006817 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006818 Partial->setTemplateParameterListsInfo(
6819 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006820 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006821
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006822 if (!PrevPartial)
6823 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006824 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006825
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006826 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006827 // template specialization, make a note of that.
6828 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6829 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006830
Richard Smith57aae072016-12-28 02:37:25 +00006831 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00006832 } else {
6833 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006834 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006835 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006836 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006837 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006838 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006839 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006840 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00006841 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006842 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006843 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006844 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006845 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006846 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006847
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006848 if (!PrevDecl)
6849 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006850
David Majnemer678f50b2015-11-18 19:49:19 +00006851 if (CurContext->isDependentContext()) {
6852 // -fms-extensions permits specialization of nested classes without
6853 // fully specializing the outer class(es).
6854 assert(getLangOpts().MicrosoftExt &&
6855 "Only possible with -fms-extensions!");
6856 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6857 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00006858 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00006859 } else {
6860 CanonType = Context.getTypeDeclType(Specialization);
6861 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006862 }
6863
Douglas Gregor06db9f52009-10-12 20:18:28 +00006864 // C++ [temp.expl.spec]p6:
6865 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006866 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006867 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006868 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006869 // use occurs; no diagnostic is required.
6870 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006871 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006872 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006873 // Is there any previous explicit specialization declaration?
6874 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6875 Okay = true;
6876 break;
6877 }
6878 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006879
Douglas Gregorc854c662010-02-26 06:03:23 +00006880 if (!Okay) {
6881 SourceRange Range(TemplateNameLoc, RAngleLoc);
6882 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6883 << Context.getTypeDeclType(Specialization) << Range;
6884
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006885 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006886 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006887 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006888 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006889 return true;
6890 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006891 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006892
Douglas Gregor2208a292009-09-26 20:57:03 +00006893 // If this is not a friend, note that this is an explicit specialization.
6894 if (TUK != TUK_Friend)
6895 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006896
6897 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006898 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006899 RecordDecl *Def = Specialization->getDefinition();
6900 NamedDecl *Hidden = nullptr;
6901 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6902 SkipBody->ShouldSkip = true;
6903 makeMergedDefinitionVisible(Hidden, KWLoc);
6904 // From here on out, treat this as just a redeclaration.
6905 TUK = TUK_Declaration;
6906 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006907 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00006908 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006909 Diag(Def->getLocation(), diag::note_previous_definition);
6910 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006911 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006912 }
6913 }
6914
John McCall659a3372010-12-18 03:30:47 +00006915 if (Attr)
6916 ProcessDeclAttributeList(S, Specialization, Attr);
6917
Richard Smith034b94a2012-08-17 03:20:55 +00006918 // Add alignment attributes if necessary; these attributes are checked when
6919 // the ASTContext lays out the structure.
6920 if (TUK == TUK_Definition) {
6921 AddAlignmentAttributesForRecord(Specialization);
6922 AddMsStructLayoutForRecord(Specialization);
6923 }
6924
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006925 if (ModulePrivateLoc.isValid())
6926 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6927 << (isPartialSpecialization? 1 : 0)
6928 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00006929
Douglas Gregord56a91e2009-02-26 22:19:44 +00006930 // Build the fully-sugared type for this class template
6931 // specialization as the user wrote in the specialization
6932 // itself. This means that we'll pretty-print the type retrieved
6933 // from the specialization's declaration the way that the user
6934 // actually wrote the specialization, rather than formatting the
6935 // name based on the "canonical" representation used to store the
6936 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006937 TypeSourceInfo *WrittenTy
6938 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6939 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006940 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006941 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006942 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006943 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006944
Douglas Gregor1e249f82009-02-25 22:18:32 +00006945 // C++ [temp.expl.spec]p9:
6946 // A template explicit specialization is in the scope of the
6947 // namespace in which the template was defined.
6948 //
6949 // We actually implement this paragraph where we set the semantic
6950 // context (in the creation of the ClassTemplateSpecializationDecl),
6951 // but we also maintain the lexical context where the actual
6952 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006953 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006954
Douglas Gregor67a65642009-02-17 23:15:12 +00006955 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006956 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006957 Specialization->startDefinition();
6958
Douglas Gregor2208a292009-09-26 20:57:03 +00006959 if (TUK == TUK_Friend) {
6960 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6961 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006962 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006963 /*FIXME:*/KWLoc);
6964 Friend->setAccess(AS_public);
6965 CurContext->addDecl(Friend);
6966 } else {
6967 // Add the specialization into its lexical context, so that it can
6968 // be seen when iterating through the list of declarations in that
6969 // context. However, specializations are not found by name lookup.
6970 CurContext->addDecl(Specialization);
6971 }
John McCall48871652010-08-21 09:40:31 +00006972 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006973}
Douglas Gregor333489b2009-03-27 23:10:48 +00006974
John McCall48871652010-08-21 09:40:31 +00006975Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006976 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006977 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006978 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006979 ActOnDocumentableDecl(NewDecl);
6980 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006981}
6982
John McCall4f7ced62010-02-11 01:33:53 +00006983/// \brief Strips various properties off an implicit instantiation
6984/// that has just been explicitly specialized.
6985static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006986 D->dropAttr<DLLImportAttr>();
6987 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006988
Nico Webere4974382014-12-19 23:52:45 +00006989 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006990 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006991}
6992
Nico Webera8f80b32012-01-09 19:52:25 +00006993/// \brief Compute the diagnostic location for an explicit instantiation
6994// declaration or definition.
6995static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006996 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006997 // Explicit instantiations following a specialization have no effect and
6998 // hence no PointOfInstantiation. In that case, walk decl backwards
6999 // until a valid name loc is found.
7000 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007001 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7002 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007003 PrevDiagLoc = Prev->getLocation();
7004 }
7005 assert(PrevDiagLoc.isValid() &&
7006 "Explicit instantiation without point of instantiation?");
7007 return PrevDiagLoc;
7008}
7009
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007010/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007011/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007012/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007013/// new specialization/instantiation will have any effect.
7014///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007015/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007016/// instantiation.
7017///
7018/// \param NewTSK the kind of the new explicit specialization or instantiation.
7019///
7020/// \param PrevDecl the previous declaration of the entity.
7021///
7022/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7023///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007024/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007025/// declaration was instantiated (either implicitly or explicitly).
7026///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007027/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007028/// specialization or instantiation has no effect and should be ignored.
7029///
7030/// \returns true if there was an error that should prevent the introduction of
7031/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007032bool
7033Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7034 TemplateSpecializationKind NewTSK,
7035 NamedDecl *PrevDecl,
7036 TemplateSpecializationKind PrevTSK,
7037 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007038 bool &HasNoEffect) {
7039 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007040
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007041 switch (NewTSK) {
7042 case TSK_Undeclared:
7043 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007044 assert(
7045 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7046 "previous declaration must be implicit!");
7047 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007048
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007049 case TSK_ExplicitSpecialization:
7050 switch (PrevTSK) {
7051 case TSK_Undeclared:
7052 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007053 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007054 // explicitly specialized or has merely been mentioned without any
7055 // instantiation.
7056 return false;
7057
7058 case TSK_ImplicitInstantiation:
7059 if (PrevPointOfInstantiation.isInvalid()) {
7060 // The declaration itself has not actually been instantiated, so it is
7061 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007062 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007063 return false;
7064 }
7065 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007066
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007067 case TSK_ExplicitInstantiationDeclaration:
7068 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007069 assert((PrevTSK == TSK_ImplicitInstantiation ||
7070 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007071 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007072
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007073 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007074 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007075 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007076 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007077 // implicit instantiation to take place, in every translation unit in
7078 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007079 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007080 // Is there any previous explicit specialization declaration?
7081 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7082 return false;
7083 }
7084
Douglas Gregor1d957a32009-10-27 18:42:08 +00007085 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007086 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007087 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007088 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007089
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007090 return true;
7091 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007092
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007093 case TSK_ExplicitInstantiationDeclaration:
7094 switch (PrevTSK) {
7095 case TSK_ExplicitInstantiationDeclaration:
7096 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007097 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007098 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007099
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007100 case TSK_Undeclared:
7101 case TSK_ImplicitInstantiation:
7102 // We're explicitly instantiating something that may have already been
7103 // implicitly instantiated; that's fine.
7104 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007105
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007106 case TSK_ExplicitSpecialization:
7107 // C++0x [temp.explicit]p4:
7108 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007109 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007110 // specialization for that template, the explicit instantiation has no
7111 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007112 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007113 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007114
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007115 case TSK_ExplicitInstantiationDefinition:
7116 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007117 // If an entity is the subject of both an explicit instantiation
7118 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007119 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007120 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007121 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007122
7123 // Explicit instantiations following a specialization have no effect and
7124 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7125 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007126 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7127 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007128 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007129 return false;
7130 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007131
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007132 case TSK_ExplicitInstantiationDefinition:
7133 switch (PrevTSK) {
7134 case TSK_Undeclared:
7135 case TSK_ImplicitInstantiation:
7136 // We're explicitly instantiating something that may have already been
7137 // implicitly instantiated; that's fine.
7138 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007139
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007140 case TSK_ExplicitSpecialization:
7141 // C++ DR 259, C++0x [temp.explicit]p4:
7142 // For a given set of template parameters, if an explicit
7143 // instantiation of a template appears after a declaration of
7144 // an explicit specialization for that template, the explicit
7145 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00007146 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007147 << PrevDecl;
7148 Diag(PrevDecl->getLocation(),
7149 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007150 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007151 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007152
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007153 case TSK_ExplicitInstantiationDeclaration:
7154 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007155 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00007156
7157 // C++0x [temp.explicit]p4:
7158 // For a given set of template parameters, if an explicit instantiation
7159 // of a template appears after a declaration of an explicit
7160 // specialization for that template, the explicit instantiation has no
7161 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007162 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00007163 // Is there any previous explicit specialization declaration?
7164 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7165 HasNoEffect = true;
7166 break;
7167 }
7168 }
7169
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007170 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007171
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007172 case TSK_ExplicitInstantiationDefinition:
7173 // C++0x [temp.spec]p5:
7174 // For a given template and a given set of template-arguments,
7175 // - an explicit instantiation definition shall appear at most once
7176 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007177
7178 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7179 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00007180 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007181 : diag::err_explicit_instantiation_duplicate)
7182 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00007183 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00007184 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007185 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007186 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007187 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007189
David Blaikie83d382b2011-09-23 05:06:16 +00007190 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007191}
7192
John McCallb9c78482010-04-08 09:05:18 +00007193/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00007194/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00007195///
James Dennettf14a6e52012-06-15 22:23:43 +00007196/// The only possible way to get a dependent function template specialization
7197/// is with a friend declaration, like so:
7198///
7199/// \code
7200/// template \<class T> void foo(T);
7201/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00007202/// friend void foo<>(T);
7203/// };
James Dennettf14a6e52012-06-15 22:23:43 +00007204/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00007205///
7206/// There really isn't any useful analysis we can do here, so we
7207/// just store the information.
7208bool
7209Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7210 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7211 LookupResult &Previous) {
7212 // Remove anything from Previous that isn't a function template in
7213 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00007214 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00007215 LookupResult::Filter F = Previous.makeFilter();
7216 while (F.hasNext()) {
7217 NamedDecl *D = F.next()->getUnderlyingDecl();
7218 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00007219 !FDLookupContext->InEnclosingNamespaceSetOf(
7220 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00007221 F.erase();
7222 }
7223 F.done();
7224
7225 // Should this be diagnosed here?
7226 if (Previous.empty()) return true;
7227
7228 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7229 ExplicitTemplateArgs);
7230 return false;
7231}
7232
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007233/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007234/// specialization.
7235///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007236/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007237/// explicit function template specialization. On successful completion,
7238/// the function declaration \p FD will become a function template
7239/// specialization.
7240///
7241/// \param FD the function declaration, which will be updated to become a
7242/// function template specialization.
7243///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007244/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7245/// if any. Note that this may be valid info even when 0 arguments are
7246/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7247/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007248///
Francois Pichet3a44e432011-07-08 06:21:47 +00007249/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007250/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007251bool Sema::CheckFunctionTemplateSpecialization(
7252 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7253 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007254 // The set of function template specializations that could match this
7255 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00007256 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007257 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7258 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007259
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007260 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7261 ConvertedTemplateArgs;
7262
Sebastian Redl50c68252010-08-31 00:36:30 +00007263 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00007264 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7265 I != E; ++I) {
7266 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7267 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007268 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007269 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007270 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7271 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007272 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007273
Richard Smith574f4f62013-01-14 05:37:29 +00007274 // When matching a constexpr member function template specialization
7275 // against the primary template, we don't yet know whether the
7276 // specialization has an implicit 'const' (because we don't know whether
7277 // it will be a static member function until we know which template it
7278 // specializes), so adjust it now assuming it specializes this template.
7279 QualType FT = FD->getType();
7280 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007281 CXXMethodDecl *OldMD =
7282 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00007283 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007284 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00007285 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7286 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007287 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007288 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00007289 }
7290 }
7291
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007292 TemplateArgumentListInfo Args;
7293 if (ExplicitTemplateArgs)
7294 Args = *ExplicitTemplateArgs;
7295
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007296 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007297 // A trailing template-argument can be left unspecified in the
7298 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007299 // provided it can be deduced from the function argument type.
7300 // Perform template argument deduction to determine whether we may be
7301 // specializing this template.
7302 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00007303 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007304 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00007305 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7306 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00007307 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7308 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007309 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007310 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00007311 FailedCandidates.addCandidate().set(
7312 I.getPair(), FunTmpl->getTemplatedDecl(),
7313 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007314 (void)TDK;
7315 continue;
7316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007317
Artem Belevich64135c32016-12-08 19:38:13 +00007318 // Target attributes are part of the cuda function signature, so
7319 // the deduced template's cuda target must match that of the
7320 // specialization. Given that C++ template deduction does not
7321 // take target attributes into account, we reject candidates
7322 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007323 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00007324 IdentifyCUDATarget(Specialization,
7325 /* IgnoreImplicitHDAttributes = */ true) !=
7326 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007327 FailedCandidates.addCandidate().set(
7328 I.getPair(), FunTmpl->getTemplatedDecl(),
7329 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7330 continue;
7331 }
7332
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007333 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007334 if (ExplicitTemplateArgs)
7335 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00007336 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007337 }
7338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007339
Douglas Gregor5de279c2009-09-26 03:41:46 +00007340 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007341 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007342 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007343 FD->getLocation(),
7344 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7345 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00007346 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007347 PDiag(diag::note_function_template_spec_matched));
7348
John McCall58cc69d2010-01-27 01:50:18 +00007349 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007350 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007351
7352 // Ignore access information; it doesn't figure into redeclaration checking.
7353 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007354
Nathan Wilson83839122016-04-09 02:55:27 +00007355 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7356 // an explicit specialization (14.8.3) [...] of a concept definition.
7357 if (Specialization->getPrimaryTemplate()->isConcept()) {
7358 Diag(FD->getLocation(), diag::err_concept_specialized)
7359 << 0 /*function*/ << 1 /*explicitly specialized*/;
7360 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7361 return true;
7362 }
7363
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007364 FunctionTemplateSpecializationInfo *SpecInfo
7365 = Specialization->getTemplateSpecializationInfo();
7366 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007367
7368 // Note: do not overwrite location info if previous template
7369 // specialization kind was explicit.
7370 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00007371 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00007372 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00007373 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7374 // function can differ from the template declaration with respect to
7375 // the constexpr specifier.
7376 Specialization->setConstexpr(FD->isConstexpr());
7377 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007378
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007379 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00007380 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00007381
7382 // If this is a friend declaration, then we're not really declaring
7383 // an explicit specialization.
7384 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007385
Douglas Gregor54888652009-10-07 00:13:32 +00007386 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00007387 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007388 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00007389 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007390 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007391 false))
Douglas Gregor54888652009-10-07 00:13:32 +00007392 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007393
7394 // C++ [temp.expl.spec]p6:
7395 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007396 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007397 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007398 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007399 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007400 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007401 if (!isFriend &&
7402 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007403 TSK_ExplicitSpecialization,
7404 Specialization,
7405 SpecInfo->getTemplateSpecializationKind(),
7406 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007407 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007408 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00007409
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007410 // Mark the prior declaration as an explicit specialization, so that later
7411 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007412 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007413 // Since explicit specializations do not inherit '=delete' from their
7414 // primary function template - check if the 'specialization' that was
7415 // implicitly generated (during template argument deduction for partial
7416 // ordering) from the most specialized of all the function templates that
7417 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7418 // first check that it was implicitly generated during template argument
7419 // deduction by making sure it wasn't referenced, and then reset the deleted
7420 // flag to not-deleted, so that we can inherit that information from 'FD'.
7421 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7422 !Specialization->getCanonicalDecl()->isReferenced()) {
7423 assert(
7424 Specialization->getCanonicalDecl() == Specialization &&
7425 "This must be the only existing declaration of this specialization");
7426 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007427 }
John McCall816d75b2010-03-24 07:46:06 +00007428 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007429 MarkUnusedFileScopedDecl(Specialization);
7430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007431
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007432 // Turn the given function declaration into a function template
7433 // specialization, with the template arguments from the previous
7434 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007435 // Take copies of (semantic and syntactic) template argument lists.
7436 const TemplateArgumentList* TemplArgs = new (Context)
7437 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007438 FD->setFunctionTemplateSpecialization(
7439 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7440 SpecInfo->getTemplateSpecializationKind(),
7441 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007442
Artem Belevich64135c32016-12-08 19:38:13 +00007443 // A function template specialization inherits the target attributes
7444 // of its template. (We require the attributes explicitly in the
7445 // code to match, but a template may have implicit attributes by
7446 // virtue e.g. of being constexpr, and it passes these implicit
7447 // attributes on to its specializations.)
7448 if (LangOpts.CUDA)
7449 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
7450
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007451 // The "previous declaration" for this function template specialization is
7452 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007453 Previous.clear();
7454 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007455 return false;
7456}
7457
Douglas Gregor86d142a2009-10-08 07:24:58 +00007458/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007459/// specialization.
7460///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007461/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007462/// explicit member function specialization. On successful completion,
7463/// the function declaration \p FD will become a member function
7464/// specialization.
7465///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007466/// \param Member the member declaration, which will be updated to become a
7467/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007468///
John McCall1f82f242009-11-18 22:49:29 +00007469/// \param Previous the set of declarations, one of which may be specialized
7470/// by this function specialization; the set will be modified to contain the
7471/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007472bool
John McCall1f82f242009-11-18 22:49:29 +00007473Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007474 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007475
Douglas Gregor86d142a2009-10-08 07:24:58 +00007476 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007477 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007478 NamedDecl *Instantiation = nullptr;
7479 NamedDecl *InstantiatedFrom = nullptr;
7480 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007481
John McCall1f82f242009-11-18 22:49:29 +00007482 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007483 // Nowhere to look anyway.
7484 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007485 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7486 I != E; ++I) {
7487 NamedDecl *D = (*I)->getUnderlyingDecl();
7488 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007489 QualType Adjusted = Function->getType();
7490 if (!hasExplicitCallingConv(Adjusted))
7491 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7492 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007493 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007494 Instantiation = Method;
7495 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007496 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007497 break;
7498 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007499 }
7500 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007501 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007502 VarDecl *PrevVar;
7503 if (Previous.isSingleResult() &&
7504 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007505 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007506 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007507 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007508 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007509 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007510 }
7511 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007512 CXXRecordDecl *PrevRecord;
7513 if (Previous.isSingleResult() &&
7514 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007515 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007516 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007517 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007518 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007519 }
Richard Smith7d137e32012-03-23 03:33:32 +00007520 } else if (isa<EnumDecl>(Member)) {
7521 EnumDecl *PrevEnum;
7522 if (Previous.isSingleResult() &&
7523 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007524 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007525 Instantiation = PrevEnum;
7526 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7527 MSInfo = PrevEnum->getMemberSpecializationInfo();
7528 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007529 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007530
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007531 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007532 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007533 // specializations are always out-of-line, the caller will complain about
7534 // this mismatch later.
7535 return false;
7536 }
John McCalle820e5e2010-04-13 20:37:33 +00007537
7538 // If this is a friend, just bail out here before we start turning
7539 // things into explicit specializations.
7540 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7541 // Preserve instantiation information.
7542 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7543 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7544 cast<CXXMethodDecl>(InstantiatedFrom),
7545 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7546 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7547 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7548 cast<CXXRecordDecl>(InstantiatedFrom),
7549 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7550 }
7551
7552 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007553 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007554 return false;
7555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007556
Douglas Gregor86d142a2009-10-08 07:24:58 +00007557 // Make sure that this is a specialization of a member.
7558 if (!InstantiatedFrom) {
7559 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7560 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007561 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7562 return true;
7563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007564
Douglas Gregor06db9f52009-10-12 20:18:28 +00007565 // C++ [temp.expl.spec]p6:
7566 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007567 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007568 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007569 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007570 // use occurs; no diagnostic is required.
7571 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007572
Abramo Bagnara8075c852010-06-12 07:44:57 +00007573 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007574 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7575 TSK_ExplicitSpecialization,
7576 Instantiation,
7577 MSInfo->getTemplateSpecializationKind(),
7578 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007579 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007580 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007581
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007582 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007583 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007584 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007585 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007586 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007587 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007588
Douglas Gregor86d142a2009-10-08 07:24:58 +00007589 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007590 // the original declaration to note that it is an explicit specialization
7591 // (if it was previously an implicit instantiation). This latter step
7592 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007593 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007594 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7595 if (InstantiationFunction->getTemplateSpecializationKind() ==
7596 TSK_ImplicitInstantiation) {
7597 InstantiationFunction->setTemplateSpecializationKind(
7598 TSK_ExplicitSpecialization);
7599 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007600 // Explicit specializations of member functions of class templates do not
7601 // inherit '=delete' from the member function they are specializing.
7602 if (InstantiationFunction->isDeleted()) {
7603 assert(InstantiationFunction->getCanonicalDecl() ==
7604 InstantiationFunction);
Richard Smith5f274382016-09-28 23:55:27 +00007605 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007606 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007608
Douglas Gregor86d142a2009-10-08 07:24:58 +00007609 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7610 cast<CXXMethodDecl>(InstantiatedFrom),
7611 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007612 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007613 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007614 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7615 if (InstantiationVar->getTemplateSpecializationKind() ==
7616 TSK_ImplicitInstantiation) {
7617 InstantiationVar->setTemplateSpecializationKind(
7618 TSK_ExplicitSpecialization);
7619 InstantiationVar->setLocation(Member->getLocation());
7620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007621
Larisse Voufo39a1e502013-08-06 01:03:05 +00007622 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7623 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007624 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007625 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007626 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7627 if (InstantiationClass->getTemplateSpecializationKind() ==
7628 TSK_ImplicitInstantiation) {
7629 InstantiationClass->setTemplateSpecializationKind(
7630 TSK_ExplicitSpecialization);
7631 InstantiationClass->setLocation(Member->getLocation());
7632 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007633
Douglas Gregor86d142a2009-10-08 07:24:58 +00007634 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007635 cast<CXXRecordDecl>(InstantiatedFrom),
7636 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007637 } else {
7638 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7639 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7640 if (InstantiationEnum->getTemplateSpecializationKind() ==
7641 TSK_ImplicitInstantiation) {
7642 InstantiationEnum->setTemplateSpecializationKind(
7643 TSK_ExplicitSpecialization);
7644 InstantiationEnum->setLocation(Member->getLocation());
7645 }
7646
7647 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7648 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007649 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007650
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007651 // Save the caller the trouble of having to figure out which declaration
7652 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007653 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007654 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007655 return false;
7656}
7657
Douglas Gregore47f5a72009-10-14 23:41:34 +00007658/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007659///
7660/// \returns true if a serious error occurs, false otherwise.
7661static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007662 SourceLocation InstLoc,
7663 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007664 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7665 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007666
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007667 if (CurContext->isRecord()) {
7668 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7669 << D;
7670 return true;
7671 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007672
Richard Smith050d2612011-10-18 02:28:33 +00007673 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007674 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007675 // template. If the name declared in the explicit instantiation is an
7676 // unqualified name, the explicit instantiation shall appear in the
7677 // namespace where its template is declared or, if that namespace is inline
7678 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007679 //
7680 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007681 if (WasQualifiedName) {
7682 if (CurContext->Encloses(OrigContext))
7683 return false;
7684 } else {
7685 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7686 return false;
7687 }
7688
7689 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7690 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007691 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007692 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007693 diag::err_explicit_instantiation_out_of_scope :
7694 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007695 << D << NS;
7696 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007697 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007698 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007699 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7700 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7701 << D << NS;
7702 } else
7703 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007704 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007705 diag::err_explicit_instantiation_must_be_global :
7706 diag::warn_explicit_instantiation_must_be_global_0x)
7707 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007708 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007709 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007710}
7711
7712/// \brief Determine whether the given scope specifier has a template-id in it.
7713static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7714 if (!SS.isSet())
7715 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007716
Richard Smith050d2612011-10-18 02:28:33 +00007717 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007718 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007719 // or a static data member of a class template specialization, the name of
7720 // the class template specialization in the qualified-id for the member
7721 // name shall be a simple-template-id.
7722 //
7723 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007724 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7725 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007726 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007727 if (isa<TemplateSpecializationType>(T))
7728 return true;
7729
7730 return false;
7731}
7732
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007733/// Make a dllexport or dllimport attr on a class template specialization take
7734/// effect.
7735static void dllExportImportClassTemplateSpecialization(
7736 Sema &S, ClassTemplateSpecializationDecl *Def) {
7737 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
7738 assert(A && "dllExportImportClassTemplateSpecialization called "
7739 "on Def without dllexport or dllimport");
7740
7741 // We reject explicit instantiations in class scope, so there should
7742 // never be any delayed exported classes to worry about.
7743 assert(S.DelayedDllExportClasses.empty() &&
7744 "delayed exports present at explicit instantiation");
7745 S.checkClassLevelDLLAttribute(Def);
7746
7747 // Propagate attribute to base class templates.
7748 for (auto &B : Def->bases()) {
7749 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7750 B.getType()->getAsCXXRecordDecl()))
7751 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7752 }
7753
7754 S.referenceDLLExportedClassMethods();
7755}
7756
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007757// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007758DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007759Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007760 SourceLocation ExternLoc,
7761 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007762 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007763 SourceLocation KWLoc,
7764 const CXXScopeSpec &SS,
7765 TemplateTy TemplateD,
7766 SourceLocation TemplateNameLoc,
7767 SourceLocation LAngleLoc,
7768 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007769 SourceLocation RAngleLoc,
7770 AttributeList *Attr) {
7771 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007772 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007773 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007774 // Check that the specialization uses the same tag kind as the
7775 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007776 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7777 assert(Kind != TTK_Enum &&
7778 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007779
Richard Trieu265c3442016-04-05 21:13:54 +00007780 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7781
7782 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00007783 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
7784 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00007785 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00007786 return true;
7787 }
7788
Douglas Gregord9034f02009-05-14 16:41:31 +00007789 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007790 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007791 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007792 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007793 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007794 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007795 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007796 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007797 diag::note_previous_use);
7798 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7799 }
7800
Douglas Gregore47f5a72009-10-14 23:41:34 +00007801 // C++0x [temp.explicit]p2:
7802 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007803 // definition and an explicit instantiation declaration. An explicit
7804 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007805 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7806 ? TSK_ExplicitInstantiationDefinition
7807 : TSK_ExplicitInstantiationDeclaration;
7808
7809 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7810 // Check for dllexport class template instantiation declarations.
7811 for (AttributeList *A = Attr; A; A = A->getNext()) {
7812 if (A->getKind() == AttributeList::AT_DLLExport) {
7813 Diag(ExternLoc,
7814 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7815 Diag(A->getLoc(), diag::note_attribute);
7816 break;
7817 }
7818 }
7819
7820 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7821 Diag(ExternLoc,
7822 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7823 Diag(A->getLocation(), diag::note_attribute);
7824 }
7825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007826
Hans Wennborga86a83b2016-05-26 19:42:56 +00007827 // In MSVC mode, dllimported explicit instantiation definitions are treated as
7828 // instantiation declarations for most purposes.
7829 bool DLLImportExplicitInstantiationDef = false;
7830 if (TSK == TSK_ExplicitInstantiationDefinition &&
7831 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7832 // Check for dllimport class template instantiation definitions.
7833 bool DLLImport =
7834 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7835 for (AttributeList *A = Attr; A; A = A->getNext()) {
7836 if (A->getKind() == AttributeList::AT_DLLImport)
7837 DLLImport = true;
7838 if (A->getKind() == AttributeList::AT_DLLExport) {
7839 // dllexport trumps dllimport here.
7840 DLLImport = false;
7841 break;
7842 }
7843 }
7844 if (DLLImport) {
7845 TSK = TSK_ExplicitInstantiationDeclaration;
7846 DLLImportExplicitInstantiationDef = true;
7847 }
7848 }
7849
Douglas Gregora1f49972009-05-13 00:25:59 +00007850 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007851 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007852 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007853
7854 // Check that the template argument list is well-formed for this
7855 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007856 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007857 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7858 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007859 return true;
7860
Douglas Gregora1f49972009-05-13 00:25:59 +00007861 // Find the class template specialization declaration that
7862 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007863 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007864 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007865 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007866
Abramo Bagnara8075c852010-06-12 07:44:57 +00007867 TemplateSpecializationKind PrevDecl_TSK
7868 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7869
Douglas Gregor54888652009-10-07 00:13:32 +00007870 // C++0x [temp.explicit]p2:
7871 // [...] An explicit instantiation shall appear in an enclosing
7872 // namespace of its template. [...]
7873 //
7874 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007875 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7876 SS.isSet()))
7877 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007878
Craig Topperc3ec1492014-05-26 06:22:03 +00007879 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007880
Abramo Bagnara8075c852010-06-12 07:44:57 +00007881 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007882 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007883 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007884 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007885 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007886 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007887 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007888
Abramo Bagnara8075c852010-06-12 07:44:57 +00007889 // Even though HasNoEffect == true means that this explicit instantiation
7890 // has no effect on semantics, we go on to put its syntax in the AST.
7891
7892 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7893 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007894 // Since the only prior class template specialization with these
7895 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007896 // declaration node as our own, updating the source location
7897 // for the template name to reflect our new declaration.
7898 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007899 Specialization = PrevDecl;
7900 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007901 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007902 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00007903
7904 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7905 DLLImportExplicitInstantiationDef) {
7906 // The new specialization might add a dllimport attribute.
7907 HasNoEffect = false;
7908 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007909 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007910
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007911 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007912 // Create a new class template specialization declaration node for
7913 // this explicit specialization.
7914 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007915 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007916 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007917 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007918 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007919 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007920 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007921 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007922
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007923 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007924 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007925 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007926 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007927 }
7928
7929 // Build the fully-sugared type for this explicit instantiation as
7930 // the user wrote in the explicit instantiation itself. This means
7931 // that we'll pretty-print the type retrieved from the
7932 // specialization's declaration the way that the user actually wrote
7933 // the explicit instantiation, rather than formatting the name based
7934 // on the "canonical" representation used to store the template
7935 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007936 TypeSourceInfo *WrittenTy
7937 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7938 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007939 Context.getTypeDeclType(Specialization));
7940 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007941
Abramo Bagnara8075c852010-06-12 07:44:57 +00007942 // Set source locations for keywords.
7943 Specialization->setExternLoc(ExternLoc);
7944 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00007945 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007946
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00007947 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Rafael Espindola0b062072012-01-03 06:04:21 +00007948 if (Attr)
7949 ProcessDeclAttributeList(S, Specialization, Attr);
7950
Abramo Bagnara8075c852010-06-12 07:44:57 +00007951 // Add the explicit instantiation into its lexical context. However,
7952 // since explicit instantiations are never found by name lookup, we
7953 // just put it into the declaration context directly.
7954 Specialization->setLexicalDeclContext(CurContext);
7955 CurContext->addDecl(Specialization);
7956
7957 // Syntax is now OK, so return if it has no other effect on semantics.
7958 if (HasNoEffect) {
7959 // Set the template specialization kind.
7960 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007961 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007962 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007963
7964 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007965 // A definition of a class template or class member template
7966 // shall be in scope at the point of the explicit instantiation of
7967 // the class template or class member template.
7968 //
7969 // This check comes when we actually try to perform the
7970 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007971 ClassTemplateSpecializationDecl *Def
7972 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007973 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007974 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007975 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007976 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007977 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007978 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7979 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007980
Douglas Gregor1d957a32009-10-27 18:42:08 +00007981 // Instantiate the members of this class template specialization.
7982 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007983 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007984 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007985 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007986 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7987 // TSK_ExplicitInstantiationDefinition
7988 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00007989 (TSK == TSK_ExplicitInstantiationDefinition ||
7990 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007991 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007992 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007993
Hans Wennborgc0875502015-06-09 00:39:05 +00007994 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00007995 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
7996 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00007997 // In the MS ABI, an explicit instantiation definition can add a dll
7998 // attribute to a template with a previous instantiation declaration.
7999 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008000 auto *A = cast<InheritableAttr>(
8001 getDLLAttr(Specialization)->clone(getASTContext()));
8002 A->setInherited(true);
8003 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008004 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008005 }
8006 }
8007
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008008 // Fix a TSK_ImplicitInstantiation followed by a
8009 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008010 bool NewlyDLLExported =
8011 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8012 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008013 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8014 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8015 // In the MS ABI, an explicit instantiation definition can add a dll
8016 // attribute to a template with a previous implicit instantiation.
8017 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8018 // avoid potentially strange codegen behavior. For example, if we extend
8019 // this conditional to dllimport, and we have a source file calling a
8020 // method on an implicitly instantiated template class instance and then
8021 // declaring a dllimport explicit instantiation definition for the same
8022 // template class, the codegen for the method call will not respect the
8023 // dllimport, while it will with cl. The Def will already have the DLL
8024 // attribute, since the Def and Specialization will be the same in the
8025 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8026 // attribute to the Specialization; we just need to make it take effect.
8027 assert(Def == Specialization &&
8028 "Def and Specialization should match for implicit instantiation");
8029 dllExportImportClassTemplateSpecialization(*this, Def);
8030 }
8031
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008032 // Set the template specialization kind. Make sure it is set before
8033 // instantiating the members which will trigger ASTConsumer callbacks.
8034 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008035 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008036 } else {
8037
8038 // Set the template specialization kind.
8039 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008040 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008041
John McCall48871652010-08-21 09:40:31 +00008042 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008043}
8044
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008045// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008046DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008047Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008048 SourceLocation ExternLoc,
8049 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008050 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008051 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008052 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008053 IdentifierInfo *Name,
8054 SourceLocation NameLoc,
8055 AttributeList *Attr) {
8056
Douglas Gregord6ab8742009-05-28 23:31:59 +00008057 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008058 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008059 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008060 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008061 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008062 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008063 SourceLocation(), false, TypeResult(),
8064 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00008065 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8066
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008067 if (!TagD)
8068 return true;
8069
John McCall48871652010-08-21 09:40:31 +00008070 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00008071 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008072
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008073 if (Tag->isInvalidDecl())
8074 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008075
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008076 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8077 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8078 if (!Pattern) {
8079 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8080 << Context.getTypeDeclType(Record);
8081 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8082 return true;
8083 }
8084
Douglas Gregore47f5a72009-10-14 23:41:34 +00008085 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008086 // If the explicit instantiation is for a class or member class, the
8087 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00008088 // simple-template-id.
8089 //
8090 // C++98 has the same restriction, just worded differently.
8091 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00008092 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008093 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008094
Douglas Gregore47f5a72009-10-14 23:41:34 +00008095 // C++0x [temp.explicit]p2:
8096 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008097 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00008098 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00008099 TemplateSpecializationKind TSK
8100 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8101 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008102
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008103 // C++0x [temp.explicit]p2:
8104 // [...] An explicit instantiation shall appear in an enclosing
8105 // namespace of its template. [...]
8106 //
8107 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008108 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008109
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008110 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008111 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00008112 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008113 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00008114 PrevDecl = Record;
8115 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008116 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008117 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008118 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008119 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008120 PrevDecl,
8121 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008122 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008123 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008124 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00008125 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008126 return TagD;
8127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008128
Douglas Gregor12e49d32009-10-15 22:53:21 +00008129 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008130 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008131 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00008132 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008133 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00008134 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008135 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008136 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00008137 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00008138 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8139 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00008140 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8141 << Pattern;
8142 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008143 } else {
8144 if (InstantiateClass(NameLoc, Record, Def,
8145 getTemplateInstantiationArgs(Record),
8146 TSK))
8147 return true;
8148
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008149 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00008150 if (!RecordDef)
8151 return true;
8152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008153 }
8154
Douglas Gregor1d957a32009-10-27 18:42:08 +00008155 // Instantiate all of the members of the class.
8156 InstantiateClassMembers(NameLoc, RecordDef,
8157 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008158
Douglas Gregor88d292c2010-05-13 16:44:06 +00008159 if (TSK == TSK_ExplicitInstantiationDefinition)
8160 MarkVTableUsed(NameLoc, RecordDef, true);
8161
Mike Stump87c57ac2009-05-16 07:39:55 +00008162 // FIXME: We don't have any representation for explicit instantiations of
8163 // member classes. Such a representation is not needed for compilation, but it
8164 // should be available for clients that want to see all of the declarations in
8165 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008166 return TagD;
8167}
8168
John McCallfaf5fb42010-08-26 23:41:50 +00008169DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8170 SourceLocation ExternLoc,
8171 SourceLocation TemplateLoc,
8172 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008173 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008174 // TODO: check if/when DNInfo should replace Name.
8175 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8176 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00008177 if (!Name) {
8178 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008179 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008180 diag::err_explicit_instantiation_requires_name)
8181 << D.getDeclSpec().getSourceRange()
8182 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008183
Douglas Gregor450f00842009-09-25 18:43:00 +00008184 return true;
8185 }
8186
8187 // The scope passed in may not be a decl scope. Zip up the scope tree until
8188 // we find one that is.
8189 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8190 (S->getFlags() & Scope::TemplateParamScope) != 0)
8191 S = S->getParent();
8192
8193 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00008194 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8195 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00008196 if (R.isNull())
8197 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008198
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008199 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00008200 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008201 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00008202 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008203 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8204 << Name;
8205 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008206 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008207 != DeclSpec::SCS_unspecified) {
8208 // Complain about then remove the storage class specifier.
8209 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8210 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008211
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008212 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00008213 }
8214
Douglas Gregor3c74d412009-10-14 20:14:33 +00008215 // C++0x [temp.explicit]p1:
8216 // [...] An explicit instantiation of a function template shall not use the
8217 // inline or constexpr specifiers.
8218 // Presumably, this also applies to member functions of class templates as
8219 // well.
Richard Smith83c19292011-10-18 03:44:03 +00008220 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008221 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008222 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00008223 diag::err_explicit_instantiation_inline :
8224 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00008225 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00008226 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00008227 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8228 // not already specified.
8229 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8230 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008231
Nathan Wilsonde498452016-02-08 05:34:00 +00008232 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8233 // applied only to the definition of a function template or variable template,
8234 // declared in namespace scope.
8235 if (D.getDeclSpec().isConceptSpecified()) {
8236 Diag(D.getDeclSpec().getConceptSpecLoc(),
8237 diag::err_concept_specified_specialization) << 0;
8238 return true;
8239 }
8240
Richard Smith19a311a2017-02-09 22:47:51 +00008241 // A deduction guide is not on the list of entities that can be explicitly
8242 // instantiated.
8243 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8244 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8245 << /*explicit instantiation*/ 0;
8246 return true;
8247 }
8248
Douglas Gregore47f5a72009-10-14 23:41:34 +00008249 // C++0x [temp.explicit]p2:
8250 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008251 // definition and an explicit instantiation declaration. An explicit
8252 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00008253 TemplateSpecializationKind TSK
8254 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8255 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008256
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008257 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00008258 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00008259
8260 if (!R->isFunctionType()) {
8261 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008262 // A [...] static data member of a class template can be explicitly
8263 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008264 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008265 // C++1y [temp.explicit]p1:
8266 // A [...] variable [...] template specialization can be explicitly
8267 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00008268 if (Previous.isAmbiguous())
8269 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008270
John McCall67c00872009-12-02 08:25:40 +00008271 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00008272 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008273
Larisse Voufo39a1e502013-08-06 01:03:05 +00008274 if (!PrevTemplate) {
8275 if (!Prev || !Prev->isStaticDataMember()) {
8276 // We expect to see a data data member here.
8277 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8278 << Name;
8279 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8280 P != PEnd; ++P)
8281 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8282 return true;
8283 }
8284
8285 if (!Prev->getInstantiatedFromStaticDataMember()) {
8286 // FIXME: Check for explicit specialization?
8287 Diag(D.getIdentifierLoc(),
8288 diag::err_explicit_instantiation_data_member_not_instantiated)
8289 << Prev;
8290 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8291 // FIXME: Can we provide a note showing where this was declared?
8292 return true;
8293 }
8294 } else {
8295 // Explicitly instantiate a variable template.
8296
8297 // C++1y [dcl.spec.auto]p6:
8298 // ... A program that uses auto or decltype(auto) in a context not
8299 // explicitly allowed in this section is ill-formed.
8300 //
8301 // This includes auto-typed variable template instantiations.
8302 if (R->isUndeducedType()) {
8303 Diag(T->getTypeLoc().getLocStart(),
8304 diag::err_auto_not_allowed_var_inst);
8305 return true;
8306 }
8307
Richard Smithef985ac2013-09-18 02:10:12 +00008308 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8309 // C++1y [temp.explicit]p3:
8310 // If the explicit instantiation is for a variable, the unqualified-id
8311 // in the declaration shall be a template-id.
8312 Diag(D.getIdentifierLoc(),
8313 diag::err_explicit_instantiation_without_template_id)
8314 << PrevTemplate;
8315 Diag(PrevTemplate->getLocation(),
8316 diag::note_explicit_instantiation_here);
8317 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00008318 }
8319
Nathan Wilson83839122016-04-09 02:55:27 +00008320 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8321 // explicit instantiation (14.8.2) [...] of a concept definition.
8322 if (PrevTemplate->isConcept()) {
8323 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8324 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8325 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8326 return true;
8327 }
8328
Richard Smithef985ac2013-09-18 02:10:12 +00008329 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00008330 TemplateArgumentListInfo TemplateArgs =
8331 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00008332
Larisse Voufo39a1e502013-08-06 01:03:05 +00008333 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8334 D.getIdentifierLoc(), TemplateArgs);
8335 if (Res.isInvalid())
8336 return true;
8337
8338 // Ignore access control bits, we don't need them for redeclaration
8339 // checking.
8340 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00008341 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008342
Douglas Gregore47f5a72009-10-14 23:41:34 +00008343 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008344 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008345 // or a static data member of a class template specialization, the name of
8346 // the class template specialization in the qualified-id for the member
8347 // name shall be a simple-template-id.
8348 //
8349 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008350 //
Richard Smith5977d872013-09-18 21:55:14 +00008351 // This does not apply to variable template specializations, where the
8352 // template-id is in the unqualified-id instead.
8353 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008354 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008355 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008356 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008357
Douglas Gregore47f5a72009-10-14 23:41:34 +00008358 // Check the scope of this explicit instantiation.
8359 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008360
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008361 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00008362 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8363 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008364 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008365 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00008366 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008367 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008368
Larisse Voufo39a1e502013-08-06 01:03:05 +00008369 if (!HasNoEffect) {
8370 // Instantiate static data member or variable template.
8371
8372 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8373 if (PrevTemplate) {
8374 // Merge attributes.
8375 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8376 ProcessDeclAttributeList(S, Prev, Attr);
8377 }
8378 if (TSK == TSK_ExplicitInstantiationDefinition)
8379 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8380 }
8381
8382 // Check the new variable specialization against the parsed input.
8383 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8384 Diag(T->getTypeLoc().getLocStart(),
8385 diag::err_invalid_var_template_spec_type)
8386 << 0 << PrevTemplate << R << Prev->getType();
8387 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8388 << 2 << PrevTemplate->getDeclName();
8389 return true;
8390 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008391
Douglas Gregor450f00842009-09-25 18:43:00 +00008392 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00008393 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008394 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008395
8396 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00008397 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00008398 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00008399 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00008400 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00008401 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00008402 HasExplicitTemplateArgs = true;
8403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008404
Douglas Gregor450f00842009-09-25 18:43:00 +00008405 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008406 // A [...] function [...] can be explicitly instantiated from its template.
8407 // A member function [...] of a class template can be explicitly
8408 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008409 // template.
John McCall58cc69d2010-01-27 01:50:18 +00008410 UnresolvedSet<8> Matches;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008411 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008412 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00008413 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8414 P != PEnd; ++P) {
8415 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00008416 if (!HasExplicitTemplateArgs) {
8417 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00008418 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
8419 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00008420 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00008421 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008422
John McCall58cc69d2010-01-27 01:50:18 +00008423 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008424 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8425 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00008426 }
Douglas Gregor450f00842009-09-25 18:43:00 +00008427 }
8428 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008429
Douglas Gregor450f00842009-09-25 18:43:00 +00008430 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8431 if (!FunTmpl)
8432 continue;
8433
Larisse Voufo98b20f12013-07-19 23:00:19 +00008434 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008435 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008436 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008437 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00008438 (HasExplicitTemplateArgs ? &TemplateArgs
8439 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00008440 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008441 // Keep track of almost-matches.
8442 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00008443 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008444 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008445 (void)TDK;
8446 continue;
8447 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008448
Artem Belevich64135c32016-12-08 19:38:13 +00008449 // Target attributes are part of the cuda function signature, so
8450 // the cuda target of the instantiated function must match that of its
8451 // template. Given that C++ template deduction does not take
8452 // target attributes into account, we reject candidates here that
8453 // have a different target.
8454 if (LangOpts.CUDA &&
8455 IdentifyCUDATarget(Specialization,
8456 /* IgnoreImplicitHDAttributes = */ true) !=
8457 IdentifyCUDATarget(Attr)) {
8458 FailedCandidates.addCandidate().set(
8459 P.getPair(), FunTmpl->getTemplatedDecl(),
8460 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8461 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008462 }
8463
John McCall58cc69d2010-01-27 01:50:18 +00008464 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008465 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008466
Douglas Gregor450f00842009-09-25 18:43:00 +00008467 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008468 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008469 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008470 D.getIdentifierLoc(),
8471 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8472 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8473 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008474
John McCall58cc69d2010-01-27 01:50:18 +00008475 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008476 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008477
8478 // Ignore access control bits, we don't need them for redeclaration checking.
8479 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008480
Alexey Bataev73983912014-11-06 10:10:50 +00008481 // C++11 [except.spec]p4
8482 // In an explicit instantiation an exception-specification may be specified,
8483 // but is not required.
8484 // If an exception-specification is specified in an explicit instantiation
8485 // directive, it shall be compatible with the exception-specifications of
8486 // other declarations of that function.
8487 if (auto *FPT = R->getAs<FunctionProtoType>())
8488 if (FPT->hasExceptionSpec()) {
8489 unsigned DiagID =
8490 diag::err_mismatched_exception_spec_explicit_instantiation;
8491 if (getLangOpts().MicrosoftExt)
8492 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8493 bool Result = CheckEquivalentExceptionSpec(
8494 PDiag(DiagID) << Specialization->getType(),
8495 PDiag(diag::note_explicit_instantiation_here),
8496 Specialization->getType()->getAs<FunctionProtoType>(),
8497 Specialization->getLocation(), FPT, D.getLocStart());
8498 // In Microsoft mode, mismatching exception specifications just cause a
8499 // warning.
8500 if (!getLangOpts().MicrosoftExt && Result)
8501 return true;
8502 }
8503
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008504 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008505 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008506 diag::err_explicit_instantiation_member_function_not_instantiated)
8507 << Specialization
8508 << (Specialization->getTemplateSpecializationKind() ==
8509 TSK_ExplicitSpecialization);
8510 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8511 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008512 }
8513
Douglas Gregorec9fd132012-01-14 16:38:05 +00008514 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008515 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8516 PrevDecl = Specialization;
8517
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008518 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008519 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008520 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008521 PrevDecl,
8522 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008523 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008524 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008525 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008526
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008527 // FIXME: We may still want to build some representation of this
8528 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008529 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008530 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008531 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008532
8533 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008534 if (Attr)
8535 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008536
Richard Smitheb36ddf2014-04-24 22:45:46 +00008537 if (Specialization->isDefined()) {
8538 // Let the ASTConsumer know that this function has been explicitly
8539 // instantiated now, and its linkage might have changed.
8540 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8541 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008542 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008543
Douglas Gregore47f5a72009-10-14 23:41:34 +00008544 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008545 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008546 // or a static data member of a class template specialization, the name of
8547 // the class template specialization in the qualified-id for the member
8548 // name shall be a simple-template-id.
8549 //
8550 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008551 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008552 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008553 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008554 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008555 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008556 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008557 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008558
Nathan Wilson83839122016-04-09 02:55:27 +00008559 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8560 // explicit instantiation (14.8.2) [...] of a concept definition.
8561 if (FunTmpl && FunTmpl->isConcept() &&
8562 !D.getDeclSpec().isConceptSpecified()) {
8563 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8564 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8565 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8566 return true;
8567 }
8568
Douglas Gregore47f5a72009-10-14 23:41:34 +00008569 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008570 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008571 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008572 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008573 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008574
Douglas Gregor450f00842009-09-25 18:43:00 +00008575 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008576 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008577}
8578
John McCallfaf5fb42010-08-26 23:41:50 +00008579TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008580Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8581 const CXXScopeSpec &SS, IdentifierInfo *Name,
8582 SourceLocation TagLoc, SourceLocation NameLoc) {
8583 // This has to hold, because SS is expected to be defined.
8584 assert(Name && "Expected a name in a dependent tag");
8585
Aaron Ballman4a979672014-01-03 13:56:08 +00008586 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008587 if (!NNS)
8588 return true;
8589
Abramo Bagnara6150c882010-05-11 21:36:43 +00008590 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008591
Douglas Gregorba41d012010-04-24 16:38:41 +00008592 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8593 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008594 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008595 return true;
8596 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008597
Douglas Gregore7c20652011-03-02 00:47:37 +00008598 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008599 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008600 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008601
Douglas Gregore7c20652011-03-02 00:47:37 +00008602 // Create type-source location information for this type.
8603 TypeLocBuilder TLB;
8604 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008605 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008606 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8607 TL.setNameLoc(NameLoc);
8608 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008609}
8610
John McCallfaf5fb42010-08-26 23:41:50 +00008611TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008612Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8613 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008614 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008615 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008616 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008617
Richard Smith0bf8a4922011-10-18 20:49:44 +00008618 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8619 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008620 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008621 diag::warn_cxx98_compat_typename_outside_of_template :
8622 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008623 << FixItHint::CreateRemoval(TypenameLoc);
8624
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008625 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008626 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8627 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008628 if (T.isNull())
8629 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008630
8631 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8632 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008633 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008634 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008635 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008636 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008637 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008638 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008639 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008640 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008641 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008642 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008643
John McCallba7bf592010-08-24 05:47:05 +00008644 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008645}
8646
John McCallfaf5fb42010-08-26 23:41:50 +00008647TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008648Sema::ActOnTypenameType(Scope *S,
8649 SourceLocation TypenameLoc,
8650 const CXXScopeSpec &SS,
8651 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008652 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00008653 IdentifierInfo *TemplateII,
8654 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008655 SourceLocation LAngleLoc,
8656 ASTTemplateArgsPtr TemplateArgsIn,
8657 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008658 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8659 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008660 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008661 diag::warn_cxx98_compat_typename_outside_of_template :
8662 diag::ext_typename_outside_of_template)
8663 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008664
Richard Smith74f02342017-01-19 21:00:13 +00008665 // Strangely, non-type results are not ignored by this lookup, so the
8666 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00008667 if (TypenameLoc.isValid()) {
8668 auto *LookupRD =
8669 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
8670 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
8671 Diag(TemplateIILoc,
8672 diag::ext_out_of_line_qualified_id_type_names_constructor)
8673 << TemplateII << 0 /*injected-class-name used as template name*/
8674 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
8675 }
Richard Smith74f02342017-01-19 21:00:13 +00008676 }
8677
Douglas Gregorb09518c2011-02-27 22:46:49 +00008678 // Translate the parser's template argument list in our AST format.
8679 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8680 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008681
Douglas Gregorb09518c2011-02-27 22:46:49 +00008682 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008683 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8684 // Construct a dependent template specialization type.
8685 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008686 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008687 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8688 DTN->getQualifier(),
8689 DTN->getIdentifier(),
8690 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008691
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008692 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008693 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008694 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008695 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008696 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8697 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008698 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00008699 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008700 SpecTL.setLAngleLoc(LAngleLoc);
8701 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008702 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8703 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008704 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008705 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00008706
Richard Smith74f02342017-01-19 21:00:13 +00008707 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008708 if (T.isNull())
8709 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008710
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008711 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008712 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008713 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008714 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008715 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00008716 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008717 SpecTL.setLAngleLoc(LAngleLoc);
8718 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008719 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8720 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008721
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008722 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8723 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008724 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008725 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00008726
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008727 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8728 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008729}
8730
Douglas Gregorb09518c2011-02-27 22:46:49 +00008731
Richard Smith6f8d2c62012-05-09 05:17:00 +00008732/// Determine whether this failed name lookup should be treated as being
8733/// disabled by a usage of std::enable_if.
8734static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8735 SourceRange &CondRange) {
8736 // We must be looking for a ::type...
8737 if (!II.isStr("type"))
8738 return false;
8739
8740 // ... within an explicitly-written template specialization...
8741 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8742 return false;
8743 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008744 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8745 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8746 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008747 return false;
8748 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008749 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008750
8751 // ... which names a complete class template declaration...
8752 const TemplateDecl *EnableIfDecl =
8753 EnableIfTST->getTemplateName().getAsTemplateDecl();
8754 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8755 return false;
8756
8757 // ... called "enable_if".
8758 const IdentifierInfo *EnableIfII =
8759 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8760 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8761 return false;
8762
8763 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008764 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008765 return true;
8766}
8767
Douglas Gregor333489b2009-03-27 23:10:48 +00008768/// \brief Build the type that describes a C++ typename specifier,
8769/// e.g., "typename T::type".
8770QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00008771Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008772 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00008773 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008774 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008775 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008776 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008777 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008778
John McCall0b66eb32010-05-01 00:40:08 +00008779 DeclContext *Ctx = computeDeclContext(SS);
8780 if (!Ctx) {
8781 // If the nested-name-specifier is dependent and couldn't be
8782 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008783 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008784 return Context.getDependentNameType(Keyword,
8785 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008786 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008787 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008788
John McCall0b66eb32010-05-01 00:40:08 +00008789 // If the nested-name-specifier refers to the current instantiation,
8790 // the "typename" keyword itself is superfluous. In C++03, the
8791 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8792 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008793 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008794
John McCall0b66eb32010-05-01 00:40:08 +00008795 if (RequireCompleteDeclContext(SS, Ctx))
8796 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008797
8798 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008799 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008800 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008801 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008802 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008803 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008804 case LookupResult::NotFound: {
8805 // If we're looking up 'type' within a template named 'enable_if', produce
8806 // a more specific diagnostic.
8807 SourceRange CondRange;
8808 if (isEnableIf(QualifierLoc, II, CondRange)) {
8809 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8810 << Ctx << CondRange;
8811 return QualType();
8812 }
8813
Douglas Gregore40876a2009-10-13 21:16:44 +00008814 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008815 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008816 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008817
8818 case LookupResult::FoundUnresolvedValue: {
8819 // We found a using declaration that is a value. Most likely, the using
8820 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008821 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008822 IILoc);
8823 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8824 << Name << Ctx << FullRange;
8825 if (UnresolvedUsingValueDecl *Using
8826 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008827 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008828 Diag(Loc, diag::note_using_value_decl_missing_typename)
8829 << FixItHint::CreateInsertion(Loc, "typename ");
8830 }
8831 }
8832 // Fall through to create a dependent typename type, from which we can recover
8833 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008834
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008835 case LookupResult::NotFoundInCurrentInstantiation:
8836 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00008837 return Context.getDependentNameType(Keyword,
8838 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008839 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008840
8841 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008842 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00008843 // C++ [class.qual]p2:
8844 // In a lookup in which function names are not ignored and the
8845 // nested-name-specifier nominates a class C, if the name specified
8846 // after the nested-name-specifier, when looked up in C, is the
8847 // injected-class-name of C [...] then the name is instead considered
8848 // to name the constructor of class C.
8849 //
8850 // Unlike in an elaborated-type-specifier, function names are not ignored
8851 // in typename-specifier lookup. However, they are ignored in all the
8852 // contexts where we form a typename type with no keyword (that is, in
8853 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
8854 //
8855 // FIXME: That's not strictly true: mem-initializer-id lookup does not
8856 // ignore functions, but that appears to be an oversight.
8857 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
8858 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
8859 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
8860 FoundRD->isInjectedClassName() &&
8861 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
8862 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
8863 << &II << 1 << 0 /*'typename' keyword used*/;
8864
Abramo Bagnara6150c882010-05-11 21:36:43 +00008865 // We found a type. Build an ElaboratedType, since the
8866 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008867 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00008868 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008869 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008870 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008871 }
8872
Richard Smithee579842017-01-30 20:39:26 +00008873 // C++ [dcl.type.simple]p2:
8874 // A type-specifier of the form
8875 // typename[opt] nested-name-specifier[opt] template-name
8876 // is a placeholder for a deduced class type [...].
8877 if (getLangOpts().CPlusPlus1z) {
8878 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
8879 return Context.getElaboratedType(
8880 Keyword, QualifierLoc.getNestedNameSpecifier(),
8881 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
8882 QualType(), false));
8883 }
8884 }
Richard Smith600b5262017-01-26 20:40:47 +00008885
Douglas Gregor333489b2009-03-27 23:10:48 +00008886 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008887 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008888 break;
8889
8890 case LookupResult::FoundOverloaded:
8891 DiagID = diag::err_typename_nested_not_type;
8892 Referenced = *Result.begin();
8893 break;
8894
John McCall6538c932009-10-10 05:48:19 +00008895 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008896 return QualType();
8897 }
8898
8899 // If we get here, it's because name lookup did not find a
8900 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008901 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008902 IILoc);
8903 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008904 if (Referenced)
8905 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8906 << Name;
8907 return QualType();
8908}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008909
8910namespace {
8911 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008912 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008913 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008914 SourceLocation Loc;
8915 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008916
Douglas Gregor15acfb92009-08-06 16:20:37 +00008917 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008918 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008919
Mike Stump11289f42009-09-09 15:08:12 +00008920 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008921 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008922 DeclarationName Entity)
8923 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008924 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008925
8926 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008927 /// transformed.
8928 ///
8929 /// For the purposes of type reconstruction, a type has already been
8930 /// transformed if it is NULL or if it is not dependent.
8931 bool AlreadyTransformed(QualType T) {
8932 return T.isNull() || !T->isDependentType();
8933 }
Mike Stump11289f42009-09-09 15:08:12 +00008934
8935 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008936 /// rebuilt.
8937 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008938
Douglas Gregor15acfb92009-08-06 16:20:37 +00008939 /// \brief Returns the name of the entity whose type is being rebuilt.
8940 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008941
Douglas Gregoref6ab412009-10-27 06:26:26 +00008942 /// \brief Sets the "base" location and entity when that
8943 /// information is known based on another transformation.
8944 void setBase(SourceLocation Loc, DeclarationName Entity) {
8945 this->Loc = Loc;
8946 this->Entity = Entity;
8947 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00008948
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008949 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8950 // Lambdas never need to be transformed.
8951 return E;
8952 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008953 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008954} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008955
Douglas Gregor15acfb92009-08-06 16:20:37 +00008956/// \brief Rebuilds a type within the context of the current instantiation.
8957///
Mike Stump11289f42009-09-09 15:08:12 +00008958/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008959/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008960/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008961/// partial specialization thereof). This routine will rebuild that type now
8962/// that we have entered the declarator's scope, which may produce different
8963/// canonical types, e.g.,
8964///
8965/// \code
8966/// template<typename T>
8967/// struct X {
8968/// typedef T* pointer;
8969/// pointer data();
8970/// };
8971///
8972/// template<typename T>
8973/// typename X<T>::pointer X<T>::data() { ... }
8974/// \endcode
8975///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008976/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008977/// since we do not know that we can look into X<T> when we parsed the type.
8978/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008979/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008980/// as the canonical type of T*, allowing the return types of the out-of-line
8981/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008982TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8983 SourceLocation Loc,
8984 DeclarationName Name) {
8985 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008986 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008987
Douglas Gregor15acfb92009-08-06 16:20:37 +00008988 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8989 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008990}
Douglas Gregorbe999392009-09-15 16:23:51 +00008991
John McCalldadc5752010-08-24 06:29:42 +00008992ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008993 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8994 DeclarationName());
8995 return Rebuilder.TransformExpr(E);
8996}
8997
John McCall99b2fe52010-04-29 23:50:39 +00008998bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00008999 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009000 return true;
John McCall2408e322010-04-27 00:57:59 +00009001
Douglas Gregor10176412011-02-25 16:07:42 +00009002 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009003 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9004 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009005 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009006 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009007 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009008 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009009
Douglas Gregor10176412011-02-25 16:07:42 +00009010 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009011 return false;
John McCall2408e322010-04-27 00:57:59 +00009012}
9013
Douglas Gregor041b0842011-10-14 15:31:12 +00009014/// \brief Rebuild the template parameters now that we know we're in a current
9015/// instantiation.
9016bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9017 TemplateParameterList *Params) {
9018 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9019 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009020
Douglas Gregor041b0842011-10-14 15:31:12 +00009021 // There is nothing to rebuild in a type parameter.
9022 if (isa<TemplateTypeParmDecl>(Param))
9023 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009024
Douglas Gregor041b0842011-10-14 15:31:12 +00009025 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009026 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009027 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9028 if (RebuildTemplateParamsInCurrentInstantiation(
9029 TTP->getTemplateParameters()))
9030 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009031
Douglas Gregor041b0842011-10-14 15:31:12 +00009032 continue;
9033 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009034
Douglas Gregor041b0842011-10-14 15:31:12 +00009035 // Rebuild the type of a non-type template parameter.
9036 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009037 TypeSourceInfo *NewTSI
9038 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9039 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009040 NTTP->getDeclName());
9041 if (!NewTSI)
9042 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009043
Douglas Gregor041b0842011-10-14 15:31:12 +00009044 if (NewTSI != NTTP->getTypeSourceInfo()) {
9045 NTTP->setTypeSourceInfo(NewTSI);
9046 NTTP->setType(NewTSI->getType());
9047 }
9048 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009049
Douglas Gregor041b0842011-10-14 15:31:12 +00009050 return false;
9051}
9052
Douglas Gregorbe999392009-09-15 16:23:51 +00009053/// \brief Produces a formatted string that describes the binding of
9054/// template parameters to template arguments.
9055std::string
9056Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9057 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009058 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00009059}
9060
9061std::string
9062Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9063 const TemplateArgument *Args,
9064 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009065 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00009066 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00009067
Douglas Gregore62e6a02009-11-11 19:13:48 +00009068 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009069 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009070
Douglas Gregorbe999392009-09-15 16:23:51 +00009071 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00009072 if (I >= NumArgs)
9073 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009074
Douglas Gregorbe999392009-09-15 16:23:51 +00009075 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009076 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00009077 else
Douglas Gregor0192c232010-12-20 16:52:59 +00009078 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009079
Douglas Gregorbe999392009-09-15 16:23:51 +00009080 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00009081 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00009082 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00009083 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00009084 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009085
Douglas Gregor0192c232010-12-20 16:52:59 +00009086 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00009087 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00009088 }
Douglas Gregor0192c232010-12-20 16:52:59 +00009089
9090 Out << ']';
9091 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00009092}
Francois Pichet1c229c02011-04-22 22:18:13 +00009093
Richard Smithe40f2ba2013-08-07 21:41:30 +00009094void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9095 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00009096 if (!FD)
9097 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00009098
Justin Lebar28f09c52016-10-10 16:26:08 +00009099 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00009100
9101 // Take tokens to avoid allocations
9102 LPT->Toks.swap(Toks);
9103 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00009104 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00009105
9106 FD->setLateTemplateParsed(true);
9107}
9108
9109void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9110 if (!FD)
9111 return;
9112 FD->setLateTemplateParsed(false);
9113}
Francois Pichet1c229c02011-04-22 22:18:13 +00009114
9115bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9116 DeclContext *DC = CurContext;
9117
9118 while (DC) {
9119 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9120 const FunctionDecl *FD = RD->isLocalClass();
9121 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9122 } else if (DC->isTranslationUnit() || DC->isNamespace())
9123 return false;
9124
9125 DC = DC->getParent();
9126 }
9127 return false;
9128}
Richard Smith6739a102016-05-05 00:56:12 +00009129
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009130namespace {
Richard Smith6739a102016-05-05 00:56:12 +00009131/// \brief Walk the path from which a declaration was instantiated, and check
9132/// that every explicit specialization along that path is visible. This enforces
9133/// C++ [temp.expl.spec]/6:
9134///
9135/// If a template, a member template or a member of a class template is
9136/// explicitly specialized then that specialization shall be declared before
9137/// the first use of that specialization that would cause an implicit
9138/// instantiation to take place, in every translation unit in which such a
9139/// use occurs; no diagnostic is required.
9140///
9141/// and also C++ [temp.class.spec]/1:
9142///
9143/// A partial specialization shall be declared before the first use of a
9144/// class template specialization that would make use of the partial
9145/// specialization as the result of an implicit or explicit instantiation
9146/// in every translation unit in which such a use occurs; no diagnostic is
9147/// required.
9148class ExplicitSpecializationVisibilityChecker {
9149 Sema &S;
9150 SourceLocation Loc;
9151 llvm::SmallVector<Module *, 8> Modules;
9152
9153public:
9154 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9155 : S(S), Loc(Loc) {}
9156
9157 void check(NamedDecl *ND) {
9158 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9159 return checkImpl(FD);
9160 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9161 return checkImpl(RD);
9162 if (auto *VD = dyn_cast<VarDecl>(ND))
9163 return checkImpl(VD);
9164 if (auto *ED = dyn_cast<EnumDecl>(ND))
9165 return checkImpl(ED);
9166 }
9167
9168private:
9169 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9170 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9171 : Sema::MissingImportKind::ExplicitSpecialization;
9172 const bool Recover = true;
9173
9174 // If we got a custom set of modules (because only a subset of the
9175 // declarations are interesting), use them, otherwise let
9176 // diagnoseMissingImport intelligently pick some.
9177 if (Modules.empty())
9178 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9179 else
9180 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9181 }
9182
9183 // Check a specific declaration. There are three problematic cases:
9184 //
9185 // 1) The declaration is an explicit specialization of a template
9186 // specialization.
9187 // 2) The declaration is an explicit specialization of a member of an
9188 // templated class.
9189 // 3) The declaration is an instantiation of a template, and that template
9190 // is an explicit specialization of a member of a templated class.
9191 //
9192 // We don't need to go any deeper than that, as the instantiation of the
9193 // surrounding class / etc is not triggered by whatever triggered this
9194 // instantiation, and thus should be checked elsewhere.
9195 template<typename SpecDecl>
9196 void checkImpl(SpecDecl *Spec) {
9197 bool IsHiddenExplicitSpecialization = false;
9198 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9199 IsHiddenExplicitSpecialization =
9200 Spec->getMemberSpecializationInfo()
9201 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9202 : !S.hasVisibleDeclaration(Spec);
9203 } else {
9204 checkInstantiated(Spec);
9205 }
9206
9207 if (IsHiddenExplicitSpecialization)
9208 diagnose(Spec->getMostRecentDecl(), false);
9209 }
9210
9211 void checkInstantiated(FunctionDecl *FD) {
9212 if (auto *TD = FD->getPrimaryTemplate())
9213 checkTemplate(TD);
9214 }
9215
9216 void checkInstantiated(CXXRecordDecl *RD) {
9217 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9218 if (!SD)
9219 return;
9220
9221 auto From = SD->getSpecializedTemplateOrPartial();
9222 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9223 checkTemplate(TD);
9224 else if (auto *TD =
9225 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9226 if (!S.hasVisibleDeclaration(TD))
9227 diagnose(TD, true);
9228 checkTemplate(TD);
9229 }
9230 }
9231
9232 void checkInstantiated(VarDecl *RD) {
9233 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9234 if (!SD)
9235 return;
9236
9237 auto From = SD->getSpecializedTemplateOrPartial();
9238 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9239 checkTemplate(TD);
9240 else if (auto *TD =
9241 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9242 if (!S.hasVisibleDeclaration(TD))
9243 diagnose(TD, true);
9244 checkTemplate(TD);
9245 }
9246 }
9247
9248 void checkInstantiated(EnumDecl *FD) {}
9249
9250 template<typename TemplDecl>
9251 void checkTemplate(TemplDecl *TD) {
9252 if (TD->isMemberSpecialization()) {
9253 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9254 diagnose(TD->getMostRecentDecl(), false);
9255 }
9256 }
9257};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009258} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00009259
9260void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
9261 if (!getLangOpts().Modules)
9262 return;
9263
9264 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9265}
9266
9267/// \brief Check whether a template partial specialization that we've discovered
9268/// is hidden, and produce suitable diagnostics if so.
9269void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
9270 NamedDecl *Spec) {
9271 llvm::SmallVector<Module *, 8> Modules;
9272 if (!hasVisibleDeclaration(Spec, &Modules))
9273 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9274 MissingImportKind::PartialSpecialization,
9275 /*Recover*/true);
9276}