blob: 9d3bf1c1605d9636aae772597a4b1d74577d2fca [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
Douglas Gregor5101c242008-12-05 18:15:24 +000036using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000038
John McCall9b72f892010-11-10 02:40:36 +000039// Exported for use by Parser.
40SourceRange
41clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
42 unsigned N) {
43 if (!N) return SourceRange();
44 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
45}
46
Douglas Gregorb7bfe792009-09-02 22:59:36 +000047/// \brief Determine whether the declaration found is acceptable as the name
48/// of a template and, if so, return that template declaration. Otherwise,
49/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000050static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000051 NamedDecl *Orig,
52 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000053 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000054
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000055 if (isa<TemplateDecl>(D)) {
56 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000057 return nullptr;
58
John McCalle9cccd82010-06-16 08:42:20 +000059 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000060 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
63 // C++ [temp.local]p1:
64 // Like normal (non-template) classes, class templates have an
65 // injected-class-name (Clause 9). The injected-class-name
66 // can be used with or without a template-argument-list. When
67 // it is used without a template-argument-list, it is
68 // equivalent to the injected-class-name followed by the
69 // template-parameters of the class template enclosed in
70 // <>. When it is used with a template-argument-list, it
71 // refers to the specified class template specialization,
72 // which could be the current specialization or another
73 // specialization.
74 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000075 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000076 if (Record->getDescribedClassTemplate())
77 return Record->getDescribedClassTemplate();
78
79 if (ClassTemplateSpecializationDecl *Spec
80 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
81 return Spec->getSpecializedTemplate();
82 }
Mike Stump11289f42009-09-09 15:08:12 +000083
Craig Topperc3ec1492014-05-26 06:22:03 +000084 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000085 }
Mike Stump11289f42009-09-09 15:08:12 +000086
Craig Topperc3ec1492014-05-26 06:22:03 +000087 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000088}
89
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000090void Sema::FilterAcceptableTemplateNames(LookupResult &R,
91 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +000092 // The set of class templates we've already seen.
93 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000094 LookupResult::Filter filter = R.makeFilter();
95 while (filter.hasNext()) {
96 NamedDecl *Orig = filter.next();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000097 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
98 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +000099 if (!Repl)
100 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000101 else if (Repl != Orig) {
102
103 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000104 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000105 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000106 // one base class). If all of the injected-class-names that are found
107 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000108 // is used as a template-name, the reference refers to the class
109 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000110 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000111 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000112 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000113 filter.erase();
114 continue;
115 }
John McCallbd8062d2010-08-13 07:02:08 +0000116
117 // FIXME: we promote access to public here as a workaround to
118 // the fact that LookupResult doesn't let us remember that we
119 // found this template through a particular injected class name,
120 // which means we end up doing nasty things to the invariants.
121 // Pretending that access is public is *much* safer.
122 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000123 }
John McCalle66edc12009-11-24 19:00:30 +0000124 }
125 filter.done();
126}
127
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000128bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
129 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000130 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000131 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000132 return true;
133
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000134 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000135}
136
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000137TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000138 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000139 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000140 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000141 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000142 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000143 TemplateTy &TemplateResult,
144 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000145 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000146
Douglas Gregor3cf81312009-11-03 23:16:33 +0000147 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000148 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000149
Douglas Gregor3cf81312009-11-03 23:16:33 +0000150 switch (Name.getKind()) {
151 case UnqualifiedId::IK_Identifier:
152 TName = DeclarationName(Name.Identifier);
153 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000154
Douglas Gregor3cf81312009-11-03 23:16:33 +0000155 case UnqualifiedId::IK_OperatorFunctionId:
156 TName = Context.DeclarationNames.getCXXOperatorName(
157 Name.OperatorFunctionId.Operator);
158 break;
159
Alexis Hunted0530f2009-11-28 08:58:14 +0000160 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000161 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
162 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000163
Douglas Gregor3cf81312009-11-03 23:16:33 +0000164 default:
165 return TNK_Non_template;
166 }
Mike Stump11289f42009-09-09 15:08:12 +0000167
John McCallba7bf592010-08-24 05:47:05 +0000168 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000169
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000170 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000171 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
172 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000173 if (R.empty()) return TNK_Non_template;
174 if (R.isAmbiguous()) {
175 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000176 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000177
178 // FIXME: we might have ambiguous templates, in which case we
179 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000180 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000181 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000182
John McCalld28ae272009-12-02 08:04:21 +0000183 TemplateName Template;
184 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000185
John McCalld28ae272009-12-02 08:04:21 +0000186 unsigned ResultCount = R.end() - R.begin();
187 if (ResultCount > 1) {
188 // We assume that we'll preserve the qualifier from a function
189 // template name in other ways.
190 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
191 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000192
193 // We'll do this lookup again later.
194 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000195 } else {
John McCalld28ae272009-12-02 08:04:21 +0000196 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
197
198 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000199 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000200 Template = Context.getQualifiedTemplateName(Qualifier,
201 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000202 } else {
203 Template = TemplateName(TD);
204 }
205
John McCalldcc71402010-08-13 02:23:42 +0000206 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000207 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000208
209 // We'll do this lookup again later.
210 R.suppressDiagnostics();
211 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000212 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000213 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
214 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000215 TemplateKind =
216 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000217 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000218 }
Mike Stump11289f42009-09-09 15:08:12 +0000219
John McCalld28ae272009-12-02 08:04:21 +0000220 TemplateResult = TemplateTy::make(Template);
221 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000222}
223
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000225 SourceLocation IILoc,
226 Scope *S,
227 const CXXScopeSpec *SS,
228 TemplateTy &SuggestedTemplate,
229 TemplateNameKind &SuggestedKind) {
230 // We can't recover unless there's a dependent scope specifier preceding the
231 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000232 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000233 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
234 computeDeclContext(*SS))
235 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Douglas Gregor18473f32010-01-12 21:28:44 +0000237 // The code is missing a 'template' keyword prior to the dependent template
238 // name.
239 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
240 Diag(IILoc, diag::err_template_kw_missing)
241 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000242 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000243 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000244 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
245 SuggestedKind = TNK_Dependent_template_name;
246 return true;
247}
248
John McCalle66edc12009-11-24 19:00:30 +0000249void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000250 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000251 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000252 bool EnteringContext,
253 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000254 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000255 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000256 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000257 bool isDependent = false;
258 if (!ObjectType.isNull()) {
259 // This nested-name-specifier occurs in a member access expression, e.g.,
260 // x->B::f, and we are looking into the type of the object.
261 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
262 LookupCtx = computeDeclContext(ObjectType);
263 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000264 assert((isDependent || !ObjectType->isIncompleteType() ||
265 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000266 "Caller should have completed object type");
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000267
268 // Template names cannot appear inside an Objective-C class or object type.
269 if (ObjectType->isObjCObjectOrInterfaceType()) {
270 Found.clear();
271 return;
272 }
John McCalle66edc12009-11-24 19:00:30 +0000273 } else if (SS.isSet()) {
274 // This nested-name-specifier occurs after another nested-name-specifier,
275 // so long into the context associated with the prior nested-name-specifier.
276 LookupCtx = computeDeclContext(SS, EnteringContext);
277 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278
John McCalle66edc12009-11-24 19:00:30 +0000279 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000280 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000281 return;
282 }
283
284 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000285 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000286 if (LookupCtx) {
287 // Perform "qualified" name lookup into the declaration context we
288 // computed, which is either the type of the base of a member access
289 // expression or the declaration context associated with a prior
290 // nested-name-specifier.
291 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000292 if (!ObjectType.isNull() && Found.empty()) {
293 // C++ [basic.lookup.classref]p1:
294 // In a class member access expression (5.2.5), if the . or -> token is
295 // immediately followed by an identifier followed by a <, the
296 // identifier must be looked up to determine whether the < is the
297 // beginning of a template argument list (14.2) or a less-than operator.
298 // The identifier is first looked up in the class of the object
299 // expression. If the identifier is not found, it is then looked up in
300 // the context of the entire postfix-expression and shall name a class
301 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000302 if (S) LookupName(Found, S);
303 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000304 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000305 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000306 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000307 // We cannot look into a dependent object type or nested nme
308 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000309 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000310 return;
311 } else {
312 // Perform unqualified name lookup in the current scope.
313 LookupName(Found, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000314
315 if (!ObjectType.isNull())
316 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000317 }
318
Douglas Gregorc119dd52010-01-12 17:06:20 +0000319 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000320 // If we did not find any names, attempt to correct any typos.
321 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000322 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000323 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000324 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
325 FilterCCC->WantTypeSpecifiers = false;
326 FilterCCC->WantExpressionKeywords = false;
327 FilterCCC->WantRemainingKeywords = false;
328 FilterCCC->WantCXXNamedCasts = true;
329 if (TypoCorrection Corrected = CorrectTypo(
330 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
331 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000332 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000333 if (auto *ND = Corrected.getFoundDecl())
334 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000335 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000336 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000337 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000338 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
339 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000340 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000341 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
342 << Name << LookupCtx << DroppedSpecifier
343 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000344 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000345 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000346 }
John McCalle9cccd82010-06-16 08:42:20 +0000347 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000348 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000349 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000350 }
351 }
352
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000353 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000354 if (Found.empty()) {
355 if (isDependent)
356 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000357 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000358 }
John McCalle66edc12009-11-24 19:00:30 +0000359
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000360 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000361 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000362 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000363 // [...] If the lookup in the class of the object expression finds a
364 // template, the name is also looked up in the context of the entire
365 // postfix-expression and [...]
366 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000367 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000368 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
369 LookupOrdinaryName);
370 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000371 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000372
John McCalle66edc12009-11-24 19:00:30 +0000373 if (FoundOuter.empty()) {
374 // - if the name is not found, the name found in the class of the
375 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000376 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
377 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000378 // - if the name is found in the context of the entire
379 // postfix-expression and does not name a class template, the name
380 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000381 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000382 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000383 // - if the name found is a class template, it must refer to the same
384 // entity as the one found in the class of the object expression,
385 // otherwise the program is ill-formed.
386 if (!Found.isSingleResult() ||
387 Found.getFoundDecl()->getCanonicalDecl()
388 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000390 diag::ext_nested_name_member_ref_lookup_ambiguous)
391 << Found.getLookupName()
392 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000393 Diag(Found.getRepresentativeDecl()->getLocation(),
394 diag::note_ambig_member_ref_object_type)
395 << ObjectType;
396 Diag(FoundOuter.getFoundDecl()->getLocation(),
397 diag::note_ambig_member_ref_scope);
398
399 // Recover by taking the template that we found in the object
400 // expression's type.
401 }
402 }
403 }
404}
405
John McCallcd4b4772009-12-02 03:53:29 +0000406/// ActOnDependentIdExpression - Handle a dependent id-expression that
407/// was just parsed. This is only possible with an explicit scope
408/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000409ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000410Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000411 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000412 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000413 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000414 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000415 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000416
Reid Kleckner1af391df2016-03-11 18:59:12 +0000417 // C++11 [expr.prim.general]p12:
418 // An id-expression that denotes a non-static data member or non-static
419 // member function of a class can only be used:
420 // (...)
421 // - if that id-expression denotes a non-static data member and it
422 // appears in an unevaluated operand.
423 //
424 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
425 // CXXDependentScopeMemberExpr. The former can instantiate to either
426 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
427 // always a MemberExpr.
428 bool MightBeCxx11UnevalField =
429 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
430
431 if (!MightBeCxx11UnevalField && !isAddressOfOperand &&
432 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000433 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434
John McCalle66edc12009-11-24 19:00:30 +0000435 // Since the 'this' expression is synthesized, we don't need to
436 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000437 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000438
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000439 return CXXDependentScopeMemberExpr::Create(
440 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
441 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
442 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000443 }
444
Abramo Bagnara7945c982012-01-27 09:46:47 +0000445 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000446}
447
John McCalldadc5752010-08-24 06:29:42 +0000448ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000449Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000450 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000451 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000452 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000453 return DependentScopeDeclRefExpr::Create(
454 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
455 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000456}
457
Douglas Gregor5101c242008-12-05 18:15:24 +0000458/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
459/// that the template parameter 'PrevDecl' is being shadowed by a new
460/// declaration at location Loc. Returns true to indicate that this is
461/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000462void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000463 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000464
465 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000466 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000467 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000468
469 // C++ [temp.local]p4:
470 // A template-parameter shall not be redeclared within its
471 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000472 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000473 << cast<NamedDecl>(PrevDecl)->getDeclName();
474 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000475}
476
Douglas Gregor463421d2009-03-03 04:44:36 +0000477/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000478/// the parameter D to reference the templated declaration and return a pointer
479/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000480TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
481 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
482 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000483 return Temp;
484 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000485 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000486}
487
Douglas Gregoreb29d182011-01-05 17:40:24 +0000488ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
489 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000490 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000491 "Only template template arguments can be pack expansions here");
492 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
493 "Template template argument pack expansion without packs");
494 ParsedTemplateArgument Result(*this);
495 Result.EllipsisLoc = EllipsisLoc;
496 return Result;
497}
498
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000499static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
500 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000502 switch (Arg.getKind()) {
503 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000504 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000505 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000506 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000507 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000508 return TemplateArgumentLoc(TemplateArgument(T), DI);
509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000510
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000511 case ParsedTemplateArgument::NonType: {
512 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
513 return TemplateArgumentLoc(TemplateArgument(E), E);
514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000515
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000516 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000517 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000518 TemplateArgument TArg;
519 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000520 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000521 else
522 TArg = Template;
523 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000524 Arg.getScopeSpec().getWithLocInContext(
525 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000526 Arg.getLocation(),
527 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000528 }
529 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000530
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000531 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000532}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000534/// \brief Translates template arguments as provided by the parser
535/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000536void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
537 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000538 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000539 TemplateArgs.addArgument(translateTemplateArgument(*this,
540 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000541}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000542
Richard Smithb80d5402013-06-25 22:21:36 +0000543static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
544 SourceLocation Loc,
545 IdentifierInfo *Name) {
546 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
547 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
548 if (PrevDecl && PrevDecl->isTemplateParameter())
549 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
550}
551
Douglas Gregor5101c242008-12-05 18:15:24 +0000552/// ActOnTypeParameter - Called when a C++ template type parameter
553/// (e.g., "typename T") has been parsed. Typename specifies whether
554/// the keyword "typename" was used to declare the type parameter
555/// (otherwise, "class" was used), and KeyLoc is the location of the
556/// "class" or "typename" keyword. ParamName is the name of the
557/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000558/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000559/// If the type parameter has a default argument, it will be added
560/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000561Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000562 SourceLocation EllipsisLoc,
563 SourceLocation KeyLoc,
564 IdentifierInfo *ParamName,
565 SourceLocation ParamNameLoc,
566 unsigned Depth, unsigned Position,
567 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000568 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000569 assert(S->isTemplateParamScope() &&
570 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000571
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000572 SourceLocation Loc = ParamNameLoc;
573 if (!ParamName)
574 Loc = KeyLoc;
575
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000576 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000577 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000578 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000579 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000580 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000581 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000582
583 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000584 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
585
Douglas Gregor5101c242008-12-05 18:15:24 +0000586 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000587 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000588 IdResolver.AddDecl(Param);
589 }
590
Douglas Gregorf5500772011-01-05 15:48:55 +0000591 // C++0x [temp.param]p9:
592 // A default template-argument may be specified for any kind of
593 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000594 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000595 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000596 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000597 }
598
Douglas Gregordc13ded2010-07-01 00:00:45 +0000599 // Handle the default argument, if provided.
600 if (DefaultArg) {
601 TypeSourceInfo *DefaultTInfo;
602 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000603
Douglas Gregordc13ded2010-07-01 00:00:45 +0000604 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000606 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000608 UPPC_DefaultArgument))
609 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610
Douglas Gregordc13ded2010-07-01 00:00:45 +0000611 // Check the template argument itself.
612 if (CheckTemplateArgument(Param, DefaultTInfo)) {
613 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000614 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000615 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Richard Smith1469b912015-06-10 00:29:03 +0000617 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
John McCall48871652010-08-21 09:40:31 +0000620 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000621}
622
Douglas Gregor463421d2009-03-03 04:44:36 +0000623/// \brief Check that the type of a non-type template parameter is
624/// well-formed.
625///
626/// \returns the (possibly-promoted) parameter type if valid;
627/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000628QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000629Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000630 // We don't allow variably-modified types as the type of non-type template
631 // parameters.
632 if (T->isVariablyModifiedType()) {
633 Diag(Loc, diag::err_variably_modified_nontype_template_param)
634 << T;
635 return QualType();
636 }
637
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 // C++ [temp.param]p4:
639 //
640 // A non-type template-parameter shall have one of the following
641 // (optionally cv-qualified) types:
642 //
643 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000644 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000645 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000646 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000647 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000648 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000649 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000650 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000651 // -- std::nullptr_t.
652 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000653 // If T is a dependent type, we can't do the check now, so we
654 // assume that it is well-formed.
Richard Smithd0e1c952012-03-13 07:21:50 +0000655 T->isDependentType()) {
656 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
657 // are ignored when determining its type.
658 return T.getUnqualifiedType();
659 }
660
Douglas Gregor463421d2009-03-03 04:44:36 +0000661 // C++ [temp.param]p8:
662 //
663 // A non-type template-parameter of type "array of T" or
664 // "function returning T" is adjusted to be of type "pointer to
665 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000666 else if (T->isArrayType() || T->isFunctionType())
667 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000668
Douglas Gregor463421d2009-03-03 04:44:36 +0000669 Diag(Loc, diag::err_template_nontype_parm_bad_type)
670 << T;
671
672 return QualType();
673}
674
John McCall48871652010-08-21 09:40:31 +0000675Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
676 unsigned Depth,
677 unsigned Position,
678 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000679 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000680 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
681 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000682
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000683 assert(S->isTemplateParamScope() &&
684 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000685 bool Invalid = false;
686
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000687 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
688 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000689 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000690 Invalid = true;
691 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000692
Richard Smithb80d5402013-06-25 22:21:36 +0000693 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000694 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000695 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000696 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000697 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000698 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000700 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000701 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000702
Douglas Gregor5101c242008-12-05 18:15:24 +0000703 if (Invalid)
704 Param->setInvalidDecl();
705
Richard Smithb80d5402013-06-25 22:21:36 +0000706 if (ParamName) {
707 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
708 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 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
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.
718 if (Default && IsParameterPack) {
719 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000720 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000721 }
722
Douglas Gregordc13ded2010-07-01 00:00:45 +0000723 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000724 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000725 // Check for unexpanded parameter packs.
726 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
727 return Param;
728
Douglas Gregordc13ded2010-07-01 00:00:45 +0000729 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000730 ExprResult DefaultRes =
731 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000732 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000733 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000734 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000735 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000736 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000737
Richard Smith1469b912015-06-10 00:29:03 +0000738 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000740
John McCall48871652010-08-21 09:40:31 +0000741 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000742}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000743
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000744/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000745/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000746/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000747Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
748 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000749 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000750 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000751 IdentifierInfo *Name,
752 SourceLocation NameLoc,
753 unsigned Depth,
754 unsigned Position,
755 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000756 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000757 assert(S->isTemplateParamScope() &&
758 "Template template parameter not in template parameter scope!");
759
760 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000761 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000762 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000763 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764 NameLoc.isInvalid()? TmpLoc : NameLoc,
765 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000766 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000767 Param->setAccess(AS_public);
768
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000770 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000771 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000772 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
773
John McCall48871652010-08-21 09:40:31 +0000774 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000775 IdResolver.AddDecl(Param);
776 }
777
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000778 if (Params->size() == 0) {
779 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
780 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
781 Param->setInvalidDecl();
782 }
783
Douglas Gregorf5500772011-01-05 15:48:55 +0000784 // C++0x [temp.param]p9:
785 // A default template-argument may be specified for any kind of
786 // template-parameter that is not a template parameter pack.
787 if (IsParameterPack && !Default.isInvalid()) {
788 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
789 Default = ParsedTemplateArgument();
790 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000791
Douglas Gregordc13ded2010-07-01 00:00:45 +0000792 if (!Default.isInvalid()) {
793 // Check only that we have a template template argument. We don't want to
794 // try to check well-formedness now, because our template template parameter
795 // might have dependent types in its template parameters, which we wouldn't
796 // be able to match now.
797 //
798 // If none of the template template parameter's template arguments mention
799 // other template parameters, we could actually perform more checking here.
800 // However, it isn't worth doing.
801 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
802 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000803 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000804 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000805 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000807
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000808 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000809 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000810 DefaultArg.getArgument().getAsTemplate(),
811 UPPC_DefaultArgument))
812 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000813
Richard Smith1469b912015-06-10 00:29:03 +0000814 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816
John McCall48871652010-08-21 09:40:31 +0000817 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000818}
819
Hubert Tongf608c052016-04-29 18:05:37 +0000820/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
821/// constrained by RequiresClause, that contains the template parameters in
822/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000823TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000824Sema::ActOnTemplateParameterList(unsigned Depth,
825 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000826 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000827 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000828 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +0000829 SourceLocation RAngleLoc,
830 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000831 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000832 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000833
Hubert Tongf608c052016-04-29 18:05:37 +0000834 // FIXME: store RequiresClause
David Majnemer902f8c62015-12-27 07:16:27 +0000835 return TemplateParameterList::Create(
836 Context, TemplateLoc, LAngleLoc,
837 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
838 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000839}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000840
John McCall3e11ebe2010-03-15 10:12:16 +0000841static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
842 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000843 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000844}
845
John McCallfaf5fb42010-08-26 23:41:50 +0000846DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000847Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000848 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000849 IdentifierInfo *Name, SourceLocation NameLoc,
850 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000851 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000852 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000853 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000854 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000855 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000856 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000857 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000858 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000859 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000860 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000861
862 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000863 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000864 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000865
Abramo Bagnara6150c882010-05-11 21:36:43 +0000866 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
867 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000868
869 // There is no such thing as an unnamed class template.
870 if (!Name) {
871 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000872 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000873 }
874
Richard Smith6483d222012-04-21 01:27:54 +0000875 // Find any previous declaration with this name. For a friend with no
876 // scope explicitly specified, we only look for tag declarations (per
877 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000878 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000879 LookupResult Previous(*this, Name, NameLoc,
880 (SS.isEmpty() && TUK == TUK_Friend)
881 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000882 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000883 if (SS.isNotEmpty() && !SS.isInvalid()) {
884 SemanticContext = computeDeclContext(SS, true);
885 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000886 // FIXME: Horrible, horrible hack! We can't currently represent this
887 // in the AST, and historically we have just ignored such friend
888 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000889 Diag(NameLoc, TUK == TUK_Friend
890 ? diag::warn_template_qualified_friend_ignored
891 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000892 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000893 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000894 }
Mike Stump11289f42009-09-09 15:08:12 +0000895
John McCall0b66eb32010-05-01 00:40:08 +0000896 if (RequireCompleteDeclContext(SS, SemanticContext))
897 return true;
898
Douglas Gregor041b0842011-10-14 15:31:12 +0000899 // If we're adding a template to a dependent context, we may need to
900 // rebuilding some of the types used within the template parameter list,
901 // now that we know what the current instantiation is.
902 if (SemanticContext->isDependentContext()) {
903 ContextRAII SavedContext(*this, SemanticContext);
904 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
905 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000906 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
907 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000908
John McCall27b18f82009-11-17 02:14:36 +0000909 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000910 } else {
911 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +0000912
913 // C++14 [class.mem]p14:
914 // If T is the name of a class, then each of the following shall have a
915 // name different from T:
916 // -- every member template of class T
917 if (TUK != TUK_Friend &&
918 DiagnoseClassNameShadow(SemanticContext,
919 DeclarationNameInfo(Name, NameLoc)))
920 return true;
921
John McCall27b18f82009-11-17 02:14:36 +0000922 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000923 }
Mike Stump11289f42009-09-09 15:08:12 +0000924
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000925 if (Previous.isAmbiguous())
926 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000927
Craig Topperc3ec1492014-05-26 06:22:03 +0000928 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000929 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000930 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000931
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000932 // If there is a previous declaration with the same name, check
933 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000934 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000935 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000936
937 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000938 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000939 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000940 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000941 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
942 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000943 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000944 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
945 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
946 PrevClassTemplate
947 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
948 ->getSpecializedTemplate();
949 }
950 }
951
John McCalld43784f2009-12-18 11:25:59 +0000952 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000953 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954 // [...] When looking for a prior declaration of a class or a function
955 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000956 // function is neither a qualified name nor a template-id, scopes outside
957 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000958 if (!SS.isSet()) {
959 DeclContext *OutermostContext = CurContext;
960 while (!OutermostContext->isFileContext())
961 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000962
Richard Smith61e582f2012-04-20 07:12:26 +0000963 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000964 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
965 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
966 SemanticContext = PrevDecl->getDeclContext();
967 } else {
968 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000970 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +0000971 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +0000972 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000973
974 // Check that the chosen semantic context doesn't already contain a
975 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +0000976 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +0000977 DeclContext *LookupContext = SemanticContext;
978 while (LookupContext->isTransparentContext())
979 LookupContext = LookupContext->getLookupParent();
980 LookupQualifiedName(Previous, LookupContext);
981
982 if (Previous.isAmbiguous())
983 return true;
984
985 if (Previous.begin() != Previous.end())
986 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000987 }
John McCall90d3bb92009-12-17 23:21:11 +0000988 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000989 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +0000990 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
991 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000992 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000993
Richard Smithfc805ca2015-07-06 04:43:58 +0000994 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
995 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
996 if (SS.isEmpty() &&
997 !(PrevClassTemplate &&
998 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
999 SemanticContext->getRedeclContext()))) {
1000 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1001 Diag(Shadow->getTargetDecl()->getLocation(),
1002 diag::note_using_decl_target);
1003 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1004 // Recover by ignoring the old declaration.
1005 PrevDecl = PrevClassTemplate = nullptr;
1006 }
1007 }
1008
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001009 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001010 // Ensure that the template parameter lists are compatible. Skip this check
1011 // for a friend in a dependent context: the template parameter list itself
1012 // could be dependent.
1013 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1014 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001015 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001016 /*Complain=*/true,
1017 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001018 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001019
1020 // C++ [temp.class]p4:
1021 // In a redeclaration, partial specialization, explicit
1022 // specialization or explicit instantiation of a class template,
1023 // the class-key shall agree in kind with the original class
1024 // template declaration (7.1.5.3).
1025 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001026 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001027 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001028 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001029 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001030 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001031 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001032 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001033 }
1034
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001035 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001036 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001037 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001038 // If we have a prior definition that is not visible, treat this as
1039 // simply making that previous definition visible.
1040 NamedDecl *Hidden = nullptr;
1041 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001042 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001043 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1044 assert(Tmpl && "original definition of a class template is not a "
1045 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001046 makeMergedDefinitionVisible(Hidden, KWLoc);
1047 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001048 return Def;
1049 }
1050
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001051 Diag(NameLoc, diag::err_redefinition) << Name;
1052 Diag(Def->getLocation(), diag::note_previous_definition);
1053 // FIXME: Would it make sense to try to "forget" the previous
1054 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001055 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001056 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001057 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001058 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1059 // Maybe we will complain about the shadowed template parameter.
1060 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1061 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001062 PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001063 } else if (PrevDecl) {
1064 // C++ [temp]p5:
1065 // A class template shall not have the same name as any other
1066 // template, class, function, object, enumeration, enumerator,
1067 // namespace, or type in the same scope (3.3), except as specified
1068 // in (14.5.4).
1069 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1070 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001071 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001072 }
1073
Douglas Gregordba32632009-02-10 19:49:53 +00001074 // Check the template parameter list of this declaration, possibly
1075 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001076 // template declaration. Skip this check for a friend in a dependent
1077 // context, because the template parameter list might be dependent.
1078 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001079 CheckTemplateParameterList(
1080 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001081 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1082 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001083 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1084 SemanticContext->isDependentContext())
1085 ? TPC_ClassTemplateMember
1086 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1087 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001088 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001089
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001090 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001091 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001092 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001093 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1094 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001095 : diag::err_member_decl_does_not_match)
1096 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001097 Invalid = true;
1098 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001099 }
1100
Mike Stump11289f42009-09-09 15:08:12 +00001101 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001102 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001103 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001104 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001105 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001106 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001107 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001108 NewClass->setTemplateParameterListsInfo(
1109 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1110 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001111
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001112 // Add alignment attributes if necessary; these attributes are checked when
1113 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001114 if (TUK == TUK_Definition) {
1115 AddAlignmentAttributesForRecord(NewClass);
1116 AddMsStructLayoutForRecord(NewClass);
1117 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001118
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001119 ClassTemplateDecl *NewTemplate
1120 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1121 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001122 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001123 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001124
Douglas Gregor21823bf2011-12-20 18:11:52 +00001125 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001126 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001127
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001128 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001129 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001130 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001131 assert(T->isDependentType() && "Class template type is not dependent?");
1132 (void)T;
1133
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001134 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001135 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001137 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1138 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001139
Anders Carlsson137108d2009-03-26 01:24:28 +00001140 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001141 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001142 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001143
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001144 // Set the lexical context of these templates
1145 NewClass->setLexicalDeclContext(CurContext);
1146 NewTemplate->setLexicalDeclContext(CurContext);
1147
John McCall9bb74a52009-07-31 02:45:11 +00001148 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001149 NewClass->startDefinition();
1150
1151 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001152 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001153
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001154 if (PrevClassTemplate)
1155 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1156
Rafael Espindola385c0422012-07-13 18:04:45 +00001157 AddPushedVisibilityAttribute(NewClass);
1158
Richard Smith234ff472014-08-23 00:49:01 +00001159 if (TUK != TUK_Friend) {
1160 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1161 Scope *Outer = S;
1162 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1163 Outer = Outer->getParent();
1164 PushOnScopeChains(NewTemplate, Outer);
1165 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001166 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001167 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001168 NewClass->setAccess(PrevClassTemplate->getAccess());
1169 }
John McCall27b5c252009-09-14 21:59:20 +00001170
Richard Smith64017682013-07-17 23:53:16 +00001171 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001172
John McCall27b5c252009-09-14 21:59:20 +00001173 // Friend templates are visible in fairly strange ways.
1174 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001175 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001176 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001177 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1178 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001180 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001182 FriendDecl *Friend = FriendDecl::Create(
1183 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001184 Friend->setAccess(AS_public);
1185 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001186 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001187
Douglas Gregordba32632009-02-10 19:49:53 +00001188 if (Invalid) {
1189 NewTemplate->setInvalidDecl();
1190 NewClass->setInvalidDecl();
1191 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001192
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001193 ActOnDocumentableDecl(NewTemplate);
1194
John McCall48871652010-08-21 09:40:31 +00001195 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001196}
1197
Douglas Gregored5731f2009-11-25 17:50:39 +00001198/// \brief Diagnose the presence of a default template argument on a
1199/// template parameter, which is ill-formed in certain contexts.
1200///
1201/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001202static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001203 Sema::TemplateParamListContext TPC,
1204 SourceLocation ParamLoc,
1205 SourceRange DefArgRange) {
1206 switch (TPC) {
1207 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001208 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001209 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001210 return false;
1211
1212 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001213 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001214 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001215 // A default template-argument shall not be specified in a
1216 // function template declaration or a function template
1217 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001218 // If a friend function template declaration specifies a default
1219 // template-argument, that declaration shall be a definition and shall be
1220 // the only declaration of the function template in the translation unit.
1221 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001222 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001223 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1224 : diag::ext_template_parameter_default_in_function_template)
1225 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001226 return false;
1227
1228 case Sema::TPC_ClassTemplateMember:
1229 // C++0x [temp.param]p9:
1230 // A default template-argument shall not be specified in the
1231 // template-parameter-lists of the definition of a member of a
1232 // class template that appears outside of the member's class.
1233 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1234 << DefArgRange;
1235 return true;
1236
David Majnemerba8f17a2013-06-25 22:08:55 +00001237 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001238 case Sema::TPC_FriendFunctionTemplate:
1239 // C++ [temp.param]p9:
1240 // A default template-argument shall not be specified in a
1241 // friend template declaration.
1242 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1243 << DefArgRange;
1244 return true;
1245
1246 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1247 // for friend function templates if there is only a single
1248 // declaration (and it is a definition). Strange!
1249 }
1250
David Blaikie8a40f702012-01-17 06:56:22 +00001251 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001252}
1253
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001254/// \brief Check for unexpanded parameter packs within the template parameters
1255/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001256static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1257 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001258 // A template template parameter which is a parameter pack is also a pack
1259 // expansion.
1260 if (TTP->isParameterPack())
1261 return false;
1262
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001263 TemplateParameterList *Params = TTP->getTemplateParameters();
1264 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1265 NamedDecl *P = Params->getParam(I);
1266 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001267 if (!NTTP->isParameterPack() &&
1268 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001269 NTTP->getTypeSourceInfo(),
1270 Sema::UPPC_NonTypeTemplateParameterType))
1271 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001272
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001273 continue;
1274 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001275
1276 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001277 = dyn_cast<TemplateTemplateParmDecl>(P))
1278 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1279 return true;
1280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001281
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001282 return false;
1283}
1284
Douglas Gregordba32632009-02-10 19:49:53 +00001285/// \brief Checks the validity of a template parameter list, possibly
1286/// considering the template parameter list from a previous
1287/// declaration.
1288///
1289/// If an "old" template parameter list is provided, it must be
1290/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1291/// template parameter list.
1292///
1293/// \param NewParams Template parameter list for a new template
1294/// declaration. This template parameter list will be updated with any
1295/// default arguments that are carried through from the previous
1296/// template parameter list.
1297///
1298/// \param OldParams If provided, template parameter list from a
1299/// previous declaration of the same template. Default template
1300/// arguments will be merged from the old template parameter list to
1301/// the new template parameter list.
1302///
Douglas Gregored5731f2009-11-25 17:50:39 +00001303/// \param TPC Describes the context in which we are checking the given
1304/// template parameter list.
1305///
Douglas Gregordba32632009-02-10 19:49:53 +00001306/// \returns true if an error occurred, false otherwise.
1307bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001308 TemplateParameterList *OldParams,
1309 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001310 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001311
Douglas Gregordba32632009-02-10 19:49:53 +00001312 // C++ [temp.param]p10:
1313 // The set of default template-arguments available for use with a
1314 // template declaration or definition is obtained by merging the
1315 // default arguments from the definition (if in scope) and all
1316 // declarations in scope in the same way default function
1317 // arguments are (8.3.6).
1318 bool SawDefaultArgument = false;
1319 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001320
Mike Stumpc89c8e32009-02-11 23:03:27 +00001321 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001322 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001323 if (OldParams)
1324 OldParam = OldParams->begin();
1325
Douglas Gregor0693def2011-01-27 01:40:17 +00001326 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001327 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1328 NewParamEnd = NewParams->end();
1329 NewParam != NewParamEnd; ++NewParam) {
1330 // Variables used to diagnose redundant default arguments
1331 bool RedundantDefaultArg = false;
1332 SourceLocation OldDefaultLoc;
1333 SourceLocation NewDefaultLoc;
1334
David Blaikie651c73c2011-10-19 05:19:50 +00001335 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001336 bool MissingDefaultArg = false;
1337
David Blaikie651c73c2011-10-19 05:19:50 +00001338 // Variable used to diagnose non-final parameter packs
1339 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001340
Douglas Gregordba32632009-02-10 19:49:53 +00001341 if (TemplateTypeParmDecl *NewTypeParm
1342 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001343 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344 if (NewTypeParm->hasDefaultArgument() &&
1345 DiagnoseDefaultTemplateArgument(*this, TPC,
1346 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001347 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001348 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001349 NewTypeParm->removeDefaultArgument();
1350
1351 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001352 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001353 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001354 if (NewTypeParm->isParameterPack()) {
1355 assert(!NewTypeParm->hasDefaultArgument() &&
1356 "Parameter packs can't have a default argument!");
1357 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001358 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001359 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001360 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1361 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1362 SawDefaultArgument = true;
1363 RedundantDefaultArg = true;
1364 PreviousDefaultArgLoc = NewDefaultLoc;
1365 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1366 // Merge the default argument from the old declaration to the
1367 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001368 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001369 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1370 } else if (NewTypeParm->hasDefaultArgument()) {
1371 SawDefaultArgument = true;
1372 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1373 } else if (SawDefaultArgument)
1374 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001375 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001376 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001377 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001378 if (!NewNonTypeParm->isParameterPack() &&
1379 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001380 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001381 UPPC_NonTypeTemplateParameterType)) {
1382 Invalid = true;
1383 continue;
1384 }
1385
Douglas Gregored5731f2009-11-25 17:50:39 +00001386 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387 if (NewNonTypeParm->hasDefaultArgument() &&
1388 DiagnoseDefaultTemplateArgument(*this, TPC,
1389 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001390 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001391 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001392 }
1393
Mike Stump12b8ce12009-08-04 21:02:39 +00001394 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001395 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001396 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001397 if (NewNonTypeParm->isParameterPack()) {
1398 assert(!NewNonTypeParm->hasDefaultArgument() &&
1399 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001400 if (!NewNonTypeParm->isPackExpansion())
1401 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001402 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001403 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001404 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1405 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1406 SawDefaultArgument = true;
1407 RedundantDefaultArg = true;
1408 PreviousDefaultArgLoc = NewDefaultLoc;
1409 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1410 // Merge the default argument from the old declaration to the
1411 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001412 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001413 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1414 } else if (NewNonTypeParm->hasDefaultArgument()) {
1415 SawDefaultArgument = true;
1416 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1417 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001418 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001419 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001420 TemplateTemplateParmDecl *NewTemplateParm
1421 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001423 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001424 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001425 Invalid = true;
1426 continue;
1427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001428
David Blaikie651c73c2011-10-19 05:19:50 +00001429 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001430 if (NewTemplateParm->hasDefaultArgument() &&
1431 DiagnoseDefaultTemplateArgument(*this, TPC,
1432 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001433 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001434 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001435
1436 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001437 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001438 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001439 if (NewTemplateParm->isParameterPack()) {
1440 assert(!NewTemplateParm->hasDefaultArgument() &&
1441 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001442 if (!NewTemplateParm->isPackExpansion())
1443 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001444 } else if (OldTemplateParm &&
1445 hasVisibleDefaultArgument(OldTemplateParm) &&
1446 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001447 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1448 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001449 SawDefaultArgument = true;
1450 RedundantDefaultArg = true;
1451 PreviousDefaultArgLoc = NewDefaultLoc;
1452 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1453 // Merge the default argument from the old declaration to the
1454 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001455 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001456 PreviousDefaultArgLoc
1457 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001458 } else if (NewTemplateParm->hasDefaultArgument()) {
1459 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001460 PreviousDefaultArgLoc
1461 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001462 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001463 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001464 }
1465
Richard Smith1fde8ec2012-09-07 02:06:42 +00001466 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001467 // If a template parameter of a primary class template or alias template
1468 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001469 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001470 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1471 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001472 Diag((*NewParam)->getLocation(),
1473 diag::err_template_param_pack_must_be_last_template_parameter);
1474 Invalid = true;
1475 }
1476
Douglas Gregordba32632009-02-10 19:49:53 +00001477 if (RedundantDefaultArg) {
1478 // C++ [temp.param]p12:
1479 // A template-parameter shall not be given default arguments
1480 // by two different declarations in the same scope.
1481 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1482 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1483 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001484 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001485 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001486 // If a template-parameter of a class template has a default
1487 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001488 // have a default template-argument supplied or be a template parameter
1489 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001490 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001491 diag::err_template_param_default_arg_missing);
1492 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1493 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001494 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001495 }
1496
1497 // If we have an old template parameter list that we're merging
1498 // in, move on to the next parameter.
1499 if (OldParams)
1500 ++OldParam;
1501 }
1502
Douglas Gregor0693def2011-01-27 01:40:17 +00001503 // We were missing some default arguments at the end of the list, so remove
1504 // all of the default arguments.
1505 if (RemoveDefaultArguments) {
1506 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1507 NewParamEnd = NewParams->end();
1508 NewParam != NewParamEnd; ++NewParam) {
1509 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1510 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001511 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001512 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1513 NTTP->removeDefaultArgument();
1514 else
1515 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1516 }
1517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001518
Douglas Gregordba32632009-02-10 19:49:53 +00001519 return Invalid;
1520}
Douglas Gregord32e0282009-02-09 23:23:08 +00001521
John McCalla020a012010-10-20 05:44:58 +00001522namespace {
1523
1524/// A class which looks for a use of a certain level of template
1525/// parameter.
1526struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1527 typedef RecursiveASTVisitor<DependencyChecker> super;
1528
1529 unsigned Depth;
1530 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001531 SourceLocation MatchLoc;
1532
1533 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001534
1535 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1536 NamedDecl *ND = Params->getParam(0);
1537 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1538 Depth = PD->getDepth();
1539 } else if (NonTypeTemplateParmDecl *PD =
1540 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1541 Depth = PD->getDepth();
1542 } else {
1543 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1544 }
1545 }
1546
Richard Smith6056d5e2014-02-09 00:54:43 +00001547 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001548 if (ParmDepth >= Depth) {
1549 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001550 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001551 return true;
1552 }
1553 return false;
1554 }
1555
Richard Smith6056d5e2014-02-09 00:54:43 +00001556 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1557 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1558 }
1559
John McCalla020a012010-10-20 05:44:58 +00001560 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1561 return !Matches(T->getDepth());
1562 }
1563
1564 bool TraverseTemplateName(TemplateName N) {
1565 if (TemplateTemplateParmDecl *PD =
1566 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001567 if (Matches(PD->getDepth()))
1568 return false;
John McCalla020a012010-10-20 05:44:58 +00001569 return super::TraverseTemplateName(N);
1570 }
1571
1572 bool VisitDeclRefExpr(DeclRefExpr *E) {
1573 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001574 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1575 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001576 return false;
John McCalla020a012010-10-20 05:44:58 +00001577 return super::VisitDeclRefExpr(E);
1578 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001579
1580 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1581 return TraverseType(T->getReplacementType());
1582 }
1583
1584 bool
1585 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1586 return TraverseTemplateArgument(T->getArgumentPack());
1587 }
1588
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001589 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1590 return TraverseType(T->getInjectedSpecializationType());
1591 }
John McCalla020a012010-10-20 05:44:58 +00001592};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001593} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001594
Douglas Gregor972fe532011-05-10 18:27:06 +00001595/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001596/// list.
1597static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001598DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001599 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001600 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001601 return Checker.Match;
1602}
1603
Douglas Gregor972fe532011-05-10 18:27:06 +00001604// Find the source range corresponding to the named type in the given
1605// nested-name-specifier, if any.
1606static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1607 QualType T,
1608 const CXXScopeSpec &SS) {
1609 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1610 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1611 if (const Type *CurType = NNS->getAsType()) {
1612 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1613 return NNSLoc.getTypeLoc().getSourceRange();
1614 } else
1615 break;
1616
1617 NNSLoc = NNSLoc.getPrefix();
1618 }
1619
1620 return SourceRange();
1621}
1622
Mike Stump11289f42009-09-09 15:08:12 +00001623/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001624/// specifier, returning the template parameter list that applies to the
1625/// name.
1626///
1627/// \param DeclStartLoc the start of the declaration that has a scope
1628/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001629///
Douglas Gregor972fe532011-05-10 18:27:06 +00001630/// \param DeclLoc The location of the declaration itself.
1631///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001632/// \param SS the scope specifier that will be matched to the given template
1633/// parameter lists. This scope specifier precedes a qualified name that is
1634/// being declared.
1635///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001636/// \param TemplateId The template-id following the scope specifier, if there
1637/// is one. Used to check for a missing 'template<>'.
1638///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001639/// \param ParamLists the template parameter lists, from the outermost to the
1640/// innermost template parameter lists.
1641///
John McCalle820e5e2010-04-13 20:37:33 +00001642/// \param IsFriend Whether to apply the slightly different rules for
1643/// matching template parameters to scope specifiers in friend
1644/// declarations.
1645///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001646/// \param IsExplicitSpecialization will be set true if the entity being
1647/// declared is an explicit specialization, false otherwise.
1648///
Mike Stump11289f42009-09-09 15:08:12 +00001649/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001650/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001651/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001652/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001653/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001654/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001655TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1656 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001657 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001658 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1659 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001660 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001661 Invalid = false;
1662
1663 // The sequence of nested types to which we will match up the template
1664 // parameter lists. We first build this list by starting with the type named
1665 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001666 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001667 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001668 if (SS.getScopeRep()) {
1669 if (CXXRecordDecl *Record
1670 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1671 T = Context.getTypeDeclType(Record);
1672 else
1673 T = QualType(SS.getScopeRep()->getAsType(), 0);
1674 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001675
1676 // If we found an explicit specialization that prevents us from needing
1677 // 'template<>' headers, this will be set to the location of that
1678 // explicit specialization.
1679 SourceLocation ExplicitSpecLoc;
1680
1681 while (!T.isNull()) {
1682 NestedTypes.push_back(T);
1683
1684 // Retrieve the parent of a record type.
1685 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1686 // If this type is an explicit specialization, we're done.
1687 if (ClassTemplateSpecializationDecl *Spec
1688 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1689 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1690 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1691 ExplicitSpecLoc = Spec->getLocation();
1692 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001693 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001694 } else if (Record->getTemplateSpecializationKind()
1695 == TSK_ExplicitSpecialization) {
1696 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001697 break;
1698 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001699
1700 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1701 T = Context.getTypeDeclType(Parent);
1702 else
1703 T = QualType();
1704 continue;
1705 }
1706
1707 if (const TemplateSpecializationType *TST
1708 = T->getAs<TemplateSpecializationType>()) {
1709 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1710 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1711 T = Context.getTypeDeclType(Parent);
1712 else
1713 T = QualType();
1714 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001715 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001716 }
1717
1718 // Look one step prior in a dependent template specialization type.
1719 if (const DependentTemplateSpecializationType *DependentTST
1720 = T->getAs<DependentTemplateSpecializationType>()) {
1721 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1722 T = QualType(NNS->getAsType(), 0);
1723 else
1724 T = QualType();
1725 continue;
1726 }
1727
1728 // Look one step prior in a dependent name type.
1729 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1730 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1731 T = QualType(NNS->getAsType(), 0);
1732 else
1733 T = QualType();
1734 continue;
1735 }
1736
1737 // Retrieve the parent of an enumeration type.
1738 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1739 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1740 // check here.
1741 EnumDecl *Enum = EnumT->getDecl();
1742
1743 // Get to the parent type.
1744 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1745 T = Context.getTypeDeclType(Parent);
1746 else
1747 T = QualType();
1748 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001749 }
Mike Stump11289f42009-09-09 15:08:12 +00001750
Douglas Gregor972fe532011-05-10 18:27:06 +00001751 T = QualType();
1752 }
1753 // Reverse the nested types list, since we want to traverse from the outermost
1754 // to the innermost while checking template-parameter-lists.
1755 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001756
Douglas Gregor972fe532011-05-10 18:27:06 +00001757 // C++0x [temp.expl.spec]p17:
1758 // A member or a member template may be nested within many
1759 // enclosing class templates. In an explicit specialization for
1760 // such a member, the member declaration shall be preceded by a
1761 // template<> for each enclosing class template that is
1762 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001763 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001764
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001765 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001766 if (SawNonEmptyTemplateParameterList) {
1767 Diag(DeclLoc, diag::err_specialize_member_of_template)
1768 << !Recovery << Range;
1769 Invalid = true;
1770 IsExplicitSpecialization = false;
1771 return true;
1772 }
1773
1774 return false;
1775 };
1776
1777 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1778 // Check that we can have an explicit specialization here.
1779 if (CheckExplicitSpecialization(Range, true))
1780 return true;
1781
1782 // We don't have a template header, but we should.
1783 SourceLocation ExpectedTemplateLoc;
1784 if (!ParamLists.empty())
1785 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1786 else
1787 ExpectedTemplateLoc = DeclStartLoc;
1788
1789 Diag(DeclLoc, diag::err_template_spec_needs_header)
1790 << Range
1791 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1792 return false;
1793 };
1794
Douglas Gregor972fe532011-05-10 18:27:06 +00001795 unsigned ParamIdx = 0;
1796 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1797 ++TypeIdx) {
1798 T = NestedTypes[TypeIdx];
1799
1800 // Whether we expect a 'template<>' header.
1801 bool NeedEmptyTemplateHeader = false;
1802
1803 // Whether we expect a template header with parameters.
1804 bool NeedNonemptyTemplateHeader = false;
1805
1806 // For a dependent type, the set of template parameters that we
1807 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001808 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001809
Douglas Gregor373af9b2011-05-11 23:26:17 +00001810 // C++0x [temp.expl.spec]p15:
1811 // A member or a member template may be nested within many enclosing
1812 // class templates. In an explicit specialization for such a member, the
1813 // member declaration shall be preceded by a template<> for each
1814 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001815 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1816 if (ClassTemplatePartialSpecializationDecl *Partial
1817 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1818 ExpectedTemplateParams = Partial->getTemplateParameters();
1819 NeedNonemptyTemplateHeader = true;
1820 } else if (Record->isDependentType()) {
1821 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001822 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001823 ->getTemplateParameters();
1824 NeedNonemptyTemplateHeader = true;
1825 }
1826 } else if (ClassTemplateSpecializationDecl *Spec
1827 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1828 // C++0x [temp.expl.spec]p4:
1829 // Members of an explicitly specialized class template are defined
1830 // in the same manner as members of normal classes, and not using
1831 // the template<> syntax.
1832 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1833 NeedEmptyTemplateHeader = true;
1834 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001835 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001836 } else if (Record->getTemplateSpecializationKind()) {
1837 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001838 != TSK_ExplicitSpecialization &&
1839 TypeIdx == NumTypes - 1)
1840 IsExplicitSpecialization = true;
1841
1842 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001843 }
1844 } else if (const TemplateSpecializationType *TST
1845 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001846 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001847 ExpectedTemplateParams = Template->getTemplateParameters();
1848 NeedNonemptyTemplateHeader = true;
1849 }
1850 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1851 // FIXME: We actually could/should check the template arguments here
1852 // against the corresponding template parameter list.
1853 NeedNonemptyTemplateHeader = false;
1854 }
1855
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001856 // C++ [temp.expl.spec]p16:
1857 // In an explicit specialization declaration for a member of a class
1858 // template or a member template that ap- pears in namespace scope, the
1859 // member template and some of its enclosing class templates may remain
1860 // unspecialized, except that the declaration shall not explicitly
1861 // specialize a class member template if its en- closing class templates
1862 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001863 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001864 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001865 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1866 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001867 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001868 } else
1869 SawNonEmptyTemplateParameterList = true;
1870 }
1871
Douglas Gregor972fe532011-05-10 18:27:06 +00001872 if (NeedEmptyTemplateHeader) {
1873 // If we're on the last of the types, and we need a 'template<>' header
1874 // here, then it's an explicit specialization.
1875 if (TypeIdx == NumTypes - 1)
1876 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001877
1878 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001879 if (ParamLists[ParamIdx]->size() > 0) {
1880 // The header has template parameters when it shouldn't. Complain.
1881 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1882 diag::err_template_param_list_matches_nontemplate)
1883 << T
1884 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1885 ParamLists[ParamIdx]->getRAngleLoc())
1886 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1887 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001888 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001889 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001890
Douglas Gregor972fe532011-05-10 18:27:06 +00001891 // Consume this template header.
1892 ++ParamIdx;
1893 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001894 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001895
1896 if (!IsFriend)
1897 if (DiagnoseMissingExplicitSpecialization(
1898 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001899 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001900
Douglas Gregor972fe532011-05-10 18:27:06 +00001901 continue;
1902 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001903
Douglas Gregor972fe532011-05-10 18:27:06 +00001904 if (NeedNonemptyTemplateHeader) {
1905 // In friend declarations we can have template-ids which don't
1906 // depend on the corresponding template parameter lists. But
1907 // assume that empty parameter lists are supposed to match this
1908 // template-id.
1909 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001910 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001911 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001912 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001913 else
1914 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001915 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001916
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001917 if (ParamIdx < ParamLists.size()) {
1918 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001919 if (ExpectedTemplateParams &&
1920 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1921 ExpectedTemplateParams,
1922 true, TPL_TemplateMatch))
1923 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001924
Douglas Gregor972fe532011-05-10 18:27:06 +00001925 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001926 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001927 TPC_ClassTemplateMember))
1928 Invalid = true;
1929
1930 ++ParamIdx;
1931 continue;
1932 }
1933
1934 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1935 << T
1936 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1937 Invalid = true;
1938 continue;
1939 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001940 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001941
Douglas Gregord8d297c2009-07-21 23:53:31 +00001942 // If there were at least as many template-ids as there were template
1943 // parameter lists, then there are no template parameter lists remaining for
1944 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001945 if (ParamIdx >= ParamLists.size()) {
1946 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001947 // We don't have a template header for the declaration itself, but we
1948 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001949 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001950 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1951 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001952
1953 // Fabricate an empty template parameter list for the invented header.
1954 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00001955 SourceLocation(), None,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001956 SourceLocation());
1957 }
1958
Craig Topperc3ec1492014-05-26 06:22:03 +00001959 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001960 }
Mike Stump11289f42009-09-09 15:08:12 +00001961
Douglas Gregord8d297c2009-07-21 23:53:31 +00001962 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001963 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001964 bool HasAnyExplicitSpecHeader = false;
1965 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001966 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001967 if (ParamLists[I]->size() == 0)
1968 HasAnyExplicitSpecHeader = true;
1969 else
1970 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001971 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001972
Douglas Gregor972fe532011-05-10 18:27:06 +00001973 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001974 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1975 : diag::err_template_spec_extra_headers)
1976 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1977 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001978
1979 // If there was a specialization somewhere, such that 'template<>' is
1980 // not required, and there were any 'template<>' headers, note where the
1981 // specialization occurred.
1982 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1983 Diag(ExplicitSpecLoc,
1984 diag::note_explicit_template_spec_does_not_need_header)
1985 << NestedTypes.back();
1986
1987 // We have a template parameter list with no corresponding scope, which
1988 // means that the resulting template declaration can't be instantiated
1989 // properly (we'll end up with dependent nodes when we shouldn't).
1990 if (!AllExplicitSpecHeaders)
1991 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001992 }
Mike Stump11289f42009-09-09 15:08:12 +00001993
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001994 // C++ [temp.expl.spec]p16:
1995 // In an explicit specialization declaration for a member of a class
1996 // template or a member template that ap- pears in namespace scope, the
1997 // member template and some of its enclosing class templates may remain
1998 // unspecialized, except that the declaration shall not explicitly
1999 // specialize a class member template if its en- closing class templates
2000 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002001 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002002 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2003 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002004 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002005
Douglas Gregord8d297c2009-07-21 23:53:31 +00002006 // Return the last template parameter list, which corresponds to the
2007 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002008 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002009}
2010
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002011void Sema::NoteAllFoundTemplates(TemplateName Name) {
2012 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2013 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002014 << (isa<FunctionTemplateDecl>(Template)
2015 ? 0
2016 : isa<ClassTemplateDecl>(Template)
2017 ? 1
2018 : isa<VarTemplateDecl>(Template)
2019 ? 2
2020 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2021 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002022 return;
2023 }
2024
2025 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2026 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2027 IEnd = OST->end();
2028 I != IEnd; ++I)
2029 Diag((*I)->getLocation(), diag::note_template_declared_here)
2030 << 0 << (*I)->getDeclName();
2031
2032 return;
2033 }
2034}
2035
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002036static QualType
2037checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2038 const SmallVectorImpl<TemplateArgument> &Converted,
2039 SourceLocation TemplateLoc,
2040 TemplateArgumentListInfo &TemplateArgs) {
2041 ASTContext &Context = SemaRef.getASTContext();
2042 switch (BTD->getBuiltinTemplateKind()) {
2043 case BTK__make_integer_seq:
2044 // Specializations of __make_integer_seq<S, T, N> are treated like
2045 // S<T, 0, ..., N-1>.
2046
2047 // C++14 [inteseq.intseq]p1:
2048 // T shall be an integer type.
2049 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2050 SemaRef.Diag(TemplateArgs[1].getLocation(),
2051 diag::err_integer_sequence_integral_element_type);
2052 return QualType();
2053 }
2054
2055 // C++14 [inteseq.make]p1:
2056 // If N is negative the program is ill-formed.
2057 TemplateArgument NumArgsArg = Converted[2];
2058 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2059 if (NumArgs < 0) {
2060 SemaRef.Diag(TemplateArgs[2].getLocation(),
2061 diag::err_integer_sequence_negative_length);
2062 return QualType();
2063 }
2064
2065 QualType ArgTy = NumArgsArg.getIntegralType();
2066 TemplateArgumentListInfo SyntheticTemplateArgs;
2067 // The type argument gets reused as the first template argument in the
2068 // synthetic template argument list.
2069 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2070 // Expand N into 0 ... N-1.
2071 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2072 I < NumArgs; ++I) {
2073 TemplateArgument TA(Context, I, ArgTy);
2074 Expr *E = SemaRef.BuildExpressionFromIntegralTemplateArgument(
2075 TA, TemplateArgs[2].getLocation())
2076 .getAs<Expr>();
2077 SyntheticTemplateArgs.addArgument(
2078 TemplateArgumentLoc(TemplateArgument(E), E));
2079 }
2080 // The first template argument will be reused as the template decl that
2081 // our synthetic template arguments will be applied to.
2082 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2083 TemplateLoc, SyntheticTemplateArgs);
2084 }
2085 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2086}
2087
Douglas Gregordc572a32009-03-30 22:58:21 +00002088QualType Sema::CheckTemplateIdType(TemplateName Name,
2089 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002090 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002091 DependentTemplateName *DTN
2092 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002093 if (DTN && DTN->isIdentifier())
2094 // When building a template-id where the template-name is dependent,
2095 // assume the template is a type template. Either our assumption is
2096 // correct, or the code is ill-formed and will be diagnosed when the
2097 // dependent name is substituted.
2098 return Context.getDependentTemplateSpecializationType(ETK_None,
2099 DTN->getQualifier(),
2100 DTN->getIdentifier(),
2101 TemplateArgs);
2102
Douglas Gregordc572a32009-03-30 22:58:21 +00002103 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002104 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2105 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002106 // We might have a substituted template template parameter pack. If so,
2107 // build a template specialization type for it.
2108 if (Name.getAsSubstTemplateTemplateParmPack())
2109 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002110
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002111 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2112 << Name;
2113 NoteAllFoundTemplates(Name);
2114 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002115 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002116
Douglas Gregorc40290e2009-03-09 23:48:35 +00002117 // Check that the template argument list is well-formed for this
2118 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002119 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002120 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002121 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002122 return QualType();
2123
Douglas Gregorc40290e2009-03-09 23:48:35 +00002124 QualType CanonType;
2125
Douglas Gregor678d76c2011-07-01 01:22:09 +00002126 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002127 if (TypeAliasTemplateDecl *AliasTemplate =
2128 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002129 // Find the canonical type for this type alias template specialization.
2130 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2131 if (Pattern->isInvalidDecl())
2132 return QualType();
2133
2134 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2135 Converted.data(), Converted.size());
2136
2137 // Only substitute for the innermost template argument list.
2138 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002139 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002140 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2141 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002142 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002143
Richard Smith802c4b72012-08-23 06:16:52 +00002144 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002145 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002146 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002147 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002148
Richard Smith3f1b5d02011-05-05 21:57:07 +00002149 CanonType = SubstType(Pattern->getUnderlyingType(),
2150 TemplateArgLists, AliasTemplate->getLocation(),
2151 AliasTemplate->getDeclName());
2152 if (CanonType.isNull())
2153 return QualType();
2154 } else if (Name.isDependent() ||
2155 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002156 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002157 // This class template specialization is a dependent
2158 // type. Therefore, its canonical type is another class template
2159 // specialization type that contains all of the converted
2160 // arguments in canonical form. This ensures that, e.g., A<T> and
2161 // A<T, T> have identical types when A is declared as:
2162 //
2163 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002164 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002165 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002166 Converted.data(),
2167 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002168
Douglas Gregora8e02e72009-07-28 23:00:59 +00002169 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002170 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002171 // In the future, we need to teach getTemplateSpecializationType to only
2172 // build the canonical type and return that to us.
2173 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002174
2175 // This might work out to be a current instantiation, in which
2176 // case the canonical type needs to be the InjectedClassNameType.
2177 //
2178 // TODO: in theory this could be a simple hashtable lookup; most
2179 // changes to CurContext don't change the set of current
2180 // instantiations.
2181 if (isa<ClassTemplateDecl>(Template)) {
2182 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2183 // If we get out to a namespace, we're done.
2184 if (Ctx->isFileContext()) break;
2185
2186 // If this isn't a record, keep looking.
2187 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2188 if (!Record) continue;
2189
2190 // Look for one of the two cases with InjectedClassNameTypes
2191 // and check whether it's the same template.
2192 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2193 !Record->getDescribedClassTemplate())
2194 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002195
John McCall2408e322010-04-27 00:57:59 +00002196 // Fetch the injected class name type and check whether its
2197 // injected type is equal to the type we just built.
2198 QualType ICNT = Context.getTypeDeclType(Record);
2199 QualType Injected = cast<InjectedClassNameType>(ICNT)
2200 ->getInjectedSpecializationType();
2201
2202 if (CanonType != Injected->getCanonicalTypeInternal())
2203 continue;
2204
2205 // If so, the canonical type of this TST is the injected
2206 // class name type of the record we just found.
2207 assert(ICNT.isCanonical());
2208 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002209 break;
2210 }
2211 }
Mike Stump11289f42009-09-09 15:08:12 +00002212 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002213 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002214 // Find the class template specialization declaration that
2215 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002216 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002217 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002218 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002219 if (!Decl) {
2220 // This is the first time we have referenced this class template
2221 // specialization. Create the canonical declaration and add it to
2222 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002223 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002224 ClassTemplate->getTemplatedDecl()->getTagKind(),
2225 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002226 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002227 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002228 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002229 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002230 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002231 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002232 if (ClassTemplate->isOutOfLine())
2233 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002234 }
2235
Chandler Carruth2acfb222013-09-27 22:14:40 +00002236 // Diagnose uses of this specialization.
2237 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2238
Douglas Gregorc40290e2009-03-09 23:48:35 +00002239 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002240 assert(isa<RecordType>(CanonType) &&
2241 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002242 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2243 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2244 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002245 }
Mike Stump11289f42009-09-09 15:08:12 +00002246
Douglas Gregorc40290e2009-03-09 23:48:35 +00002247 // Build the fully-sugared type for this class template
2248 // specialization, which refers back to the class template
2249 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002250 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002251}
2252
John McCallfaf5fb42010-08-26 23:41:50 +00002253TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002254Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002255 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002256 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002257 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002258 SourceLocation RAngleLoc,
2259 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002260 if (SS.isInvalid())
2261 return true;
2262
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002263 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002264
Douglas Gregorc40290e2009-03-09 23:48:35 +00002265 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002266 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002267 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002268
Douglas Gregor5a064722011-02-28 17:23:35 +00002269 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002270 QualType T
2271 = Context.getDependentTemplateSpecializationType(ETK_None,
2272 DTN->getQualifier(),
2273 DTN->getIdentifier(),
2274 TemplateArgs);
2275 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002276 TypeLocBuilder TLB;
2277 DependentTemplateSpecializationTypeLoc SpecTL
2278 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002279 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2280 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002281 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002282 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002283 SpecTL.setLAngleLoc(LAngleLoc);
2284 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002285 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2286 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2287 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2288 }
2289
John McCall6b51f282009-11-23 01:53:49 +00002290 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002291
2292 if (Result.isNull())
2293 return true;
2294
Douglas Gregore7c20652011-03-02 00:47:37 +00002295 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002296 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002297 TemplateSpecializationTypeLoc SpecTL
2298 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002299 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002300 SpecTL.setTemplateNameLoc(TemplateLoc);
2301 SpecTL.setLAngleLoc(LAngleLoc);
2302 SpecTL.setRAngleLoc(RAngleLoc);
2303 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2304 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002305
Abramo Bagnara4244b432012-01-27 08:46:19 +00002306 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2307 // constructor or destructor name (in such a case, the scope specifier
2308 // will be attached to the enclosing Decl or Expr node).
2309 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002310 // Create an elaborated-type-specifier containing the nested-name-specifier.
2311 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2312 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002313 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002314 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2315 }
2316
2317 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002318}
John McCall06f6fe8d2009-09-04 01:14:41 +00002319
Douglas Gregore7c20652011-03-02 00:47:37 +00002320TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002321 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002322 SourceLocation TagLoc,
2323 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002324 SourceLocation TemplateKWLoc,
2325 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002326 SourceLocation TemplateLoc,
2327 SourceLocation LAngleLoc,
2328 ASTTemplateArgsPtr TemplateArgsIn,
2329 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002330 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002331
2332 // Translate the parser's template argument list in our AST format.
2333 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2334 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2335
2336 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002337 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002338 ElaboratedTypeKeyword Keyword
2339 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002340
Douglas Gregore7c20652011-03-02 00:47:37 +00002341 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2342 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2343 DTN->getQualifier(),
2344 DTN->getIdentifier(),
2345 TemplateArgs);
2346
2347 // Build type-source information.
2348 TypeLocBuilder TLB;
2349 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002350 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2351 SpecTL.setElaboratedKeywordLoc(TagLoc);
2352 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002353 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002354 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002355 SpecTL.setLAngleLoc(LAngleLoc);
2356 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002357 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2358 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2359 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2360 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002361
2362 if (TypeAliasTemplateDecl *TAT =
2363 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2364 // C++0x [dcl.type.elab]p2:
2365 // If the identifier resolves to a typedef-name or the simple-template-id
2366 // resolves to an alias template specialization, the
2367 // elaborated-type-specifier is ill-formed.
2368 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2369 Diag(TAT->getLocation(), diag::note_declared_at);
2370 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002371
2372 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2373 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002374 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002375
2376 // Check the tag kind
2377 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002378 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002379
John McCalld8fe9af2009-09-08 17:47:29 +00002380 IdentifierInfo *Id = D->getIdentifier();
2381 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002382
Richard Trieucaa33d32011-06-10 03:11:26 +00002383 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002384 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002385 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002386 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002387 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002388 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002389 }
2390 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002391
Douglas Gregore7c20652011-03-02 00:47:37 +00002392 // Provide source-location information for the template specialization.
2393 TypeLocBuilder TLB;
2394 TemplateSpecializationTypeLoc SpecTL
2395 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002396 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002397 SpecTL.setTemplateNameLoc(TemplateLoc);
2398 SpecTL.setLAngleLoc(LAngleLoc);
2399 SpecTL.setRAngleLoc(RAngleLoc);
2400 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2401 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002402
Douglas Gregore7c20652011-03-02 00:47:37 +00002403 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002404 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002405 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2406 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002407 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002408 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2409 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002410}
2411
Larisse Voufo39a1e502013-08-06 01:03:05 +00002412static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002413 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2414 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002415
2416static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2417 NamedDecl *PrevDecl,
2418 SourceLocation Loc,
2419 bool IsPartialSpecialization);
2420
2421static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002422
Richard Smith300e0c32013-09-24 04:49:23 +00002423static bool isTemplateArgumentTemplateParameter(
2424 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2425 switch (Arg.getKind()) {
2426 case TemplateArgument::Null:
2427 case TemplateArgument::NullPtr:
2428 case TemplateArgument::Integral:
2429 case TemplateArgument::Declaration:
2430 case TemplateArgument::Pack:
2431 case TemplateArgument::TemplateExpansion:
2432 return false;
2433
2434 case TemplateArgument::Type: {
2435 QualType Type = Arg.getAsType();
2436 const TemplateTypeParmType *TPT =
2437 Arg.getAsType()->getAs<TemplateTypeParmType>();
2438 return TPT && !Type.hasQualifiers() &&
2439 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2440 }
2441
2442 case TemplateArgument::Expression: {
2443 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2444 if (!DRE || !DRE->getDecl())
2445 return false;
2446 const NonTypeTemplateParmDecl *NTTP =
2447 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2448 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2449 }
2450
2451 case TemplateArgument::Template:
2452 const TemplateTemplateParmDecl *TTP =
2453 dyn_cast_or_null<TemplateTemplateParmDecl>(
2454 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2455 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2456 }
2457 llvm_unreachable("unexpected kind of template argument");
2458}
2459
2460static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2461 ArrayRef<TemplateArgument> Args) {
2462 if (Params->size() != Args.size())
2463 return false;
2464
2465 unsigned Depth = Params->getDepth();
2466
2467 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2468 TemplateArgument Arg = Args[I];
2469
2470 // If the parameter is a pack expansion, the argument must be a pack
2471 // whose only element is a pack expansion.
2472 if (Params->getParam(I)->isParameterPack()) {
2473 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2474 !Arg.pack_begin()->isPackExpansion())
2475 return false;
2476 Arg = Arg.pack_begin()->getPackExpansionPattern();
2477 }
2478
2479 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2480 return false;
2481 }
2482
2483 return true;
2484}
2485
Richard Smith4b55a9c2014-04-17 03:29:33 +00002486/// Convert the parser's template argument list representation into our form.
2487static TemplateArgumentListInfo
2488makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2489 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2490 TemplateId.RAngleLoc);
2491 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2492 TemplateId.NumArgs);
2493 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2494 return TemplateArgs;
2495}
2496
Larisse Voufo39a1e502013-08-06 01:03:05 +00002497DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002498 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002499 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002500 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002501 // D must be variable template id.
2502 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2503 "Variable template specialization is declared with a template it.");
2504
2505 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002506 TemplateArgumentListInfo TemplateArgs =
2507 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002508 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2509 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2510 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002511
Richard Smithbeef3452014-01-16 23:39:20 +00002512 TemplateName Name = TemplateId->Template.get();
2513
2514 // The template-id must name a variable template.
2515 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002516 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2517 if (!VarTemplate) {
2518 NamedDecl *FnTemplate;
2519 if (auto *OTS = Name.getAsOverloadedTemplate())
2520 FnTemplate = *OTS->begin();
2521 else
2522 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2523 if (FnTemplate)
2524 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2525 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002526 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2527 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002528 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002529
2530 // Check for unexpanded parameter packs in any of the template arguments.
2531 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2532 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2533 UPPC_PartialSpecialization))
2534 return true;
2535
2536 // Check that the template argument list is well-formed for this
2537 // template.
2538 SmallVector<TemplateArgument, 4> Converted;
2539 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2540 false, Converted))
2541 return true;
2542
Larisse Voufo39a1e502013-08-06 01:03:05 +00002543 // Find the variable template (partial) specialization declaration that
2544 // corresponds to these arguments.
2545 if (IsPartialSpecialization) {
2546 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002547 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2548 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002549 return true;
2550
2551 bool InstantiationDependent;
2552 if (!Name.isDependent() &&
2553 !TemplateSpecializationType::anyDependentTemplateArguments(
2554 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2555 InstantiationDependent)) {
2556 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2557 << VarTemplate->getDeclName();
2558 IsPartialSpecialization = false;
2559 }
Richard Smith300e0c32013-09-24 04:49:23 +00002560
2561 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2562 Converted)) {
2563 // C++ [temp.class.spec]p9b3:
2564 //
2565 // -- The argument list of the specialization shall not be identical
2566 // to the implicit argument list of the primary template.
2567 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2568 << /*variable template*/ 1
2569 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2570 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2571 // FIXME: Recover from this by treating the declaration as a redeclaration
2572 // of the primary template.
2573 return true;
2574 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002575 }
2576
Craig Topperc3ec1492014-05-26 06:22:03 +00002577 void *InsertPos = nullptr;
2578 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002579
2580 if (IsPartialSpecialization)
2581 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002582 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002583 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002584 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002585
Craig Topperc3ec1492014-05-26 06:22:03 +00002586 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002587
2588 // Check whether we can declare a variable template specialization in
2589 // the current scope.
2590 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2591 TemplateNameLoc,
2592 IsPartialSpecialization))
2593 return true;
2594
2595 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2596 // Since the only prior variable template specialization with these
2597 // arguments was referenced but not declared, reuse that
2598 // declaration node as our own, updating its source location and
2599 // the list of outer template parameters to reflect our new declaration.
2600 Specialization = PrevDecl;
2601 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002602 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002603 } else if (IsPartialSpecialization) {
2604 // Create a new class template partial specialization declaration node.
2605 VarTemplatePartialSpecializationDecl *PrevPartial =
2606 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002607 VarTemplatePartialSpecializationDecl *Partial =
2608 VarTemplatePartialSpecializationDecl::Create(
2609 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2610 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002611 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002612
2613 if (!PrevPartial)
2614 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2615 Specialization = Partial;
2616
2617 // If we are providing an explicit specialization of a member variable
2618 // template specialization, make a note of that.
2619 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002620 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002621
2622 // Check that all of the template parameters of the variable template
2623 // partial specialization are deducible from the template
2624 // arguments. If not, this variable template partial specialization
2625 // will never be used.
2626 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2627 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2628 TemplateParams->getDepth(), DeducibleParams);
2629
2630 if (!DeducibleParams.all()) {
2631 unsigned NumNonDeducible =
2632 DeducibleParams.size() - DeducibleParams.count();
2633 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002634 << /*variable template*/ 1 << (NumNonDeducible > 1)
2635 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002636 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2637 if (!DeducibleParams[I]) {
2638 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2639 if (Param->getDeclName())
2640 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2641 << Param->getDeclName();
2642 else
2643 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002644 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002645 }
2646 }
2647 }
2648 } else {
2649 // Create a new class template specialization declaration node for
2650 // this explicit specialization or friend declaration.
2651 Specialization = VarTemplateSpecializationDecl::Create(
2652 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2653 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2654 Specialization->setTemplateArgsInfo(TemplateArgs);
2655
2656 if (!PrevDecl)
2657 VarTemplate->AddSpecialization(Specialization, InsertPos);
2658 }
2659
2660 // C++ [temp.expl.spec]p6:
2661 // If a template, a member template or the member of a class template is
2662 // explicitly specialized then that specialization shall be declared
2663 // before the first use of that specialization that would cause an implicit
2664 // instantiation to take place, in every translation unit in which such a
2665 // use occurs; no diagnostic is required.
2666 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2667 bool Okay = false;
2668 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2669 // Is there any previous explicit specialization declaration?
2670 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2671 Okay = true;
2672 break;
2673 }
2674 }
2675
2676 if (!Okay) {
2677 SourceRange Range(TemplateNameLoc, RAngleLoc);
2678 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2679 << Name << Range;
2680
2681 Diag(PrevDecl->getPointOfInstantiation(),
2682 diag::note_instantiation_required_here)
2683 << (PrevDecl->getTemplateSpecializationKind() !=
2684 TSK_ImplicitInstantiation);
2685 return true;
2686 }
2687 }
2688
2689 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2690 Specialization->setLexicalDeclContext(CurContext);
2691
2692 // Add the specialization into its lexical context, so that it can
2693 // be seen when iterating through the list of declarations in that
2694 // context. However, specializations are not found by name lookup.
2695 CurContext->addDecl(Specialization);
2696
2697 // Note that this is an explicit specialization.
2698 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2699
2700 if (PrevDecl) {
2701 // Check that this isn't a redefinition of this specialization,
2702 // merging with previous declarations.
2703 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2704 ForRedeclaration);
2705 PrevSpec.addDecl(PrevDecl);
2706 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002707 } else if (Specialization->isStaticDataMember() &&
2708 Specialization->isOutOfLine()) {
2709 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002710 }
2711
2712 // Link instantiations of static data members back to the template from
2713 // which they were instantiated.
2714 if (Specialization->isStaticDataMember())
2715 Specialization->setInstantiationOfStaticDataMember(
2716 VarTemplate->getTemplatedDecl(),
2717 Specialization->getSpecializationKind());
2718
2719 return Specialization;
2720}
2721
2722namespace {
2723/// \brief A partial specialization whose template arguments have matched
2724/// a given template-id.
2725struct PartialSpecMatchResult {
2726 VarTemplatePartialSpecializationDecl *Partial;
2727 TemplateArgumentList *Args;
2728};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002729} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00002730
2731DeclResult
2732Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2733 SourceLocation TemplateNameLoc,
2734 const TemplateArgumentListInfo &TemplateArgs) {
2735 assert(Template && "A variable template id without template?");
2736
2737 // Check that the template argument list is well-formed for this template.
2738 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002739 if (CheckTemplateArgumentList(
2740 Template, TemplateNameLoc,
2741 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002742 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002743 return true;
2744
2745 // Find the variable template specialization declaration that
2746 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002747 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002748 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00002749 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002750 // If we already have a variable template specialization, return it.
2751 return Spec;
2752
2753 // This is the first time we have referenced this variable template
2754 // specialization. Create the canonical declaration and add it to
2755 // the set of specializations, based on the closest partial specialization
2756 // that it represents. That is,
2757 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2758 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2759 Converted.data(), Converted.size());
2760 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2761 bool AmbiguousPartialSpec = false;
2762 typedef PartialSpecMatchResult MatchResult;
2763 SmallVector<MatchResult, 4> Matched;
2764 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002765 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2766 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002767
2768 // 1. Attempt to find the closest partial specialization that this
2769 // specializes, if any.
2770 // If any of the template arguments is dependent, then this is probably
2771 // a placeholder for an incomplete declarative context; which must be
2772 // complete by instantiation time. Thus, do not search through the partial
2773 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002774 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2775 // Perhaps better after unification of DeduceTemplateArguments() and
2776 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002777 bool InstantiationDependent = false;
2778 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2779 TemplateArgs, InstantiationDependent)) {
2780
2781 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2782 Template->getPartialSpecializations(PartialSpecs);
2783
2784 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2785 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2786 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2787
2788 if (TemplateDeductionResult Result =
2789 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2790 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002791 // TODO: Actually use the failed-deduction info?
Larisse Voufo39a1e502013-08-06 01:03:05 +00002792 FailedCandidates.addCandidate()
2793 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2794 (void)Result;
2795 } else {
2796 Matched.push_back(PartialSpecMatchResult());
2797 Matched.back().Partial = Partial;
2798 Matched.back().Args = Info.take();
2799 }
2800 }
2801
Larisse Voufo39a1e502013-08-06 01:03:05 +00002802 if (Matched.size() >= 1) {
2803 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2804 if (Matched.size() == 1) {
2805 // -- If exactly one matching specialization is found, the
2806 // instantiation is generated from that specialization.
2807 // We don't need to do anything for this.
2808 } else {
2809 // -- If more than one matching specialization is found, the
2810 // partial order rules (14.5.4.2) are used to determine
2811 // whether one of the specializations is more specialized
2812 // than the others. If none of the specializations is more
2813 // specialized than all of the other matching
2814 // specializations, then the use of the variable template is
2815 // ambiguous and the program is ill-formed.
2816 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2817 PEnd = Matched.end();
2818 P != PEnd; ++P) {
2819 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2820 PointOfInstantiation) ==
2821 P->Partial)
2822 Best = P;
2823 }
2824
2825 // Determine if the best partial specialization is more specialized than
2826 // the others.
2827 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2828 PEnd = Matched.end();
2829 P != PEnd; ++P) {
2830 if (P != Best && getMoreSpecializedPartialSpecialization(
2831 P->Partial, Best->Partial,
2832 PointOfInstantiation) != Best->Partial) {
2833 AmbiguousPartialSpec = true;
2834 break;
2835 }
2836 }
2837 }
2838
2839 // Instantiate using the best variable template partial specialization.
2840 InstantiationPattern = Best->Partial;
2841 InstantiationArgs = Best->Args;
2842 } else {
2843 // -- If no match is found, the instantiation is generated
2844 // from the primary template.
2845 // InstantiationPattern = Template->getTemplatedDecl();
2846 }
2847 }
2848
Larisse Voufo39a1e502013-08-06 01:03:05 +00002849 // 2. Create the canonical declaration.
2850 // Note that we do not instantiate the variable just yet, since
2851 // instantiation is handled in DoMarkVarDeclReferenced().
2852 // FIXME: LateAttrs et al.?
2853 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2854 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2855 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2856 if (!Decl)
2857 return true;
2858
2859 if (AmbiguousPartialSpec) {
2860 // Partial ordering did not produce a clear winner. Complain.
2861 Decl->setInvalidDecl();
2862 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2863 << Decl;
2864
2865 // Print the matching partial specializations.
2866 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2867 PEnd = Matched.end();
2868 P != PEnd; ++P)
2869 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2870 << getTemplateArgumentBindingsText(
2871 P->Partial->getTemplateParameters(), *P->Args);
2872 return true;
2873 }
2874
2875 if (VarTemplatePartialSpecializationDecl *D =
2876 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2877 Decl->setInstantiationOf(D, InstantiationArgs);
2878
2879 assert(Decl && "No variable template specialization?");
2880 return Decl;
2881}
2882
2883ExprResult
2884Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2885 const DeclarationNameInfo &NameInfo,
2886 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2887 const TemplateArgumentListInfo *TemplateArgs) {
2888
2889 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2890 *TemplateArgs);
2891 if (Decl.isInvalid())
2892 return ExprError();
2893
2894 VarDecl *Var = cast<VarDecl>(Decl.get());
2895 if (!Var->getTemplateSpecializationKind())
2896 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2897 NameInfo.getLoc());
2898
2899 // Build an ordinary singleton decl ref.
2900 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002901 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002902}
2903
John McCalldadc5752010-08-24 06:29:42 +00002904ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002905 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002906 LookupResult &R,
2907 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002908 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002909 // FIXME: Can we do any checking at this point? I guess we could check the
2910 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002911 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002912 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002913 // foo<int> could identify a single function unambiguously
2914 // This approach does NOT work, since f<int>(1);
2915 // gets resolved prior to resorting to overload resolution
2916 // i.e., template<class T> void f(double);
2917 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002918
2919 // These should be filtered out by our callers.
2920 assert(!R.empty() && "empty lookup results when building templateid");
2921 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2922
Larisse Voufo39a1e502013-08-06 01:03:05 +00002923 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002924 bool InstantiationDependent;
2925 if (R.getAsSingle<VarTemplateDecl>() &&
2926 !TemplateSpecializationType::anyDependentTemplateArguments(
2927 *TemplateArgs, InstantiationDependent)) {
2928 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2929 R.getAsSingle<VarTemplateDecl>(),
2930 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002931 }
2932
John McCall58cc69d2010-01-27 01:50:18 +00002933 // We don't want lookup warnings at this point.
2934 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002935
John McCalle66edc12009-11-24 19:00:30 +00002936 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002937 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002938 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002939 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002940 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002941 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002942 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002943
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002944 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00002945}
2946
John McCalle66edc12009-11-24 19:00:30 +00002947// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002948ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002949Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002950 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002951 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002952 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002953
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002954 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002955 DeclContext *DC;
2956 if (!(DC = computeDeclContext(SS, false)) ||
2957 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002958 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00002959 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002960
Douglas Gregor786123d2010-05-21 23:18:07 +00002961 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002962 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00002963 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002964 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002965
John McCalle66edc12009-11-24 19:00:30 +00002966 if (R.isAmbiguous())
2967 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002968
John McCalle66edc12009-11-24 19:00:30 +00002969 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002970 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2971 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002972 return ExprError();
2973 }
2974
2975 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002976 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00002977 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00002978 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002979 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2980 return ExprError();
2981 }
2982
Abramo Bagnara7945c982012-01-27 09:46:47 +00002983 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00002984}
2985
Douglas Gregorb67535d2009-03-31 00:43:58 +00002986/// \brief Form a dependent template name.
2987///
2988/// This action forms a dependent template name given the template
2989/// name and its (presumably dependent) scope specifier. For
2990/// example, given "MetaFun::template apply", the scope specifier \p
2991/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2992/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002993TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00002994 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002995 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00002996 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00002997 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00002998 bool EnteringContext,
2999 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003000 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3001 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003002 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003003 diag::warn_cxx98_compat_template_outside_of_template :
3004 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003005 << FixItHint::CreateRemoval(TemplateKWLoc);
3006
Craig Topperc3ec1492014-05-26 06:22:03 +00003007 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003008 if (SS.isSet())
3009 LookupCtx = computeDeclContext(SS, EnteringContext);
3010 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003011 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003012 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003013 // C++0x [temp.names]p5:
3014 // If a name prefixed by the keyword template is not the name of
3015 // a template, the program is ill-formed. [Note: the keyword
3016 // template may not be applied to non-template members of class
3017 // templates. -end note ] [ Note: as is the case with the
3018 // typename prefix, the template prefix is allowed in cases
3019 // where it is not strictly necessary; i.e., when the
3020 // nested-name-specifier or the expression on the left of the ->
3021 // or . is not dependent on a template-parameter, or the use
3022 // does not appear in the scope of a template. -end note]
3023 //
3024 // Note: C++03 was more strict here, because it banned the use of
3025 // the "template" keyword prior to a template-name that was not a
3026 // dependent name. C++ DR468 relaxed this requirement (the
3027 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003028 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003029 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003030 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003031 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003032 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003033 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3034 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003035 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3036 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003037 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003038 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003039 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003040 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003041 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003042 << Name.getSourceRange()
3043 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003044 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003045 } else {
3046 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003047 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003048 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003049 }
3050
Aaron Ballman4a979672014-01-03 13:56:08 +00003051 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003052
Douglas Gregor3cf81312009-11-03 23:16:33 +00003053 switch (Name.getKind()) {
3054 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003055 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003056 Name.Identifier));
3057 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003058
Douglas Gregor71395fa2009-11-04 00:56:37 +00003059 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003060 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003061 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003062 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003063
3064 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003065 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003066
Douglas Gregor3cf81312009-11-03 23:16:33 +00003067 default:
3068 break;
3069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003070
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003071 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003072 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003073 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003074 << Name.getSourceRange()
3075 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003076 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003077}
3078
Mike Stump11289f42009-09-09 15:08:12 +00003079bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003080 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003081 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003082 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003083 QualType ArgType;
3084 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003085
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003086 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003087 switch(Arg.getKind()) {
3088 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003089 // C++ [temp.arg.type]p1:
3090 // A template-argument for a template-parameter which is a
3091 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003092 ArgType = Arg.getAsType();
3093 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003094 break;
3095 case TemplateArgument::Template: {
3096 // We have a template type parameter but the template argument
3097 // is a template without any arguments.
3098 SourceRange SR = AL.getSourceRange();
3099 TemplateName Name = Arg.getAsTemplate();
3100 Diag(SR.getBegin(), diag::err_template_missing_args)
3101 << Name << SR;
3102 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3103 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003104
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003105 return true;
3106 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003107 case TemplateArgument::Expression: {
3108 // We have a template type parameter but the template argument is an
3109 // expression; see if maybe it is missing the "typename" keyword.
3110 CXXScopeSpec SS;
3111 DeclarationNameInfo NameInfo;
3112
3113 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3114 SS.Adopt(ArgExpr->getQualifierLoc());
3115 NameInfo = ArgExpr->getNameInfo();
3116 } else if (DependentScopeDeclRefExpr *ArgExpr =
3117 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3118 SS.Adopt(ArgExpr->getQualifierLoc());
3119 NameInfo = ArgExpr->getNameInfo();
3120 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3121 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003122 if (ArgExpr->isImplicitAccess()) {
3123 SS.Adopt(ArgExpr->getQualifierLoc());
3124 NameInfo = ArgExpr->getMemberNameInfo();
3125 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003126 }
3127
Reid Kleckner377c1592014-06-10 23:29:48 +00003128 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003129 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3130 LookupParsedName(Result, CurScope, &SS);
3131
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003132 if (Result.getAsSingle<TypeDecl>() ||
3133 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003134 LookupResult::NotFoundInCurrentInstantiation) {
3135 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003136 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003137 Diag(Loc, getLangOpts().MSVCCompat
3138 ? diag::ext_ms_template_type_arg_missing_typename
3139 : diag::err_template_arg_must_be_type_suggest)
3140 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003141 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003142
3143 // Recover by synthesizing a type using the location information that we
3144 // already have.
3145 ArgType =
3146 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3147 TypeLocBuilder TLB;
3148 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3149 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3150 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3151 TL.setNameLoc(NameInfo.getLoc());
3152 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3153
3154 // Overwrite our input TemplateArgumentLoc so that we can recover
3155 // properly.
3156 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3157 TemplateArgumentLocInfo(TSI));
3158
3159 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003160 }
3161 }
3162 // fallthrough
3163 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003164 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003165 // We have a template type parameter but the template argument
3166 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003167 SourceRange SR = AL.getSourceRange();
3168 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003169 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003170
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003171 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003172 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003173 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003174
Reid Kleckner377c1592014-06-10 23:29:48 +00003175 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003176 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003177
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003178 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003179 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003180
3181 // Objective-C ARC:
3182 // If an explicitly-specified template argument type is a lifetime type
3183 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003184 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003185 ArgType->isObjCLifetimeType() &&
3186 !ArgType.getObjCLifetime()) {
3187 Qualifiers Qs;
3188 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3189 ArgType = Context.getQualifiedType(ArgType, Qs);
3190 }
3191
3192 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003193 return false;
3194}
3195
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003196/// \brief Substitute template arguments into the default template argument for
3197/// the given template type parameter.
3198///
3199/// \param SemaRef the semantic analysis object for which we are performing
3200/// the substitution.
3201///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003202/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003203/// for.
3204///
3205/// \param TemplateLoc the location of the template name that started the
3206/// template-id we are checking.
3207///
3208/// \param RAngleLoc the location of the right angle bracket ('>') that
3209/// terminates the template-id.
3210///
3211/// \param Param the template template parameter whose default we are
3212/// substituting into.
3213///
3214/// \param Converted the list of template arguments provided for template
3215/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003216/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003217static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003218SubstDefaultTemplateArgument(Sema &SemaRef,
3219 TemplateDecl *Template,
3220 SourceLocation TemplateLoc,
3221 SourceLocation RAngleLoc,
3222 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003223 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003224 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003225
3226 // If the argument type is dependent, instantiate it now based
3227 // on the previously-computed template arguments.
3228 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003229 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003230 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003231 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003232 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003233 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003234
David Majnemer89189202013-08-28 23:48:32 +00003235 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3236 Converted.data(), Converted.size());
3237
3238 // Only substitute for the innermost template argument list.
3239 MultiLevelTemplateArgumentList TemplateArgLists;
3240 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3241 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3242 TemplateArgLists.addOuterTemplateArguments(None);
3243
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003244 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003245 ArgType =
3246 SemaRef.SubstType(ArgType, TemplateArgLists,
3247 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003248 }
3249
3250 return ArgType;
3251}
3252
3253/// \brief Substitute template arguments into the default template argument for
3254/// the given non-type template parameter.
3255///
3256/// \param SemaRef the semantic analysis object for which we are performing
3257/// the substitution.
3258///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003259/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003260/// for.
3261///
3262/// \param TemplateLoc the location of the template name that started the
3263/// template-id we are checking.
3264///
3265/// \param RAngleLoc the location of the right angle bracket ('>') that
3266/// terminates the template-id.
3267///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003268/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003269/// substituting into.
3270///
3271/// \param Converted the list of template arguments provided for template
3272/// parameters that precede \p Param in the template parameter list.
3273///
3274/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003275static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003276SubstDefaultTemplateArgument(Sema &SemaRef,
3277 TemplateDecl *Template,
3278 SourceLocation TemplateLoc,
3279 SourceLocation RAngleLoc,
3280 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003281 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003282 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003283 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003284 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003285 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003286 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003287
David Majnemer89189202013-08-28 23:48:32 +00003288 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3289 Converted.data(), Converted.size());
3290
3291 // Only substitute for the innermost template argument list.
3292 MultiLevelTemplateArgumentList TemplateArgLists;
3293 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3294 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3295 TemplateArgLists.addOuterTemplateArguments(None);
3296
Faisal Vali48401eb2015-11-19 19:20:17 +00003297 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3298 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003299 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003300}
3301
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003302/// \brief Substitute template arguments into the default template argument for
3303/// the given template template parameter.
3304///
3305/// \param SemaRef the semantic analysis object for which we are performing
3306/// the substitution.
3307///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003308/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003309/// for.
3310///
3311/// \param TemplateLoc the location of the template name that started the
3312/// template-id we are checking.
3313///
3314/// \param RAngleLoc the location of the right angle bracket ('>') that
3315/// terminates the template-id.
3316///
3317/// \param Param the template template parameter whose default we are
3318/// substituting into.
3319///
3320/// \param Converted the list of template arguments provided for template
3321/// parameters that precede \p Param in the template parameter list.
3322///
Douglas Gregordf846d12011-03-02 18:46:51 +00003323/// \param QualifierLoc Will be set to the nested-name-specifier (with
3324/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003325///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003326/// \returns the substituted template argument, or NULL if an error occurred.
3327static TemplateName
3328SubstDefaultTemplateArgument(Sema &SemaRef,
3329 TemplateDecl *Template,
3330 SourceLocation TemplateLoc,
3331 SourceLocation RAngleLoc,
3332 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003333 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003334 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003335 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003336 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003337 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003338 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003339
David Majnemer89189202013-08-28 23:48:32 +00003340 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3341 Converted.data(), Converted.size());
3342
3343 // Only substitute for the innermost template argument list.
3344 MultiLevelTemplateArgumentList TemplateArgLists;
3345 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3346 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3347 TemplateArgLists.addOuterTemplateArguments(None);
3348
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003349 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003350 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003351 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003352 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003353 QualifierLoc =
3354 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003355 if (!QualifierLoc)
3356 return TemplateName();
3357 }
David Majnemer89189202013-08-28 23:48:32 +00003358
3359 return SemaRef.SubstTemplateName(
3360 QualifierLoc,
3361 Param->getDefaultArgument().getArgument().getAsTemplate(),
3362 Param->getDefaultArgument().getTemplateNameLoc(),
3363 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003364}
3365
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003366/// \brief If the given template parameter has a default template
3367/// argument, substitute into that default template argument and
3368/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003369TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003370Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3371 SourceLocation TemplateLoc,
3372 SourceLocation RAngleLoc,
3373 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003374 SmallVectorImpl<TemplateArgument>
3375 &Converted,
3376 bool &HasDefaultArg) {
3377 HasDefaultArg = false;
3378
3379 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003380 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003381 return TemplateArgumentLoc();
3382
Richard Smithc87b9382013-07-04 01:01:24 +00003383 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003384 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003385 TemplateLoc,
3386 RAngleLoc,
3387 TypeParm,
3388 Converted);
3389 if (DI)
3390 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3391
3392 return TemplateArgumentLoc();
3393 }
3394
3395 if (NonTypeTemplateParmDecl *NonTypeParm
3396 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003397 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003398 return TemplateArgumentLoc();
3399
Richard Smithc87b9382013-07-04 01:01:24 +00003400 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003401 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003402 TemplateLoc,
3403 RAngleLoc,
3404 NonTypeParm,
3405 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003406 if (Arg.isInvalid())
3407 return TemplateArgumentLoc();
3408
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003409 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003410 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3411 }
3412
3413 TemplateTemplateParmDecl *TempTempParm
3414 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003415 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003416 return TemplateArgumentLoc();
3417
Richard Smithc87b9382013-07-04 01:01:24 +00003418 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003419 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003420 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003421 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003422 RAngleLoc,
3423 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003424 Converted,
3425 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003426 if (TName.isNull())
3427 return TemplateArgumentLoc();
3428
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003429 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003430 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003431 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3432}
3433
Douglas Gregorda0fb532009-11-11 19:31:23 +00003434/// \brief Check that the given template argument corresponds to the given
3435/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003436///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003437/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003438/// checked.
3439///
Richard Trieu15b66532015-01-24 02:48:32 +00003440/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003441///
3442/// \param Template The template in which the template argument resides.
3443///
3444/// \param TemplateLoc The location of the template name for the template
3445/// whose argument list we're matching.
3446///
3447/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3448/// the template argument list.
3449///
3450/// \param ArgumentPackIndex The index into the argument pack where this
3451/// argument will be placed. Only valid if the parameter is a parameter pack.
3452///
3453/// \param Converted The checked, converted argument will be added to the
3454/// end of this small vector.
3455///
3456/// \param CTAK Describes how we arrived at this particular template argument:
3457/// explicitly written, deduced, etc.
3458///
3459/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003460bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003461 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003462 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003463 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003464 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003465 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003466 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003467 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003468 // Check template type parameters.
3469 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003470 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003471
Douglas Gregoreebed722009-11-11 19:41:09 +00003472 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003474 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003475 // with the template arguments we've seen thus far. But if the
3476 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003477 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003478 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3479 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003480
Peter Collingbourne01687632010-12-10 17:08:53 +00003481 if (NTTPType->isDependentType() &&
3482 !isa<TemplateTemplateParmDecl>(Template) &&
3483 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003484 // Do substitution on the type of the non-type template parameter.
3485 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003486 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003487 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003488 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003489 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490
3491 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003492 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003493 NTTPType = SubstType(NTTPType,
3494 MultiLevelTemplateArgumentList(TemplateArgs),
3495 NTTP->getLocation(),
3496 NTTP->getDeclName());
3497 // If that worked, check the non-type template parameter type
3498 // for validity.
3499 if (!NTTPType.isNull())
3500 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3501 NTTP->getLocation());
3502 if (NTTPType.isNull())
3503 return true;
3504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003505
Douglas Gregorda0fb532009-11-11 19:31:23 +00003506 switch (Arg.getArgument().getKind()) {
3507 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003508 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003509
Douglas Gregorda0fb532009-11-11 19:31:23 +00003510 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003511 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003512 ExprResult Res =
3513 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3514 Result, CTAK);
3515 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003516 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003517
Richard Trieu15b66532015-01-24 02:48:32 +00003518 // If the resulting expression is new, then use it in place of the
3519 // old expression in the template argument.
3520 if (Res.get() != Arg.getArgument().getAsExpr()) {
3521 TemplateArgument TA(Res.get());
3522 Arg = TemplateArgumentLoc(TA, Res.get());
3523 }
3524
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003525 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003526 break;
3527 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003528
Douglas Gregorda0fb532009-11-11 19:31:23 +00003529 case TemplateArgument::Declaration:
3530 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003531 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003532 // We've already checked this template argument, so just copy
3533 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003534 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003535 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003536
Douglas Gregorda0fb532009-11-11 19:31:23 +00003537 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003538 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003539 // We were given a template template argument. It may not be ill-formed;
3540 // see below.
3541 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003542 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3543 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003544 // We have a template argument such as \c T::template X, which we
3545 // parsed as a template template argument. However, since we now
3546 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003547 // template name into an expression.
3548
3549 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3550 Arg.getTemplateNameLoc());
3551
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003552 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003553 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003554 // FIXME: the template-template arg was a DependentTemplateName,
3555 // so it was provided with a template keyword. However, its source
3556 // location is not stored in the template argument structure.
3557 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003558 ExprResult E = DependentScopeDeclRefExpr::Create(
3559 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3560 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003561
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003562 // If we parsed the template argument as a pack expansion, create a
3563 // pack expansion expression.
3564 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003565 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003566 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003567 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003569
Douglas Gregorda0fb532009-11-11 19:31:23 +00003570 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003571 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003572 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003573 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003574
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003575 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003576 break;
3577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003578
Douglas Gregorda0fb532009-11-11 19:31:23 +00003579 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003580 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003581 // therefore cannot be a non-type template argument.
3582 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3583 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003584
Douglas Gregorda0fb532009-11-11 19:31:23 +00003585 Diag(Param->getLocation(), diag::note_template_param_here);
3586 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003587
Douglas Gregorda0fb532009-11-11 19:31:23 +00003588 case TemplateArgument::Type: {
3589 // We have a non-type template parameter but the template
3590 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003591
Douglas Gregorda0fb532009-11-11 19:31:23 +00003592 // C++ [temp.arg]p2:
3593 // In a template-argument, an ambiguity between a type-id and
3594 // an expression is resolved to a type-id, regardless of the
3595 // form of the corresponding template-parameter.
3596 //
3597 // We warn specifically about this case, since it can be rather
3598 // confusing for users.
3599 QualType T = Arg.getArgument().getAsType();
3600 SourceRange SR = Arg.getSourceRange();
3601 if (T->isFunctionType())
3602 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3603 else
3604 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3605 Diag(Param->getLocation(), diag::note_template_param_here);
3606 return true;
3607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003608
Douglas Gregorda0fb532009-11-11 19:31:23 +00003609 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003610 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003612
Douglas Gregorda0fb532009-11-11 19:31:23 +00003613 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003614 }
3615
3616
Douglas Gregorda0fb532009-11-11 19:31:23 +00003617 // Check template template parameters.
3618 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003619
Douglas Gregorda0fb532009-11-11 19:31:23 +00003620 // Substitute into the template parameter list of the template
3621 // template parameter, since previously-supplied template arguments
3622 // may appear within the template template parameter.
3623 {
3624 // Set up a template instantiation context.
3625 LocalInstantiationScope Scope(*this);
3626 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003627 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003628 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003629 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003630 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003631
3632 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003633 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003634 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003635 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003636 MultiLevelTemplateArgumentList(TemplateArgs)));
3637 if (!TempParm)
3638 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003639 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640
Douglas Gregorda0fb532009-11-11 19:31:23 +00003641 switch (Arg.getArgument().getKind()) {
3642 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003643 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003644
Douglas Gregorda0fb532009-11-11 19:31:23 +00003645 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003646 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003647 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003648 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003649
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003650 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003651 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003652
Douglas Gregorda0fb532009-11-11 19:31:23 +00003653 case TemplateArgument::Expression:
3654 case TemplateArgument::Type:
3655 // We have a template template parameter but the template
3656 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003657 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003658 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003659 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003660
Douglas Gregorda0fb532009-11-11 19:31:23 +00003661 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003662 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003663 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003664 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003665 case TemplateArgument::NullPtr:
3666 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667
Douglas Gregorda0fb532009-11-11 19:31:23 +00003668 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003669 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Douglas Gregorda0fb532009-11-11 19:31:23 +00003672 return false;
3673}
3674
Douglas Gregor8e072612012-02-03 07:34:46 +00003675/// \brief Diagnose an arity mismatch in the
3676static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3677 SourceLocation TemplateLoc,
3678 TemplateArgumentListInfo &TemplateArgs) {
3679 TemplateParameterList *Params = Template->getTemplateParameters();
3680 unsigned NumParams = Params->size();
3681 unsigned NumArgs = TemplateArgs.size();
3682
3683 SourceRange Range;
3684 if (NumArgs > NumParams)
3685 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3686 TemplateArgs.getRAngleLoc());
3687 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3688 << (NumArgs > NumParams)
3689 << (isa<ClassTemplateDecl>(Template)? 0 :
3690 isa<FunctionTemplateDecl>(Template)? 1 :
3691 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3692 << Template << Range;
3693 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3694 << Params->getSourceRange();
3695 return true;
3696}
3697
Richard Smith1fde8ec2012-09-07 02:06:42 +00003698/// \brief Check whether the template parameter is a pack expansion, and if so,
3699/// determine the number of parameters produced by that expansion. For instance:
3700///
3701/// \code
3702/// template<typename ...Ts> struct A {
3703/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3704/// };
3705/// \endcode
3706///
3707/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3708/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003709static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003710 if (NonTypeTemplateParmDecl *NTTP
3711 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3712 if (NTTP->isExpandedParameterPack())
3713 return NTTP->getNumExpansionTypes();
3714 }
3715
3716 if (TemplateTemplateParmDecl *TTP
3717 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3718 if (TTP->isExpandedParameterPack())
3719 return TTP->getNumExpansionTemplateParameters();
3720 }
3721
David Blaikie7a30dc52013-02-21 01:47:18 +00003722 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003723}
3724
Richard Smith35c1df52015-06-17 20:16:32 +00003725/// Diagnose a missing template argument.
3726template<typename TemplateParmDecl>
3727static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3728 TemplateDecl *TD,
3729 const TemplateParmDecl *D,
3730 TemplateArgumentListInfo &Args) {
3731 // Dig out the most recent declaration of the template parameter; there may be
3732 // declarations of the template that are more recent than TD.
3733 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3734 ->getTemplateParameters()
3735 ->getParam(D->getIndex()));
3736
3737 // If there's a default argument that's not visible, diagnose that we're
3738 // missing a module import.
3739 llvm::SmallVector<Module*, 8> Modules;
3740 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3741 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3742 D->getDefaultArgumentLoc(), Modules,
3743 Sema::MissingImportKind::DefaultArgument,
3744 /*Recover*/ true);
3745 return true;
3746 }
3747
3748 // FIXME: If there's a more recent default argument that *is* visible,
3749 // diagnose that it was declared too late.
3750
3751 return diagnoseArityMismatch(S, TD, Loc, Args);
3752}
3753
Douglas Gregord32e0282009-02-09 23:23:08 +00003754/// \brief Check that the given template argument list is well-formed
3755/// for specializing the given template.
3756bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3757 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003758 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003759 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003760 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003761 // Make a copy of the template arguments for processing. Only make the
3762 // changes at the end when successful in matching the arguments to the
3763 // template.
3764 TemplateArgumentListInfo NewArgs = TemplateArgs;
3765
Douglas Gregord32e0282009-02-09 23:23:08 +00003766 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003767
Richard Trieu15b66532015-01-24 02:48:32 +00003768 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003769
Mike Stump11289f42009-09-09 15:08:12 +00003770 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003771 // [...] The type and form of each template-argument specified in
3772 // a template-id shall match the type and form specified for the
3773 // corresponding parameter declared by the template in its
3774 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003775 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003776 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003777 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003778 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003779 for (TemplateParameterList::iterator Param = Params->begin(),
3780 ParamEnd = Params->end();
3781 Param != ParamEnd; /* increment in loop */) {
3782 // If we have an expanded parameter pack, make sure we don't have too
3783 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003784 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003785 if (*Expansions == ArgumentPack.size()) {
3786 // We're done with this parameter pack. Pack up its arguments and add
3787 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003788 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00003789 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003790 ArgumentPack.clear();
3791
Richard Smith1fde8ec2012-09-07 02:06:42 +00003792 // This argument is assigned to the next parameter.
3793 ++Param;
3794 continue;
3795 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3796 // Not enough arguments for this parameter pack.
3797 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3798 << false
3799 << (isa<ClassTemplateDecl>(Template)? 0 :
3800 isa<FunctionTemplateDecl>(Template)? 1 :
3801 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3802 << Template;
3803 Diag(Template->getLocation(), diag::note_template_decl_here)
3804 << Params->getSourceRange();
3805 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003806 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003808
Richard Smith1fde8ec2012-09-07 02:06:42 +00003809 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003810 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003811 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003812 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003813 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003814 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003815
Richard Smith96d71c32014-11-12 23:38:38 +00003816 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003817 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003818 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3819 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003820 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003821 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003822 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003823 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003824 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003825 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003826 Diag((*Param)->getLocation(), diag::note_template_param_here);
3827 return true;
3828 }
3829
Richard Smith1fde8ec2012-09-07 02:06:42 +00003830 // We're now done with this argument.
3831 ++ArgIdx;
3832
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003833 if ((*Param)->isTemplateParameterPack()) {
3834 // The template parameter was a template parameter pack, so take the
3835 // deduced argument and place it on the argument pack. Note that we
3836 // stay on the same template parameter so that we can deduce more
3837 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003838 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003839 } else {
3840 // Move to the next template parameter.
3841 ++Param;
3842 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003843
Richard Smith96d71c32014-11-12 23:38:38 +00003844 // If we just saw a pack expansion into a non-pack, then directly convert
3845 // the remaining arguments, because we don't know what parameters they'll
3846 // match up with.
3847 if (PackExpansionIntoNonPack) {
3848 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003849 // If we were part way through filling in an expanded parameter pack,
3850 // fall back to just producing individual arguments.
3851 Converted.insert(Converted.end(),
3852 ArgumentPack.begin(), ArgumentPack.end());
3853 ArgumentPack.clear();
3854 }
3855
3856 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003857 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003858 ++ArgIdx;
3859 }
3860
Richard Smith1fde8ec2012-09-07 02:06:42 +00003861 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003862 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003863
Douglas Gregor84d49a22009-11-11 21:54:23 +00003864 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003865 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003866
Douglas Gregor2f157c92011-06-03 02:59:40 +00003867 // If we're checking a partial template argument list, we're done.
3868 if (PartialTemplateArgs) {
3869 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00003870 Converted.push_back(
3871 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3872
Richard Smith1fde8ec2012-09-07 02:06:42 +00003873 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003874 }
3875
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003876 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003877 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003878 if ((*Param)->isTemplateParameterPack()) {
3879 assert(!getExpandedPackSize(*Param) &&
3880 "Should have dealt with this already");
3881
3882 // A non-expanded parameter pack before the end of the parameter list
3883 // only occurs for an ill-formed template parameter list, unless we've
3884 // got a partial argument list for a function template, so just bail out.
3885 if (Param + 1 != ParamEnd)
3886 return true;
3887
Benjamin Kramercce63472015-08-05 09:40:22 +00003888 Converted.push_back(
3889 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003890 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003891
3892 ++Param;
3893 continue;
3894 }
3895
Douglas Gregor8e072612012-02-03 07:34:46 +00003896 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003897 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003898
Douglas Gregor84d49a22009-11-11 21:54:23 +00003899 // Retrieve the default template argument from the template
3900 // parameter. For each kind of template parameter, we substitute the
3901 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003902 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003903 // the default argument.
3904 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003905 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003906 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3907 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003908
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003909 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003910 Template,
3911 TemplateLoc,
3912 RAngleLoc,
3913 TTP,
3914 Converted);
3915 if (!ArgType)
3916 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003917
Douglas Gregor84d49a22009-11-11 21:54:23 +00003918 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3919 ArgType);
3920 } else if (NonTypeTemplateParmDecl *NTTP
3921 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003922 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003923 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3924 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003925
John McCalldadc5752010-08-24 06:29:42 +00003926 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003927 TemplateLoc,
3928 RAngleLoc,
3929 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003930 Converted);
3931 if (E.isInvalid())
3932 return true;
3933
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003934 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00003935 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3936 } else {
3937 TemplateTemplateParmDecl *TempParm
3938 = cast<TemplateTemplateParmDecl>(*Param);
3939
Richard Smith95d83952015-06-10 20:36:34 +00003940 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00003941 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3942 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003943
Douglas Gregordf846d12011-03-02 18:46:51 +00003944 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003945 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003946 TemplateLoc,
3947 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003948 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003949 Converted,
3950 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003951 if (Name.isNull())
3952 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003953
Douglas Gregor9d802122011-03-02 17:09:35 +00003954 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3955 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003956 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003957
Douglas Gregor84d49a22009-11-11 21:54:23 +00003958 // Introduce an instantiation record that describes where we are using
3959 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003960 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3961 SourceRange(TemplateLoc, RAngleLoc));
3962 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003963 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003964
Douglas Gregor84d49a22009-11-11 21:54:23 +00003965 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003966 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003967 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003968 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003969
Richard Trieu15b66532015-01-24 02:48:32 +00003970 // Core issue 150 (assumed resolution): if this is a template template
3971 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00003972 // template definition.
3973 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00003974 NewArgs.addArgument(Arg);
3975
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003976 // Move to the next template parameter and argument.
3977 ++Param;
3978 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003980
Richard Smith07f79912014-06-06 16:00:50 +00003981 // If we're performing a partial argument substitution, allow any trailing
3982 // pack expansions; they might be empty. This can happen even if
3983 // PartialTemplateArgs is false (the list of arguments is complete but
3984 // still dependent).
3985 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3986 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00003987 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3988 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00003989 }
3990
Douglas Gregor8e072612012-02-03 07:34:46 +00003991 // If we have any leftover arguments, then there were too many arguments.
3992 // Complain and fail.
3993 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00003994 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3995
3996 // No problems found with the new argument list, propagate changes back
3997 // to caller.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00003998 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003999
Richard Smith1fde8ec2012-09-07 02:06:42 +00004000 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004001}
4002
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004003namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004004 class UnnamedLocalNoLinkageFinder
4005 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004006 {
4007 Sema &S;
4008 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004009
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004010 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004011
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004012 public:
4013 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4014
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004015 bool Visit(QualType T) {
4016 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004017 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004018
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004019#define TYPE(Class, Parent) \
4020 bool Visit##Class##Type(const Class##Type *);
4021#define ABSTRACT_TYPE(Class, Parent) \
4022 bool Visit##Class##Type(const Class##Type *) { return false; }
4023#define NON_CANONICAL_TYPE(Class, Parent) \
4024 bool Visit##Class##Type(const Class##Type *) { return false; }
4025#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004026
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004027 bool VisitTagDecl(const TagDecl *Tag);
4028 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4029 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004030} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004031
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004032bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004033 return false;
4034}
4035
4036bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4037 return Visit(T->getElementType());
4038}
4039
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004040bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004041 return Visit(T->getPointeeType());
4042}
4043
4044bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004045 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004046 return Visit(T->getPointeeType());
4047}
4048
4049bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004051 return Visit(T->getPointeeType());
4052}
4053
4054bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004055 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004056 return Visit(T->getPointeeType());
4057}
4058
4059bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004060 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004061 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4062}
4063
4064bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004066 return Visit(T->getElementType());
4067}
4068
4069bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004070 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004071 return Visit(T->getElementType());
4072}
4073
4074bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004075 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004076 return Visit(T->getElementType());
4077}
4078
4079bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004080 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004081 return Visit(T->getElementType());
4082}
4083
4084bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004085 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004086 return Visit(T->getElementType());
4087}
4088
4089bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4090 return Visit(T->getElementType());
4091}
4092
4093bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4094 return Visit(T->getElementType());
4095}
4096
4097bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4098 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004099 for (const auto &A : T->param_types()) {
4100 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004101 return true;
4102 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103
Alp Toker314cc812014-01-25 16:55:45 +00004104 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004105}
4106
4107bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4108 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004109 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004110}
4111
4112bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4113 const UnresolvedUsingType*) {
4114 return false;
4115}
4116
4117bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4118 return false;
4119}
4120
4121bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4122 return Visit(T->getUnderlyingType());
4123}
4124
4125bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4126 return false;
4127}
4128
Alexis Hunte852b102011-05-24 22:41:36 +00004129bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4130 const UnaryTransformType*) {
4131 return false;
4132}
4133
Richard Smith30482bc2011-02-20 03:19:35 +00004134bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4135 return Visit(T->getDeducedType());
4136}
4137
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004138bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4139 return VisitTagDecl(T->getDecl());
4140}
4141
4142bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4143 return VisitTagDecl(T->getDecl());
4144}
4145
4146bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4147 const TemplateTypeParmType*) {
4148 return false;
4149}
4150
Douglas Gregorada4b792011-01-14 02:55:32 +00004151bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4152 const SubstTemplateTypeParmPackType *) {
4153 return false;
4154}
4155
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004156bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4157 const TemplateSpecializationType*) {
4158 return false;
4159}
4160
4161bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4162 const InjectedClassNameType* T) {
4163 return VisitTagDecl(T->getDecl());
4164}
4165
4166bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4167 const DependentNameType* T) {
4168 return VisitNestedNameSpecifier(T->getQualifier());
4169}
4170
4171bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4172 const DependentTemplateSpecializationType* T) {
4173 return VisitNestedNameSpecifier(T->getQualifier());
4174}
4175
Douglas Gregord2fa7662010-12-20 02:24:11 +00004176bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4177 const PackExpansionType* T) {
4178 return Visit(T->getPattern());
4179}
4180
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004181bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4182 return false;
4183}
4184
4185bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4186 const ObjCInterfaceType *) {
4187 return false;
4188}
4189
4190bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4191 const ObjCObjectPointerType *) {
4192 return false;
4193}
4194
Eli Friedman0dfb8892011-10-06 23:00:33 +00004195bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4196 return Visit(T->getValueType());
4197}
4198
Xiuli Pan9c14e282016-01-09 12:53:17 +00004199bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4200 return false;
4201}
4202
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004203bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4204 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004205 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004206 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004207 diag::warn_cxx98_compat_template_arg_local_type :
4208 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004209 << S.Context.getTypeDeclType(Tag) << SR;
4210 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211 }
4212
John McCall5ea95772013-03-09 00:54:27 +00004213 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004214 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004215 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004216 diag::warn_cxx98_compat_template_arg_unnamed_type :
4217 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004218 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4219 return true;
4220 }
4221
4222 return false;
4223}
4224
4225bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4226 NestedNameSpecifier *NNS) {
4227 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4228 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004229
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004230 switch (NNS->getKind()) {
4231 case NestedNameSpecifier::Identifier:
4232 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004233 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004234 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004235 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004236 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004237
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004238 case NestedNameSpecifier::TypeSpec:
4239 case NestedNameSpecifier::TypeSpecWithTemplate:
4240 return Visit(QualType(NNS->getAsType(), 0));
4241 }
David Blaikie8a40f702012-01-17 06:56:22 +00004242 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004243}
4244
Douglas Gregord32e0282009-02-09 23:23:08 +00004245/// \brief Check a template argument against its corresponding
4246/// template type parameter.
4247///
4248/// This routine implements the semantics of C++ [temp.arg.type]. It
4249/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004250bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004251 TypeSourceInfo *ArgInfo) {
4252 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004253 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004254 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004255
4256 if (Arg->isVariablyModifiedType()) {
4257 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004258 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004259 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004260 }
4261
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004262 // C++03 [temp.arg.type]p2:
4263 // A local type, a type with no linkage, an unnamed type or a type
4264 // compounded from any of these types shall not be used as a
4265 // template-argument for a template type-parameter.
4266 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004267 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004268 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004269 bool NeedsCheck;
4270 if (LangOpts.CPlusPlus11)
4271 NeedsCheck =
4272 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4273 SR.getBegin()) ||
4274 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4275 SR.getBegin());
4276 else
4277 NeedsCheck = Arg->hasUnnamedOrLocalType();
4278
4279 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004280 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4281 (void)Finder.Visit(Context.getCanonicalType(Arg));
4282 }
4283
Douglas Gregord32e0282009-02-09 23:23:08 +00004284 return false;
4285}
4286
Douglas Gregor20fdef32012-04-10 17:08:25 +00004287enum NullPointerValueKind {
4288 NPV_NotNullPointer,
4289 NPV_NullPointer,
4290 NPV_Error
4291};
4292
4293/// \brief Determine whether the given template argument is a null pointer
4294/// value of the appropriate type.
4295static NullPointerValueKind
4296isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4297 QualType ParamType, Expr *Arg) {
4298 if (Arg->isValueDependent() || Arg->isTypeDependent())
4299 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004300
Richard Smithdb0ac552015-12-18 22:40:25 +00004301 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004302 llvm_unreachable(
4303 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004304
David Majnemer5c734ad2014-08-14 00:49:23 +00004305 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004306 return NPV_NotNullPointer;
4307
4308 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004309 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4310 if (ArgRV.isInvalid())
4311 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004312 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004313
Douglas Gregor20fdef32012-04-10 17:08:25 +00004314 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004315 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004316 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004317 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004318 EvalResult.HasSideEffects) {
4319 SourceLocation DiagLoc = Arg->getExprLoc();
4320
4321 // If our only note is the usual "invalid subexpression" note, just point
4322 // the caret at its location rather than producing an essentially
4323 // redundant note.
4324 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4325 diag::note_invalid_subexpr_in_const_expr) {
4326 DiagLoc = Notes[0].first;
4327 Notes.clear();
4328 }
4329
4330 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4331 << Arg->getType() << Arg->getSourceRange();
4332 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4333 S.Diag(Notes[I].first, Notes[I].second);
4334
4335 S.Diag(Param->getLocation(), diag::note_template_param_here);
4336 return NPV_Error;
4337 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004338
4339 // C++11 [temp.arg.nontype]p1:
4340 // - an address constant expression of type std::nullptr_t
4341 if (Arg->getType()->isNullPtrType())
4342 return NPV_NullPointer;
4343
4344 // - a constant expression that evaluates to a null pointer value (4.10); or
4345 // - a constant expression that evaluates to a null member pointer value
4346 // (4.11); or
4347 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4348 (EvalResult.Val.isMemberPointer() &&
4349 !EvalResult.Val.getMemberPointerDecl())) {
4350 // If our expression has an appropriate type, we've succeeded.
4351 bool ObjCLifetimeConversion;
4352 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4353 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4354 ObjCLifetimeConversion))
4355 return NPV_NullPointer;
4356
4357 // The types didn't match, but we know we got a null pointer; complain,
4358 // then recover as if the types were correct.
4359 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4360 << Arg->getType() << ParamType << Arg->getSourceRange();
4361 S.Diag(Param->getLocation(), diag::note_template_param_here);
4362 return NPV_NullPointer;
4363 }
4364
4365 // If we don't have a null pointer value, but we do have a NULL pointer
4366 // constant, suggest a cast to the appropriate type.
4367 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4368 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4369 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004370 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4371 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4372 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004373 S.Diag(Param->getLocation(), diag::note_template_param_here);
4374 return NPV_NullPointer;
4375 }
4376
4377 // FIXME: If we ever want to support general, address-constant expressions
4378 // as non-type template arguments, we should return the ExprResult here to
4379 // be interpreted by the caller.
4380 return NPV_NotNullPointer;
4381}
4382
David Majnemer61c39a12013-08-23 05:39:39 +00004383/// \brief Checks whether the given template argument is compatible with its
4384/// template parameter.
4385static bool CheckTemplateArgumentIsCompatibleWithParameter(
4386 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4387 Expr *Arg, QualType ArgType) {
4388 bool ObjCLifetimeConversion;
4389 if (ParamType->isPointerType() &&
4390 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4391 S.IsQualificationConversion(ArgType, ParamType, false,
4392 ObjCLifetimeConversion)) {
4393 // For pointer-to-object types, qualification conversions are
4394 // permitted.
4395 } else {
4396 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4397 if (!ParamRef->getPointeeType()->isFunctionType()) {
4398 // C++ [temp.arg.nontype]p5b3:
4399 // For a non-type template-parameter of type reference to
4400 // object, no conversions apply. The type referred to by the
4401 // reference may be more cv-qualified than the (otherwise
4402 // identical) type of the template- argument. The
4403 // template-parameter is bound directly to the
4404 // template-argument, which shall be an lvalue.
4405
4406 // FIXME: Other qualifiers?
4407 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4408 unsigned ArgQuals = ArgType.getCVRQualifiers();
4409
4410 if ((ParamQuals | ArgQuals) != ParamQuals) {
4411 S.Diag(Arg->getLocStart(),
4412 diag::err_template_arg_ref_bind_ignores_quals)
4413 << ParamType << Arg->getType() << Arg->getSourceRange();
4414 S.Diag(Param->getLocation(), diag::note_template_param_here);
4415 return true;
4416 }
4417 }
4418 }
4419
4420 // At this point, the template argument refers to an object or
4421 // function with external linkage. We now need to check whether the
4422 // argument and parameter types are compatible.
4423 if (!S.Context.hasSameUnqualifiedType(ArgType,
4424 ParamType.getNonReferenceType())) {
4425 // We can't perform this conversion or binding.
4426 if (ParamType->isReferenceType())
4427 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4428 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4429 else
4430 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4431 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4432 S.Diag(Param->getLocation(), diag::note_template_param_here);
4433 return true;
4434 }
4435 }
4436
4437 return false;
4438}
4439
Douglas Gregorccb07762009-02-11 19:52:55 +00004440/// \brief Checks whether the given template argument is the address
4441/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004443CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4444 NonTypeTemplateParmDecl *Param,
4445 QualType ParamType,
4446 Expr *ArgIn,
4447 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004448 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004449 Expr *Arg = ArgIn;
4450 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004451
Douglas Gregorb242683d2010-04-01 18:32:35 +00004452 bool AddressTaken = false;
4453 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004454 if (S.getLangOpts().MicrosoftExt) {
4455 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4456 // dereference and address-of operators.
4457 Arg = Arg->IgnoreParenCasts();
4458
4459 bool ExtWarnMSTemplateArg = false;
4460 UnaryOperatorKind FirstOpKind;
4461 SourceLocation FirstOpLoc;
4462 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4463 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4464 if (UnOpKind == UO_Deref)
4465 ExtWarnMSTemplateArg = true;
4466 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4467 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4468 if (!AddrOpLoc.isValid()) {
4469 FirstOpKind = UnOpKind;
4470 FirstOpLoc = UnOp->getOperatorLoc();
4471 }
4472 } else
4473 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004474 }
David Majnemer61c39a12013-08-23 05:39:39 +00004475 if (FirstOpLoc.isValid()) {
4476 if (ExtWarnMSTemplateArg)
4477 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4478 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004479
David Majnemer61c39a12013-08-23 05:39:39 +00004480 if (FirstOpKind == UO_AddrOf)
4481 AddressTaken = true;
4482 else if (Arg->getType()->isPointerType()) {
4483 // We cannot let pointers get dereferenced here, that is obviously not a
4484 // constant expression.
4485 assert(FirstOpKind == UO_Deref);
4486 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4487 << Arg->getSourceRange();
4488 }
4489 }
4490 } else {
4491 // See through any implicit casts we added to fix the type.
4492 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004493
David Majnemer61c39a12013-08-23 05:39:39 +00004494 // C++ [temp.arg.nontype]p1:
4495 //
4496 // A template-argument for a non-type, non-template
4497 // template-parameter shall be one of: [...]
4498 //
4499 // -- the address of an object or function with external
4500 // linkage, including function templates and function
4501 // template-ids but excluding non-static class members,
4502 // expressed as & id-expression where the & is optional if
4503 // the name refers to a function or array, or if the
4504 // corresponding template-parameter is a reference; or
4505
4506 // In C++98/03 mode, give an extension warning on any extra parentheses.
4507 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4508 bool ExtraParens = false;
4509 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4510 if (!Invalid && !ExtraParens) {
4511 S.Diag(Arg->getLocStart(),
4512 S.getLangOpts().CPlusPlus11
4513 ? diag::warn_cxx98_compat_template_arg_extra_parens
4514 : diag::ext_template_arg_extra_parens)
4515 << Arg->getSourceRange();
4516 ExtraParens = true;
4517 }
4518
4519 Arg = Parens->getSubExpr();
4520 }
4521
4522 while (SubstNonTypeTemplateParmExpr *subst =
4523 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4524 Arg = subst->getReplacement()->IgnoreImpCasts();
4525
4526 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4527 if (UnOp->getOpcode() == UO_AddrOf) {
4528 Arg = UnOp->getSubExpr();
4529 AddressTaken = true;
4530 AddrOpLoc = UnOp->getOperatorLoc();
4531 }
4532 }
4533
4534 while (SubstNonTypeTemplateParmExpr *subst =
4535 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4536 Arg = subst->getReplacement()->IgnoreImpCasts();
4537 }
John McCall7c454bb2011-07-15 05:09:51 +00004538
David Majnemer07910d62014-06-26 07:48:46 +00004539 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4540 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4541
4542 // If our parameter has pointer type, check for a null template value.
4543 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4544 NullPointerValueKind NPV;
4545 // dllimport'd entities aren't constant but are available inside of template
4546 // arguments.
4547 if (Entity && Entity->hasAttr<DLLImportAttr>())
4548 NPV = NPV_NotNullPointer;
4549 else
4550 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4551 switch (NPV) {
4552 case NPV_NullPointer:
4553 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004554 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4555 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004556 return false;
4557
4558 case NPV_Error:
4559 return true;
4560
4561 case NPV_NotNullPointer:
4562 break;
4563 }
4564 }
4565
Chandler Carruth724a8a12010-01-31 10:01:20 +00004566 // Stop checking the precise nature of the argument if it is value dependent,
4567 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004568 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004569 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004570 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004571 }
David Majnemer61c39a12013-08-23 05:39:39 +00004572
4573 if (isa<CXXUuidofExpr>(Arg)) {
4574 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4575 ArgIn, Arg, ArgType))
4576 return true;
4577
4578 Converted = TemplateArgument(ArgIn);
4579 return false;
4580 }
4581
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004582 if (!DRE) {
4583 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4584 << Arg->getSourceRange();
4585 S.Diag(Param->getLocation(), diag::note_template_param_here);
4586 return true;
4587 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004588
Douglas Gregorccb07762009-02-11 19:52:55 +00004589 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004590 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004591 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004592 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004593 S.Diag(Param->getLocation(), diag::note_template_param_here);
4594 return true;
4595 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004596
4597 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004598 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004599 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004600 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004601 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004602 S.Diag(Param->getLocation(), diag::note_template_param_here);
4603 return true;
4604 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004605 }
Mike Stump11289f42009-09-09 15:08:12 +00004606
Richard Smith9380e0e2012-04-04 21:11:30 +00004607 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4608 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004609
Richard Smith9380e0e2012-04-04 21:11:30 +00004610 // A non-type template argument must refer to an object or function.
4611 if (!Func && !Var) {
4612 // We found something, but we don't know specifically what it is.
4613 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4614 << Arg->getSourceRange();
4615 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4616 return true;
4617 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004618
Richard Smith9380e0e2012-04-04 21:11:30 +00004619 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004620 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004621 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004622 diag::warn_cxx98_compat_template_arg_object_internal :
4623 diag::ext_template_arg_object_internal)
4624 << !Func << Entity << Arg->getSourceRange();
4625 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4626 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004627 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004628 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4629 << !Func << Entity << Arg->getSourceRange();
4630 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4631 << !Func;
4632 return true;
4633 }
4634
4635 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004636 // If the template parameter has pointer type, the function decays.
4637 if (ParamType->isPointerType() && !AddressTaken)
4638 ArgType = S.Context.getPointerType(Func->getType());
4639 else if (AddressTaken && ParamType->isReferenceType()) {
4640 // If we originally had an address-of operator, but the
4641 // parameter has reference type, complain and (if things look
4642 // like they will work) drop the address-of operator.
4643 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4644 ParamType.getNonReferenceType())) {
4645 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4646 << ParamType;
4647 S.Diag(Param->getLocation(), diag::note_template_param_here);
4648 return true;
4649 }
4650
4651 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4652 << ParamType
4653 << FixItHint::CreateRemoval(AddrOpLoc);
4654 S.Diag(Param->getLocation(), diag::note_template_param_here);
4655
4656 ArgType = Func->getType();
4657 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004658 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004659 // A value of reference type is not an object.
4660 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004661 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004662 diag::err_template_arg_reference_var)
4663 << Var->getType() << Arg->getSourceRange();
4664 S.Diag(Param->getLocation(), diag::note_template_param_here);
4665 return true;
4666 }
4667
Richard Smith9380e0e2012-04-04 21:11:30 +00004668 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004669 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004670 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4671 << Arg->getSourceRange();
4672 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4673 return true;
4674 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004675
4676 // If the template parameter has pointer type, we must have taken
4677 // the address of this object.
4678 if (ParamType->isReferenceType()) {
4679 if (AddressTaken) {
4680 // If we originally had an address-of operator, but the
4681 // parameter has reference type, complain and (if things look
4682 // like they will work) drop the address-of operator.
4683 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4684 ParamType.getNonReferenceType())) {
4685 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4686 << ParamType;
4687 S.Diag(Param->getLocation(), diag::note_template_param_here);
4688 return true;
4689 }
4690
4691 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4692 << ParamType
4693 << FixItHint::CreateRemoval(AddrOpLoc);
4694 S.Diag(Param->getLocation(), diag::note_template_param_here);
4695
4696 ArgType = Var->getType();
4697 }
4698 } else if (!AddressTaken && ParamType->isPointerType()) {
4699 if (Var->getType()->isArrayType()) {
4700 // Array-to-pointer decay.
4701 ArgType = S.Context.getArrayDecayedType(Var->getType());
4702 } else {
4703 // If the template parameter has pointer type but the address of
4704 // this object was not taken, complain and (possibly) recover by
4705 // taking the address of the entity.
4706 ArgType = S.Context.getPointerType(Var->getType());
4707 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4708 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4709 << ParamType;
4710 S.Diag(Param->getLocation(), diag::note_template_param_here);
4711 return true;
4712 }
4713
4714 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4715 << ParamType
4716 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4717
4718 S.Diag(Param->getLocation(), diag::note_template_param_here);
4719 }
4720 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004721 }
Mike Stump11289f42009-09-09 15:08:12 +00004722
David Majnemer61c39a12013-08-23 05:39:39 +00004723 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4724 Arg, ArgType))
4725 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004726
4727 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004728 Converted =
4729 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004730 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004731 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004732}
4733
4734/// \brief Checks whether the given template argument is a pointer to
4735/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004736static bool CheckTemplateArgumentPointerToMember(Sema &S,
4737 NonTypeTemplateParmDecl *Param,
4738 QualType ParamType,
4739 Expr *&ResultArg,
4740 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004741 bool Invalid = false;
4742
Douglas Gregor20fdef32012-04-10 17:08:25 +00004743 // Check for a null pointer value.
4744 Expr *Arg = ResultArg;
4745 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4746 case NPV_Error:
4747 return true;
4748 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004749 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004750 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4751 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004752 return false;
4753 case NPV_NotNullPointer:
4754 break;
4755 }
4756
4757 bool ObjCLifetimeConversion;
4758 if (S.IsQualificationConversion(Arg->getType(),
4759 ParamType.getNonReferenceType(),
4760 false, ObjCLifetimeConversion)) {
4761 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004762 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004763 ResultArg = Arg;
4764 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4765 ParamType.getNonReferenceType())) {
4766 // We can't perform this conversion.
4767 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4768 << Arg->getType() << ParamType << Arg->getSourceRange();
4769 S.Diag(Param->getLocation(), diag::note_template_param_here);
4770 return true;
4771 }
4772
Douglas Gregorccb07762009-02-11 19:52:55 +00004773 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004774 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004775 Arg = Cast->getSubExpr();
4776
4777 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004778 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004779 // A template-argument for a non-type, non-template
4780 // template-parameter shall be one of: [...]
4781 //
4782 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004783 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004784
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004785 // In C++98/03 mode, give an extension warning on any extra parentheses.
4786 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4787 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004788 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004789 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004790 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004791 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004792 diag::warn_cxx98_compat_template_arg_extra_parens :
4793 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004794 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004795 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004796 }
4797
4798 Arg = Parens->getSubExpr();
4799 }
4800
John McCall7c454bb2011-07-15 05:09:51 +00004801 while (SubstNonTypeTemplateParmExpr *subst =
4802 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4803 Arg = subst->getReplacement()->IgnoreImpCasts();
4804
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004805 // A pointer-to-member constant written &Class::member.
4806 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004807 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004808 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4809 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004810 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004811 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004812 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004813 // A constant of pointer-to-member type.
4814 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4815 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4816 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004817 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004818 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004819 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004820 } else {
4821 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004822 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004823 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004824 return Invalid;
4825 }
4826 }
4827 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004828
Craig Topperc3ec1492014-05-26 06:22:03 +00004829 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004830 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004831
Douglas Gregorccb07762009-02-11 19:52:55 +00004832 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004833 return S.Diag(Arg->getLocStart(),
4834 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004835 << Arg->getSourceRange();
4836
David Majnemer3ac84e62013-10-22 21:56:38 +00004837 if (isa<FieldDecl>(DRE->getDecl()) ||
4838 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4839 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004840 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004841 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004842 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4843 "Only non-static member pointers can make it here");
4844
4845 // Okay: this is the address of a non-static member, and therefore
4846 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004847 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004848 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004849 } else {
4850 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004851 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004852 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004853 return Invalid;
4854 }
4855
4856 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004857 S.Diag(Arg->getLocStart(),
4858 diag::err_template_arg_not_pointer_to_member_form)
4859 << Arg->getSourceRange();
4860 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004861 return true;
4862}
4863
Douglas Gregord32e0282009-02-09 23:23:08 +00004864/// \brief Check a template argument against its corresponding
4865/// non-type template parameter.
4866///
Douglas Gregor463421d2009-03-03 04:44:36 +00004867/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004868/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004869/// returns the converted template argument. \p ParamType is the
4870/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004871ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004872 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004873 TemplateArgument &Converted,
4874 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004875 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004876
Douglas Gregor86560402009-02-10 23:36:10 +00004877 // If either the parameter has a dependent type or the argument is
4878 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004879 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004880 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004881 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004882 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004883 }
Douglas Gregor86560402009-02-10 23:36:10 +00004884
Richard Smithd663fdd2014-12-17 20:42:37 +00004885 // We should have already dropped all cv-qualifiers by now.
4886 assert(!ParamType.hasQualifiers() &&
4887 "non-type template parameter type cannot be qualified");
4888
4889 if (CTAK == CTAK_Deduced &&
4890 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4891 // C++ [temp.deduct.type]p17:
4892 // If, in the declaration of a function template with a non-type
4893 // template-parameter, the non-type template-parameter is used
4894 // in an expression in the function parameter-list and, if the
4895 // corresponding template-argument is deduced, the
4896 // template-argument type shall match the type of the
4897 // template-parameter exactly, except that a template-argument
4898 // deduced from an array bound may be of any integral type.
4899 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4900 << Arg->getType().getUnqualifiedType()
4901 << ParamType.getUnqualifiedType();
4902 Diag(Param->getLocation(), diag::note_template_param_here);
4903 return ExprError();
4904 }
4905
Richard Smith410cc892014-11-26 03:26:53 +00004906 if (getLangOpts().CPlusPlus1z) {
4907 // FIXME: We can do some limited checking for a value-dependent but not
4908 // type-dependent argument.
4909 if (Arg->isValueDependent()) {
4910 Converted = TemplateArgument(Arg);
4911 return Arg;
4912 }
4913
4914 // C++1z [temp.arg.nontype]p1:
4915 // A template-argument for a non-type template parameter shall be
4916 // a converted constant expression of the type of the template-parameter.
4917 APValue Value;
4918 ExprResult ArgResult = CheckConvertedConstantExpression(
4919 Arg, ParamType, Value, CCEK_TemplateArg);
4920 if (ArgResult.isInvalid())
4921 return ExprError();
4922
Richard Smithd663fdd2014-12-17 20:42:37 +00004923 QualType CanonParamType = Context.getCanonicalType(ParamType);
4924
Richard Smith410cc892014-11-26 03:26:53 +00004925 // Convert the APValue to a TemplateArgument.
4926 switch (Value.getKind()) {
4927 case APValue::Uninitialized:
4928 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004929 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004930 break;
4931 case APValue::Int:
4932 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004933 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00004934 break;
4935 case APValue::MemberPointer: {
4936 assert(ParamType->isMemberPointerType());
4937
4938 // FIXME: We need TemplateArgument representation and mangling for these.
4939 if (!Value.getMemberPointerPath().empty()) {
4940 Diag(Arg->getLocStart(),
4941 diag::err_template_arg_member_ptr_base_derived_not_supported)
4942 << Value.getMemberPointerDecl() << ParamType
4943 << Arg->getSourceRange();
4944 return ExprError();
4945 }
4946
4947 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00004948 Converted = VD ? TemplateArgument(VD, CanonParamType)
4949 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004950 break;
4951 }
4952 case APValue::LValue: {
4953 // For a non-type template-parameter of pointer or reference type,
4954 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00004955 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4956 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00004957 // -- a temporary object
4958 // -- a string literal
4959 // -- the result of a typeid expression, or
4960 // -- a predefind __func__ variable
4961 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4962 if (isa<CXXUuidofExpr>(E)) {
4963 Converted = TemplateArgument(const_cast<Expr*>(E));
4964 break;
4965 }
4966 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4967 << Arg->getSourceRange();
4968 return ExprError();
4969 }
4970 auto *VD = const_cast<ValueDecl *>(
4971 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4972 // -- a subobject
4973 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4974 VD && VD->getType()->isArrayType() &&
4975 Value.getLValuePath()[0].ArrayIndex == 0 &&
4976 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4977 // Per defect report (no number yet):
4978 // ... other than a pointer to the first element of a complete array
4979 // object.
4980 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4981 Value.isLValueOnePastTheEnd()) {
4982 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4983 << Value.getAsString(Context, ParamType);
4984 return ExprError();
4985 }
Richard Smithd663fdd2014-12-17 20:42:37 +00004986 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00004987 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00004988 assert((!VD || !ParamType->isNullPtrType()) &&
4989 "non-null value of type nullptr_t?");
4990 Converted = VD ? TemplateArgument(VD, CanonParamType)
4991 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004992 break;
4993 }
4994 case APValue::AddrLabelDiff:
4995 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4996 case APValue::Float:
4997 case APValue::ComplexInt:
4998 case APValue::ComplexFloat:
4999 case APValue::Vector:
5000 case APValue::Array:
5001 case APValue::Struct:
5002 case APValue::Union:
5003 llvm_unreachable("invalid kind for template argument");
5004 }
5005
5006 return ArgResult.get();
5007 }
5008
Douglas Gregor86560402009-02-10 23:36:10 +00005009 // C++ [temp.arg.nontype]p5:
5010 // The following conversions are performed on each expression used
5011 // as a non-type template-argument. If a non-type
5012 // template-argument cannot be converted to the type of the
5013 // corresponding template-parameter then the program is
5014 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005015 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005016 // C++11:
5017 // -- for a non-type template-parameter of integral or
5018 // enumeration type, conversions permitted in a converted
5019 // constant expression are applied.
5020 //
5021 // C++98:
5022 // -- for a non-type template-parameter of integral or
5023 // enumeration type, integral promotions (4.5) and integral
5024 // conversions (4.7) are applied.
5025
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005026 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005027 // We can't check arbitrary value-dependent arguments.
5028 // FIXME: If there's no viable conversion to the template parameter type,
5029 // we should be able to diagnose that prior to instantiation.
5030 if (Arg->isValueDependent()) {
5031 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005032 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00005033 }
5034
5035 // C++ [temp.arg.nontype]p1:
5036 // A template-argument for a non-type, non-template template-parameter
5037 // shall be one of:
5038 //
5039 // -- for a non-type template-parameter of integral or enumeration
5040 // type, a converted constant expression of the type of the
5041 // template-parameter; or
5042 llvm::APSInt Value;
5043 ExprResult ArgResult =
5044 CheckConvertedConstantExpression(Arg, ParamType, Value,
5045 CCEK_TemplateArg);
5046 if (ArgResult.isInvalid())
5047 return ExprError();
5048
5049 // Widen the argument value to sizeof(parameter type). This is almost
5050 // always a no-op, except when the parameter type is bool. In
5051 // that case, this may extend the argument from 1 bit to 8 bits.
5052 QualType IntegerType = ParamType;
5053 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5054 IntegerType = Enum->getDecl()->getIntegerType();
5055 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5056
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005057 Converted = TemplateArgument(Context, Value,
5058 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005059 return ArgResult;
5060 }
5061
Richard Smith08b12f12011-10-27 22:11:44 +00005062 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5063 if (ArgResult.isInvalid())
5064 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005065 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005066
5067 QualType ArgType = Arg->getType();
5068
Douglas Gregor86560402009-02-10 23:36:10 +00005069 // C++ [temp.arg.nontype]p1:
5070 // A template-argument for a non-type, non-template
5071 // template-parameter shall be one of:
5072 //
5073 // -- an integral constant-expression of integral or enumeration
5074 // type; or
5075 // -- the name of a non-type template-parameter; or
5076 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005077 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005078 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005079 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005080 diag::err_template_arg_not_integral_or_enumeral)
5081 << ArgType << Arg->getSourceRange();
5082 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005083 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005084 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005085 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5086 QualType T;
5087
5088 public:
5089 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005090
5091 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5092 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005093 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5094 }
5095 } Diagnoser(ArgType);
5096
5097 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005098 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005099 if (!Arg)
5100 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005101 }
5102
Richard Smithd663fdd2014-12-17 20:42:37 +00005103 // From here on out, all we care about is the unqualified form
5104 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005105 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005106
5107 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005108 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005109 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005110 } else if (ParamType->isBooleanType()) {
5111 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005112 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005113 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5114 !ParamType->isEnumeralType()) {
5115 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005116 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005117 } else {
5118 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005119 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005120 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005121 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005122 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005123 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005124 }
5125
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005126 // Add the value of this argument to the list of converted
5127 // arguments. We use the bitwidth and signedness of the template
5128 // parameter.
5129 if (Arg->isValueDependent()) {
5130 // The argument is value-dependent. Create a new
5131 // TemplateArgument with the converted expression.
5132 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005133 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005134 }
5135
Douglas Gregor52aba872009-03-14 00:20:21 +00005136 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005137 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005138 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005139
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005140 if (ParamType->isBooleanType()) {
5141 // Value must be zero or one.
5142 Value = Value != 0;
5143 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5144 if (Value.getBitWidth() != AllowedBits)
5145 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005146 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005147 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005148 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005149
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005150 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005151 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005152 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005153 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005154 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005155 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005156
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005157 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005158 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005159 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005160 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005161 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5162 << Arg->getSourceRange();
5163 Diag(Param->getLocation(), diag::note_template_param_here);
5164 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005165
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005166 // Complain if we overflowed the template parameter's type.
5167 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005168 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005169 RequiredBits = OldValue.getActiveBits();
5170 else if (OldValue.isUnsigned())
5171 RequiredBits = OldValue.getActiveBits() + 1;
5172 else
5173 RequiredBits = OldValue.getMinSignedBits();
5174 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005175 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005176 diag::warn_template_arg_too_large)
5177 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5178 << Arg->getSourceRange();
5179 Diag(Param->getLocation(), diag::note_template_param_here);
5180 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005181 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005182
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005183 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005184 ParamType->isEnumeralType()
5185 ? Context.getCanonicalType(ParamType)
5186 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005187 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005188 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005189
Richard Smith08b12f12011-10-27 22:11:44 +00005190 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005191 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5192
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005193 // Handle pointer-to-function, reference-to-function, and
5194 // pointer-to-member-function all in (roughly) the same way.
5195 if (// -- For a non-type template-parameter of type pointer to
5196 // function, only the function-to-pointer conversion (4.3) is
5197 // applied. If the template-argument represents a set of
5198 // overloaded functions (or a pointer to such), the matching
5199 // function is selected from the set (13.4).
5200 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005201 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005202 // -- For a non-type template-parameter of type reference to
5203 // function, no conversions apply. If the template-argument
5204 // represents a set of overloaded functions, the matching
5205 // function is selected from the set (13.4).
5206 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005207 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005208 // -- For a non-type template-parameter of type pointer to
5209 // member function, no conversions apply. If the
5210 // template-argument represents a set of overloaded member
5211 // functions, the matching member function is selected from
5212 // the set (13.4).
5213 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005214 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005215 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005216
Douglas Gregor064fdb22010-04-14 23:11:21 +00005217 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005218 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005219 true,
5220 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005221 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005222 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005223
5224 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5225 ArgType = Arg->getType();
5226 } else
John Wiegley01296292011-04-08 18:41:53 +00005227 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005228 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005229
John Wiegley01296292011-04-08 18:41:53 +00005230 if (!ParamType->isMemberPointerType()) {
5231 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5232 ParamType,
5233 Arg, Converted))
5234 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005235 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005236 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005237
Douglas Gregor20fdef32012-04-10 17:08:25 +00005238 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5239 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005240 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005241 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005242 }
5243
Chris Lattner696197c2009-02-20 21:37:53 +00005244 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005245 // -- for a non-type template-parameter of type pointer to
5246 // object, qualification conversions (4.4) and the
5247 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005248 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005249 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005250 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005251
John Wiegley01296292011-04-08 18:41:53 +00005252 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5253 ParamType,
5254 Arg, Converted))
5255 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005256 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005257 }
Mike Stump11289f42009-09-09 15:08:12 +00005258
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005259 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005260 // -- For a non-type template-parameter of type reference to
5261 // object, no conversions apply. The type referred to by the
5262 // reference may be more cv-qualified than the (otherwise
5263 // identical) type of the template-argument. The
5264 // template-parameter is bound directly to the
5265 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005266 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005267 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005268
Douglas Gregor064fdb22010-04-14 23:11:21 +00005269 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005270 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5271 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005272 true,
5273 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005274 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005275 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005276
5277 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5278 ArgType = Arg->getType();
5279 } else
John Wiegley01296292011-04-08 18:41:53 +00005280 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005281 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005282
John Wiegley01296292011-04-08 18:41:53 +00005283 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5284 ParamType,
5285 Arg, Converted))
5286 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005287 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005288 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005289
Douglas Gregor20fdef32012-04-10 17:08:25 +00005290 // Deal with parameters of type std::nullptr_t.
5291 if (ParamType->isNullPtrType()) {
5292 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5293 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005294 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005295 }
5296
5297 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5298 case NPV_NotNullPointer:
5299 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5300 << Arg->getType() << ParamType;
5301 Diag(Param->getLocation(), diag::note_template_param_here);
5302 return ExprError();
5303
5304 case NPV_Error:
5305 return ExprError();
5306
5307 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005308 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005309 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5310 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005311 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005312 }
5313 }
5314
Douglas Gregor0e558532009-02-11 16:16:59 +00005315 // -- For a non-type template-parameter of type pointer to data
5316 // member, qualification conversions (4.4) are applied.
5317 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5318
Douglas Gregor20fdef32012-04-10 17:08:25 +00005319 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5320 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005321 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005322 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005323}
5324
5325/// \brief Check a template argument against its corresponding
5326/// template template parameter.
5327///
5328/// This routine implements the semantics of C++ [temp.arg.template].
5329/// It returns true if an error occurred, and false otherwise.
5330bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005331 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005332 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005333 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005334 TemplateDecl *Template = Name.getAsTemplateDecl();
5335 if (!Template) {
5336 // Any dependent template name is fine.
5337 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5338 return false;
5339 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005340
Richard Smith3f1b5d02011-05-05 21:57:07 +00005341 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005342 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005343 // the name of a class template or an alias template, expressed as an
5344 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005345 // primary class templates are considered when matching the
5346 // template template argument with the corresponding parameter;
5347 // partial specializations are not considered even if their
5348 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005349 //
5350 // Note that we also allow template template parameters here, which
5351 // will happen when we are dealing with, e.g., class template
5352 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005353 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005354 !isa<TemplateTemplateParmDecl>(Template) &&
5355 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005356 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005357 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00005358 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005359 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005360 << Template;
5361 }
5362
Richard Smith1fde8ec2012-09-07 02:06:42 +00005363 TemplateParameterList *Params = Param->getTemplateParameters();
5364 if (Param->isExpandedParameterPack())
5365 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5366
Douglas Gregor85e0f662009-02-10 00:24:35 +00005367 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005368 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005369 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005370 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005371 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005372}
5373
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005374/// \brief Given a non-type template argument that refers to a
5375/// declaration and the type of its corresponding non-type template
5376/// parameter, produce an expression that properly refers to that
5377/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005378ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005379Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5380 QualType ParamType,
5381 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005382 // C++ [temp.param]p8:
5383 //
5384 // A non-type template-parameter of type "array of T" or
5385 // "function returning T" is adjusted to be of type "pointer to
5386 // T" or "pointer to function returning T", respectively.
5387 if (ParamType->isArrayType())
5388 ParamType = Context.getArrayDecayedType(ParamType);
5389 else if (ParamType->isFunctionType())
5390 ParamType = Context.getPointerType(ParamType);
5391
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005392 // For a NULL non-type template argument, return nullptr casted to the
5393 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005394 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005395 return ImpCastExprToType(
5396 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5397 ParamType,
5398 ParamType->getAs<MemberPointerType>()
5399 ? CK_NullToMemberPointer
5400 : CK_NullToPointer);
5401 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005402 assert(Arg.getKind() == TemplateArgument::Declaration &&
5403 "Only declaration template arguments permitted here");
5404
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005405 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5406
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005407 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005408 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5409 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005410 // If the value is a class member, we might have a pointer-to-member.
5411 // Determine whether the non-type template template parameter is of
5412 // pointer-to-member type. If so, we need to build an appropriate
5413 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5414 // would refer to the member itself.
5415 if (ParamType->isMemberPointerType()) {
5416 QualType ClassType
5417 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5418 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005419 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005420 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005421 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005422 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005423
5424 // The actual value-ness of this is unimportant, but for
5425 // internal consistency's sake, references to instance methods
5426 // are r-values.
5427 ExprValueKind VK = VK_LValue;
5428 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5429 VK = VK_RValue;
5430
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005431 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005432 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005433 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005434 Loc,
5435 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005436 if (RefExpr.isInvalid())
5437 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005438
John McCalle3027922010-08-25 11:45:40 +00005439 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005440
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005441 // We might need to perform a trailing qualification conversion, since
5442 // the element type on the parameter could be more qualified than the
5443 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005444 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005445 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005446 ParamType.getUnqualifiedType(), false,
5447 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005448 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005449
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005450 assert(!RefExpr.isInvalid() &&
5451 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005452 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005453 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005454 }
5455 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005456
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005457 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005458
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005459 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005460 // When the non-type template parameter is a pointer, take the
5461 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005462 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005463 if (RefExpr.isInvalid())
5464 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005465
5466 if (T->isFunctionType() || T->isArrayType()) {
5467 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005468 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005469 if (RefExpr.isInvalid())
5470 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005471
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005472 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005473 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005474
Douglas Gregorb242683d2010-04-01 18:32:35 +00005475 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005476 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005477 }
5478
John McCall7decc9e2010-11-18 06:31:45 +00005479 ExprValueKind VK = VK_RValue;
5480
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005481 // If the non-type template parameter has reference type, qualify the
5482 // resulting declaration reference with the extra qualifiers on the
5483 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005484 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5485 VK = VK_LValue;
5486 T = Context.getQualifiedType(T,
5487 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005488 } else if (isa<FunctionDecl>(VD)) {
5489 // References to functions are always lvalues.
5490 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005492
John McCall7decc9e2010-11-18 06:31:45 +00005493 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005494}
5495
5496/// \brief Construct a new expression that refers to the given
5497/// integral template argument with the given source-location
5498/// information.
5499///
5500/// This routine takes care of the mapping from an integral template
5501/// argument (which may have any integral type) to the appropriate
5502/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005503ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005504Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5505 SourceLocation Loc) {
5506 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005507 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005508 QualType OrigT = Arg.getIntegralType();
5509
5510 // If this is an enum type that we're instantiating, we need to use an integer
5511 // type the same size as the enumerator. We don't want to build an
5512 // IntegerLiteral with enum type. The integer type of an enum type can be of
5513 // any integral type with C++11 enum classes, make sure we create the right
5514 // type of literal for it.
5515 QualType T = OrigT;
5516 if (const EnumType *ET = OrigT->getAs<EnumType>())
5517 T = ET->getDecl()->getIntegerType();
5518
5519 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005520 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005521 // This does not need to handle u8 character literals because those are
5522 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005523 CharacterLiteral::CharacterKind Kind;
5524 if (T->isWideCharType())
5525 Kind = CharacterLiteral::Wide;
5526 else if (T->isChar16Type())
5527 Kind = CharacterLiteral::UTF16;
5528 else if (T->isChar32Type())
5529 Kind = CharacterLiteral::UTF32;
5530 else
5531 Kind = CharacterLiteral::Ascii;
5532
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005533 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5534 Kind, T, Loc);
5535 } else if (T->isBooleanType()) {
5536 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5537 T, Loc);
5538 } else if (T->isNullPtrType()) {
5539 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5540 } else {
5541 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005542 }
5543
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005544 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005545 // FIXME: This is a hack. We need a better way to handle substituted
5546 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005547 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5548 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005549 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005550 Loc, Loc);
5551 }
5552
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005553 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005554}
5555
Douglas Gregor641040a2011-01-12 23:45:44 +00005556/// \brief Match two template parameters within template parameter lists.
5557static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5558 bool Complain,
5559 Sema::TemplateParameterListEqualKind Kind,
5560 SourceLocation TemplateArgLoc) {
5561 // Check the actual kind (type, non-type, template).
5562 if (Old->getKind() != New->getKind()) {
5563 if (Complain) {
5564 unsigned NextDiag = diag::err_template_param_different_kind;
5565 if (TemplateArgLoc.isValid()) {
5566 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5567 NextDiag = diag::note_template_param_different_kind;
5568 }
5569 S.Diag(New->getLocation(), NextDiag)
5570 << (Kind != Sema::TPL_TemplateMatch);
5571 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5572 << (Kind != Sema::TPL_TemplateMatch);
5573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005574
Douglas Gregor641040a2011-01-12 23:45:44 +00005575 return false;
5576 }
5577
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005578 // Check that both are parameter packs are neither are parameter packs.
5579 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005580 // template template parameter, the template template parameter can have
5581 // a parameter pack where the template template argument does not.
5582 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5583 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5584 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005585 if (Complain) {
5586 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5587 if (TemplateArgLoc.isValid()) {
5588 S.Diag(TemplateArgLoc,
5589 diag::err_template_arg_template_params_mismatch);
5590 NextDiag = diag::note_template_parameter_pack_non_pack;
5591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005592
Douglas Gregor641040a2011-01-12 23:45:44 +00005593 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5594 : isa<NonTypeTemplateParmDecl>(New)? 1
5595 : 2;
5596 S.Diag(New->getLocation(), NextDiag)
5597 << ParamKind << New->isParameterPack();
5598 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5599 << ParamKind << Old->isParameterPack();
5600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005601
Douglas Gregor641040a2011-01-12 23:45:44 +00005602 return false;
5603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005604
Douglas Gregor641040a2011-01-12 23:45:44 +00005605 // For non-type template parameters, check the type of the parameter.
5606 if (NonTypeTemplateParmDecl *OldNTTP
5607 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5608 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005609
Douglas Gregor641040a2011-01-12 23:45:44 +00005610 // If we are matching a template template argument to a template
5611 // template parameter and one of the non-type template parameter types
5612 // is dependent, then we must wait until template instantiation time
5613 // to actually compare the arguments.
5614 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5615 (OldNTTP->getType()->isDependentType() ||
5616 NewNTTP->getType()->isDependentType()))
5617 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005618
Douglas Gregor641040a2011-01-12 23:45:44 +00005619 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5620 if (Complain) {
5621 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5622 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005623 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005624 diag::err_template_arg_template_params_mismatch);
5625 NextDiag = diag::note_template_nontype_parm_different_type;
5626 }
5627 S.Diag(NewNTTP->getLocation(), NextDiag)
5628 << NewNTTP->getType()
5629 << (Kind != Sema::TPL_TemplateMatch);
5630 S.Diag(OldNTTP->getLocation(),
5631 diag::note_template_nontype_parm_prev_declaration)
5632 << OldNTTP->getType();
5633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005634
Douglas Gregor641040a2011-01-12 23:45:44 +00005635 return false;
5636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005637
Douglas Gregor641040a2011-01-12 23:45:44 +00005638 return true;
5639 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005640
Douglas Gregor641040a2011-01-12 23:45:44 +00005641 // For template template parameters, check the template parameter types.
5642 // The template parameter lists of template template
5643 // parameters must agree.
5644 if (TemplateTemplateParmDecl *OldTTP
5645 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005646 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005647 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5648 OldTTP->getTemplateParameters(),
5649 Complain,
5650 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005651 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005652 : Kind),
5653 TemplateArgLoc);
5654 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005655
Douglas Gregor641040a2011-01-12 23:45:44 +00005656 return true;
5657}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005658
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005659/// \brief Diagnose a known arity mismatch when comparing template argument
5660/// lists.
5661static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005662void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005663 TemplateParameterList *New,
5664 TemplateParameterList *Old,
5665 Sema::TemplateParameterListEqualKind Kind,
5666 SourceLocation TemplateArgLoc) {
5667 unsigned NextDiag = diag::err_template_param_list_different_arity;
5668 if (TemplateArgLoc.isValid()) {
5669 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5670 NextDiag = diag::note_template_param_list_different_arity;
5671 }
5672 S.Diag(New->getTemplateLoc(), NextDiag)
5673 << (New->size() > Old->size())
5674 << (Kind != Sema::TPL_TemplateMatch)
5675 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5676 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5677 << (Kind != Sema::TPL_TemplateMatch)
5678 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5679}
5680
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005681/// \brief Determine whether the given template parameter lists are
5682/// equivalent.
5683///
Mike Stump11289f42009-09-09 15:08:12 +00005684/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005685/// source code as part of a new template declaration.
5686///
5687/// \param Old The old template parameter list, typically found via
5688/// name lookup of the template declared with this template parameter
5689/// list.
5690///
5691/// \param Complain If true, this routine will produce a diagnostic if
5692/// the template parameter lists are not equivalent.
5693///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005694/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005695///
5696/// \param TemplateArgLoc If this source location is valid, then we
5697/// are actually checking the template parameter list of a template
5698/// argument (New) against the template parameter list of its
5699/// corresponding template template parameter (Old). We produce
5700/// slightly different diagnostics in this scenario.
5701///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005702/// \returns True if the template parameter lists are equal, false
5703/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005704bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005705Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5706 TemplateParameterList *Old,
5707 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005708 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005709 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005710 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5711 if (Complain)
5712 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5713 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005714
5715 return false;
5716 }
5717
Douglas Gregor641040a2011-01-12 23:45:44 +00005718 // C++0x [temp.arg.template]p3:
5719 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005720 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005721 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005722 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005723 // template-parameter-list of P. [...]
5724 TemplateParameterList::iterator NewParm = New->begin();
5725 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005726 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005727 OldParmEnd = Old->end();
5728 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005729 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5730 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005731 if (NewParm == NewParmEnd) {
5732 if (Complain)
5733 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5734 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005735
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005736 return false;
5737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005738
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005739 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5740 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741 return false;
5742
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005743 ++NewParm;
5744 continue;
5745 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005746
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005747 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005748 // [...] When P's template- parameter-list contains a template parameter
5749 // pack (14.5.3), the template parameter pack will match zero or more
5750 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005751 // template-parameter-list of A with the same type and form as the
5752 // template parameter pack in P (ignoring whether those template
5753 // parameters are template parameter packs).
5754 for (; NewParm != NewParmEnd; ++NewParm) {
5755 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5756 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005757 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005758 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005760
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005761 // Make sure we exhausted all of the arguments.
5762 if (NewParm != NewParmEnd) {
5763 if (Complain)
5764 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5765 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005766
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005767 return false;
5768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005769
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005770 return true;
5771}
5772
5773/// \brief Check whether a template can be declared within this scope.
5774///
5775/// If the template declaration is valid in this scope, returns
5776/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005777bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005778Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005779 if (!S)
5780 return false;
5781
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005782 // Find the nearest enclosing declaration scope.
5783 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5784 (S->getFlags() & Scope::TemplateParamScope) != 0)
5785 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005786
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005787 // C++ [temp]p4:
5788 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005789 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005790 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005791 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005792 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005793
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005794 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005795 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005796
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005797 // C++ [temp]p2:
5798 // A template-declaration can appear only as a namespace scope or
5799 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005800 if (Ctx) {
5801 if (Ctx->isFileContext())
5802 return false;
5803 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5804 // C++ [temp.mem]p2:
5805 // A local class shall not have member templates.
5806 if (RD->isLocalClass())
5807 return Diag(TemplateParams->getTemplateLoc(),
5808 diag::err_template_inside_local_class)
5809 << TemplateParams->getSourceRange();
5810 else
5811 return false;
5812 }
5813 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005814
Mike Stump11289f42009-09-09 15:08:12 +00005815 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005816 diag::err_template_outside_namespace_or_class_scope)
5817 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005818}
Douglas Gregor67a65642009-02-17 23:15:12 +00005819
Douglas Gregor54888652009-10-07 00:13:32 +00005820/// \brief Determine what kind of template specialization the given declaration
5821/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005822static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005823 if (!D)
5824 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005825
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005826 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5827 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005828 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5829 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005830 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5831 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005832
Douglas Gregor54888652009-10-07 00:13:32 +00005833 return TSK_Undeclared;
5834}
5835
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005836/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005837/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005838///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005839/// This routine determines whether a template specialization can be declared
5840/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005841///
5842/// \param S the semantic analysis object for which this check is being
5843/// performed.
5844///
5845/// \param Specialized the entity being specialized or instantiated, which
5846/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005847/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005848/// member class).
5849///
5850/// \param PrevDecl the previous declaration of this entity, if any.
5851///
5852/// \param Loc the location of the explicit specialization or instantiation of
5853/// this entity.
5854///
5855/// \param IsPartialSpecialization whether this is a partial specialization of
5856/// a class template.
5857///
Douglas Gregor54888652009-10-07 00:13:32 +00005858/// \returns true if there was an error that we cannot recover from, false
5859/// otherwise.
5860static bool CheckTemplateSpecializationScope(Sema &S,
5861 NamedDecl *Specialized,
5862 NamedDecl *PrevDecl,
5863 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005864 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005865 // Keep these "kind" numbers in sync with the %select statements in the
5866 // various diagnostics emitted by this routine.
5867 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005868 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005869 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005870 else if (isa<VarTemplateDecl>(Specialized))
5871 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005872 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005873 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005874 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005875 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005876 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005877 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005878 else if (isa<RecordDecl>(Specialized))
5879 EntityKind = 7;
5880 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5881 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005882 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005883 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005884 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005885 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005886 return true;
5887 }
5888
Douglas Gregorf47b9112009-02-25 22:02:03 +00005889 // C++ [temp.expl.spec]p2:
5890 // An explicit specialization shall be declared in the namespace
5891 // of which the template is a member, or, for member templates, in
5892 // the namespace of which the enclosing class or enclosing class
5893 // template is a member. An explicit specialization of a member
5894 // function, member class or static data member of a class
5895 // template shall be declared in the namespace of which the class
5896 // template is a member. Such a declaration may also be a
5897 // definition. If the declaration is not a definition, the
5898 // specialization may be defined later in the name- space in which
5899 // the explicit specialization was declared, or in a namespace
5900 // that encloses the one in which the explicit specialization was
5901 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005902 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005903 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005904 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005905 return true;
5906 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005907
Douglas Gregor40fb7442009-10-07 17:30:37 +00005908 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005909 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005910 // Do not warn for class scope explicit specialization during
5911 // instantiation, warning was already emitted during pattern
5912 // semantic analysis.
5913 if (!S.ActiveTemplateInstantiations.size())
5914 S.Diag(Loc, diag::ext_function_specialization_in_class)
5915 << Specialized;
5916 } else {
5917 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5918 << Specialized;
5919 return true;
5920 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005921 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005922
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005923 if (S.CurContext->isRecord() &&
5924 !S.CurContext->Equals(Specialized->getDeclContext())) {
5925 // Make sure that we're specializing in the right record context.
5926 // Otherwise, things can go horribly wrong.
5927 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5928 << Specialized;
5929 return true;
5930 }
5931
Douglas Gregore4b05162009-10-07 17:21:34 +00005932 // C++ [temp.class.spec]p6:
5933 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005934 // in any namespace scope in which its definition may be defined (14.5.1
5935 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005936 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005937 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005938 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005939
5940 // Make sure that this redeclaration (or definition) occurs in an enclosing
5941 // namespace.
5942 // Note that HandleDeclarator() performs this check for explicit
5943 // specializations of function templates, static data members, and member
5944 // functions, so we skip the check here for those kinds of entities.
5945 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5946 // Should we refactor that check, so that it occurs later?
5947 if (!DC->Encloses(SpecializedContext) &&
5948 !(isa<FunctionTemplateDecl>(Specialized) ||
5949 isa<FunctionDecl>(Specialized) ||
5950 isa<VarTemplateDecl>(Specialized) ||
5951 isa<VarDecl>(Specialized))) {
5952 if (isa<TranslationUnitDecl>(SpecializedContext))
5953 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5954 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00005955 else if (isa<NamespaceDecl>(SpecializedContext)) {
5956 int Diag = diag::err_template_spec_redecl_out_of_scope;
5957 if (S.getLangOpts().MicrosoftExt)
5958 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5959 S.Diag(Loc, Diag) << EntityKind << Specialized
5960 << cast<NamedDecl>(SpecializedContext);
5961 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00005962 llvm_unreachable("unexpected namespace context for specialization");
5963
5964 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5965 } else if ((!PrevDecl ||
5966 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5967 getTemplateSpecializationKind(PrevDecl) ==
5968 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005969 // C++ [temp.exp.spec]p2:
5970 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005971 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005972 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005973 // An explicit specialization of a member function, member class or
5974 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005975 // namespace of which the class template is a member.
5976 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005977 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005978 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005979 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005980 // C++11 [temp.explicit]p3:
5981 // An explicit instantiation shall appear in an enclosing namespace of its
5982 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005983 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005984 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005985 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005986 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005987 "DC encloses TU but isn't in enclosing namespace set");
5988 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005989 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005990 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5991 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005992 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005993 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005994 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005995 Diag = diag::ext_template_spec_decl_out_of_scope;
5996 else
5997 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5998 S.Diag(Loc, Diag)
5999 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6000 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006001
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006002 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006003 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006004 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006005
Douglas Gregorf47b9112009-02-25 22:02:03 +00006006 return false;
6007}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006008
Richard Smith6056d5e2014-02-09 00:54:43 +00006009static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
6010 if (!E->isInstantiationDependent())
6011 return SourceLocation();
6012 DependencyChecker Checker(Depth);
6013 Checker.TraverseStmt(E);
6014 if (Checker.Match && Checker.MatchLoc.isInvalid())
6015 return E->getSourceRange();
6016 return Checker.MatchLoc;
6017}
6018
6019static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6020 if (!TL.getType()->isDependentType())
6021 return SourceLocation();
6022 DependencyChecker Checker(Depth);
6023 Checker.TraverseTypeLoc(TL);
6024 if (Checker.Match && Checker.MatchLoc.isInvalid())
6025 return TL.getSourceRange();
6026 return Checker.MatchLoc;
6027}
6028
Larisse Voufo39a1e502013-08-06 01:03:05 +00006029/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006030/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006031static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006032 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6033 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006034 for (unsigned I = 0; I != NumArgs; ++I) {
6035 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006036 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006037 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6038 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006039 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006040
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006041 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006043
Eli Friedmanb826a002012-09-26 02:36:12 +00006044 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006045 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006046
6047 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006048
Douglas Gregor98318c22011-01-03 21:37:45 +00006049 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006050 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6051 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006052
6053 // Strip off any implicit casts we added as part of type checking.
6054 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6055 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006056
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006057 // C++ [temp.class.spec]p8:
6058 // A non-type argument is non-specialized if it is the name of a
6059 // non-type parameter. All other non-type arguments are
6060 // specialized.
6061 //
6062 // Below, we check the two conditions that only apply to
6063 // specialized non-type arguments, so skip any non-specialized
6064 // arguments.
6065 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006066 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006067 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006068
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006069 // C++ [temp.class.spec]p9:
6070 // Within the argument list of a class template partial
6071 // specialization, the following restrictions apply:
6072 // -- A partially specialized non-type argument expression
6073 // shall not involve a template parameter of the partial
6074 // specialization except when the argument expression is a
6075 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006076 SourceRange ParamUseRange =
6077 findTemplateParameter(Param->getDepth(), ArgExpr);
6078 if (ParamUseRange.isValid()) {
6079 if (IsDefaultArgument) {
6080 S.Diag(TemplateNameLoc,
6081 diag::err_dependent_non_type_arg_in_partial_spec);
6082 S.Diag(ParamUseRange.getBegin(),
6083 diag::note_dependent_non_type_default_arg_in_partial_spec)
6084 << ParamUseRange;
6085 } else {
6086 S.Diag(ParamUseRange.getBegin(),
6087 diag::err_dependent_non_type_arg_in_partial_spec)
6088 << ParamUseRange;
6089 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006090 return true;
6091 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006092
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006093 // -- The type of a template parameter corresponding to a
6094 // specialized non-type argument shall not be dependent on a
6095 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006096 //
6097 // FIXME: We need to delay this check until instantiation in some cases:
6098 //
6099 // template<template<typename> class X> struct A {
6100 // template<typename T, X<T> N> struct B;
6101 // template<typename T> struct B<T, 0>;
6102 // };
6103 // template<typename> using X = int;
6104 // A<X>::B<int, 0> b;
6105 ParamUseRange = findTemplateParameter(
6106 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6107 if (ParamUseRange.isValid()) {
6108 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6109 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6110 << Param->getType() << ParamUseRange;
6111 S.Diag(Param->getLocation(), diag::note_template_param_here)
6112 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006113 return true;
6114 }
6115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006116
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006117 return false;
6118}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006119
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006120/// \brief Check the non-type template arguments of a class template
6121/// partial specialization according to C++ [temp.class.spec]p9.
6122///
Richard Smith6056d5e2014-02-09 00:54:43 +00006123/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006124/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006125/// template.
6126/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006127/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006128/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006129///
Richard Smith6056d5e2014-02-09 00:54:43 +00006130/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006131static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006132 Sema &S, SourceLocation TemplateNameLoc,
6133 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006134 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006135 const TemplateArgument *ArgList = TemplateArgs.data();
6136
6137 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6138 NonTypeTemplateParmDecl *Param
6139 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6140 if (!Param)
6141 continue;
6142
Richard Smith6056d5e2014-02-09 00:54:43 +00006143 if (CheckNonTypeTemplatePartialSpecializationArgs(
6144 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006145 return true;
6146 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006147
6148 return false;
6149}
6150
John McCall48871652010-08-21 09:40:31 +00006151DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006152Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6153 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006154 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006155 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006156 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006157 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006158 MultiTemplateParamsArg
6159 TemplateParameterLists,
6160 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006161 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006162
Richard Smith4b55a9c2014-04-17 03:29:33 +00006163 CXXScopeSpec &SS = TemplateId.SS;
6164
Abramo Bagnara60804e12011-03-18 15:16:37 +00006165 // NOTE: KWLoc is the location of the tag keyword. This will instead
6166 // store the location of the outermost template keyword in the declaration.
6167 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006168 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6169 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6170 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6171 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006172
Douglas Gregor67a65642009-02-17 23:15:12 +00006173 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006174 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006175 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006176 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6177
6178 if (!ClassTemplate) {
6179 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006180 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006181 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6182 return true;
6183 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006184
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006185 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006186 bool isPartialSpecialization = false;
6187
Douglas Gregorf47b9112009-02-25 22:02:03 +00006188 // Check the validity of the template headers that introduce this
6189 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006190 // FIXME: We probably shouldn't complain about these headers for
6191 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006192 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006193 TemplateParameterList *TemplateParams =
6194 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006195 KWLoc, TemplateNameLoc, SS, &TemplateId,
6196 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6197 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006198 if (Invalid)
6199 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006200
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006201 if (TemplateParams && TemplateParams->size() > 0) {
6202 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006203
Douglas Gregorec9518b2010-12-21 08:14:57 +00006204 if (TUK == TUK_Friend) {
6205 Diag(KWLoc, diag::err_partial_specialization_friend)
6206 << SourceRange(LAngleLoc, RAngleLoc);
6207 return true;
6208 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006209
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006210 // C++ [temp.class.spec]p10:
6211 // The template parameter list of a specialization shall not
6212 // contain default template argument values.
6213 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6214 Decl *Param = TemplateParams->getParam(I);
6215 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6216 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006217 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006218 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006219 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006220 }
6221 } else if (NonTypeTemplateParmDecl *NTTP
6222 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6223 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006224 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006225 diag::err_default_arg_in_partial_spec)
6226 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006227 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006228 }
6229 } else {
6230 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006231 if (TTP->hasDefaultArgument()) {
6232 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006233 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006234 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006235 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006236 }
6237 }
6238 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006239 } else if (TemplateParams) {
6240 if (TUK == TUK_Friend)
6241 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006242 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006243 SourceRange(TemplateParams->getTemplateLoc(),
6244 TemplateParams->getRAngleLoc()))
6245 << SourceRange(LAngleLoc, RAngleLoc);
6246 else
6247 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006248 } else {
6249 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006250 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006251
Douglas Gregor67a65642009-02-17 23:15:12 +00006252 // Check that the specialization uses the same tag kind as the
6253 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006254 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6255 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006256 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006257 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006258 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006259 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006260 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006261 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006262 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006263 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006264 diag::note_previous_use);
6265 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6266 }
6267
Douglas Gregorc40290e2009-03-09 23:48:35 +00006268 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006269 TemplateArgumentListInfo TemplateArgs =
6270 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006271
Douglas Gregor14406932011-01-03 20:35:03 +00006272 // Check for unexpanded parameter packs in any of the template arguments.
6273 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006274 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006275 UPPC_PartialSpecialization))
6276 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006277
Douglas Gregor67a65642009-02-17 23:15:12 +00006278 // Check that the template argument list is well-formed for this
6279 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006280 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006281 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6282 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006283 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006284
Douglas Gregor2373c592009-05-31 09:31:02 +00006285 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006286 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006287 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006288 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006289 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6290 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006291 return true;
6292
Douglas Gregor678d76c2011-07-01 01:22:09 +00006293 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006294 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006295 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006296 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006297 TemplateArgs.size(),
6298 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006299 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6300 << ClassTemplate->getDeclName();
6301 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006302 }
6303 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006304
Craig Topperc3ec1492014-05-26 06:22:03 +00006305 void *InsertPos = nullptr;
6306 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006307
6308 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006309 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006310 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006311 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006312 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006313
Craig Topperc3ec1492014-05-26 06:22:03 +00006314 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006315
Douglas Gregorf47b9112009-02-25 22:02:03 +00006316 // Check whether we can declare a class template specialization in
6317 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006318 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006319 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6320 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006321 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006322 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006323
Douglas Gregor15301382009-07-30 17:40:51 +00006324 // The canonical type
6325 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006326 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006327 // Build the canonical type that describes the converted template
6328 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006329 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6330 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006331 Converted.data(),
6332 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006333
6334 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006335 ClassTemplate->getInjectedClassNameSpecialization())) {
6336 // C++ [temp.class.spec]p9b3:
6337 //
6338 // -- The argument list of the specialization shall not be identical
6339 // to the implicit argument list of the primary template.
6340 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006341 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006342 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006343 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6344 ClassTemplate->getIdentifier(),
6345 TemplateNameLoc,
6346 Attr,
6347 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006348 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006349 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006350 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006351 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006352 }
Douglas Gregor15301382009-07-30 17:40:51 +00006353
Douglas Gregor2373c592009-05-31 09:31:02 +00006354 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006355 ClassTemplatePartialSpecializationDecl *PrevPartial
6356 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006357 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006358 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006359 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006360 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006361 TemplateParams,
6362 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006363 Converted.data(),
6364 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006365 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006366 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006367 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006368 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006369 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006370 Partial->setTemplateParameterListsInfo(
6371 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006372 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006373
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006374 if (!PrevPartial)
6375 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006376 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006377
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006378 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006379 // template specialization, make a note of that.
6380 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6381 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006382
Douglas Gregor91772d12009-06-13 00:26:55 +00006383 // Check that all of the template parameters of the class template
6384 // partial specialization are deducible from the template
6385 // arguments. If not, this class template partial specialization
6386 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006387 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006388 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006389 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006390 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006391
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006392 if (!DeducibleParams.all()) {
6393 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006394 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006395 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006396 << SourceRange(TemplateNameLoc, RAngleLoc);
6397 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6398 if (!DeducibleParams[I]) {
6399 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6400 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006401 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006402 diag::note_partial_spec_unused_parameter)
6403 << Param->getDeclName();
6404 else
Mike Stump11289f42009-09-09 15:08:12 +00006405 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006406 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006407 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006408 }
6409 }
6410 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006411 } else {
6412 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006413 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006414 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006415 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006416 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006417 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006418 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006419 Converted.data(),
6420 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006421 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006422 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006423 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006424 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006425 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006426 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006427
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006428 if (!PrevDecl)
6429 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006430
David Majnemer678f50b2015-11-18 19:49:19 +00006431 if (CurContext->isDependentContext()) {
6432 // -fms-extensions permits specialization of nested classes without
6433 // fully specializing the outer class(es).
6434 assert(getLangOpts().MicrosoftExt &&
6435 "Only possible with -fms-extensions!");
6436 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6437 CanonType = Context.getTemplateSpecializationType(
6438 CanonTemplate, Converted.data(), Converted.size());
6439 } else {
6440 CanonType = Context.getTypeDeclType(Specialization);
6441 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006442 }
6443
Douglas Gregor06db9f52009-10-12 20:18:28 +00006444 // C++ [temp.expl.spec]p6:
6445 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006446 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006447 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006448 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006449 // use occurs; no diagnostic is required.
6450 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006451 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006452 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006453 // Is there any previous explicit specialization declaration?
6454 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6455 Okay = true;
6456 break;
6457 }
6458 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006459
Douglas Gregorc854c662010-02-26 06:03:23 +00006460 if (!Okay) {
6461 SourceRange Range(TemplateNameLoc, RAngleLoc);
6462 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6463 << Context.getTypeDeclType(Specialization) << Range;
6464
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006465 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006466 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006467 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006468 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006469 return true;
6470 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006472
Douglas Gregor2208a292009-09-26 20:57:03 +00006473 // If this is not a friend, note that this is an explicit specialization.
6474 if (TUK != TUK_Friend)
6475 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006476
6477 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006478 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006479 RecordDecl *Def = Specialization->getDefinition();
6480 NamedDecl *Hidden = nullptr;
6481 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6482 SkipBody->ShouldSkip = true;
6483 makeMergedDefinitionVisible(Hidden, KWLoc);
6484 // From here on out, treat this as just a redeclaration.
6485 TUK = TUK_Declaration;
6486 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006487 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006488 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006489 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006490 Diag(Def->getLocation(), diag::note_previous_definition);
6491 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006492 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006493 }
6494 }
6495
John McCall659a3372010-12-18 03:30:47 +00006496 if (Attr)
6497 ProcessDeclAttributeList(S, Specialization, Attr);
6498
Richard Smith034b94a2012-08-17 03:20:55 +00006499 // Add alignment attributes if necessary; these attributes are checked when
6500 // the ASTContext lays out the structure.
6501 if (TUK == TUK_Definition) {
6502 AddAlignmentAttributesForRecord(Specialization);
6503 AddMsStructLayoutForRecord(Specialization);
6504 }
6505
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006506 if (ModulePrivateLoc.isValid())
6507 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6508 << (isPartialSpecialization? 1 : 0)
6509 << FixItHint::CreateRemoval(ModulePrivateLoc);
6510
Douglas Gregord56a91e2009-02-26 22:19:44 +00006511 // Build the fully-sugared type for this class template
6512 // specialization as the user wrote in the specialization
6513 // itself. This means that we'll pretty-print the type retrieved
6514 // from the specialization's declaration the way that the user
6515 // actually wrote the specialization, rather than formatting the
6516 // name based on the "canonical" representation used to store the
6517 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006518 TypeSourceInfo *WrittenTy
6519 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6520 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006521 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006522 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006523 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006524 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006525
Douglas Gregor1e249f82009-02-25 22:18:32 +00006526 // C++ [temp.expl.spec]p9:
6527 // A template explicit specialization is in the scope of the
6528 // namespace in which the template was defined.
6529 //
6530 // We actually implement this paragraph where we set the semantic
6531 // context (in the creation of the ClassTemplateSpecializationDecl),
6532 // but we also maintain the lexical context where the actual
6533 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006534 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006535
Douglas Gregor67a65642009-02-17 23:15:12 +00006536 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006537 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006538 Specialization->startDefinition();
6539
Douglas Gregor2208a292009-09-26 20:57:03 +00006540 if (TUK == TUK_Friend) {
6541 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6542 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006543 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006544 /*FIXME:*/KWLoc);
6545 Friend->setAccess(AS_public);
6546 CurContext->addDecl(Friend);
6547 } else {
6548 // Add the specialization into its lexical context, so that it can
6549 // be seen when iterating through the list of declarations in that
6550 // context. However, specializations are not found by name lookup.
6551 CurContext->addDecl(Specialization);
6552 }
John McCall48871652010-08-21 09:40:31 +00006553 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006554}
Douglas Gregor333489b2009-03-27 23:10:48 +00006555
John McCall48871652010-08-21 09:40:31 +00006556Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006557 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006558 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006559 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006560 ActOnDocumentableDecl(NewDecl);
6561 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006562}
6563
John McCall4f7ced62010-02-11 01:33:53 +00006564/// \brief Strips various properties off an implicit instantiation
6565/// that has just been explicitly specialized.
6566static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006567 D->dropAttr<DLLImportAttr>();
6568 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006569
Nico Webere4974382014-12-19 23:52:45 +00006570 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006571 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006572}
6573
Nico Webera8f80b32012-01-09 19:52:25 +00006574/// \brief Compute the diagnostic location for an explicit instantiation
6575// declaration or definition.
6576static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006577 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006578 // Explicit instantiations following a specialization have no effect and
6579 // hence no PointOfInstantiation. In that case, walk decl backwards
6580 // until a valid name loc is found.
6581 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006582 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6583 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006584 PrevDiagLoc = Prev->getLocation();
6585 }
6586 assert(PrevDiagLoc.isValid() &&
6587 "Explicit instantiation without point of instantiation?");
6588 return PrevDiagLoc;
6589}
6590
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006591/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006592/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006593/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006594/// new specialization/instantiation will have any effect.
6595///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006596/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006597/// instantiation.
6598///
6599/// \param NewTSK the kind of the new explicit specialization or instantiation.
6600///
6601/// \param PrevDecl the previous declaration of the entity.
6602///
6603/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6604///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006605/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006606/// declaration was instantiated (either implicitly or explicitly).
6607///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006608/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006609/// specialization or instantiation has no effect and should be ignored.
6610///
6611/// \returns true if there was an error that should prevent the introduction of
6612/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006613bool
6614Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6615 TemplateSpecializationKind NewTSK,
6616 NamedDecl *PrevDecl,
6617 TemplateSpecializationKind PrevTSK,
6618 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006619 bool &HasNoEffect) {
6620 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006621
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006622 switch (NewTSK) {
6623 case TSK_Undeclared:
6624 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006625 assert(
6626 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6627 "previous declaration must be implicit!");
6628 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006629
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006630 case TSK_ExplicitSpecialization:
6631 switch (PrevTSK) {
6632 case TSK_Undeclared:
6633 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006634 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006635 // explicitly specialized or has merely been mentioned without any
6636 // instantiation.
6637 return false;
6638
6639 case TSK_ImplicitInstantiation:
6640 if (PrevPointOfInstantiation.isInvalid()) {
6641 // The declaration itself has not actually been instantiated, so it is
6642 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006643 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006644 return false;
6645 }
6646 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006647
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006648 case TSK_ExplicitInstantiationDeclaration:
6649 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006650 assert((PrevTSK == TSK_ImplicitInstantiation ||
6651 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006652 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006653
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006654 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006655 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006656 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006657 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006658 // implicit instantiation to take place, in every translation unit in
6659 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006660 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006661 // Is there any previous explicit specialization declaration?
6662 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6663 return false;
6664 }
6665
Douglas Gregor1d957a32009-10-27 18:42:08 +00006666 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006667 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006668 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006669 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006670
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006671 return true;
6672 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006673
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006674 case TSK_ExplicitInstantiationDeclaration:
6675 switch (PrevTSK) {
6676 case TSK_ExplicitInstantiationDeclaration:
6677 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006678 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006679 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006680
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006681 case TSK_Undeclared:
6682 case TSK_ImplicitInstantiation:
6683 // We're explicitly instantiating something that may have already been
6684 // implicitly instantiated; that's fine.
6685 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006686
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006687 case TSK_ExplicitSpecialization:
6688 // C++0x [temp.explicit]p4:
6689 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006690 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006691 // specialization for that template, the explicit instantiation has no
6692 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006693 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006694 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006695
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006696 case TSK_ExplicitInstantiationDefinition:
6697 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006698 // If an entity is the subject of both an explicit instantiation
6699 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006700 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006701 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006702 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006703
6704 // Explicit instantiations following a specialization have no effect and
6705 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6706 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006707 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6708 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006709 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006710 return false;
6711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006712
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006713 case TSK_ExplicitInstantiationDefinition:
6714 switch (PrevTSK) {
6715 case TSK_Undeclared:
6716 case TSK_ImplicitInstantiation:
6717 // We're explicitly instantiating something that may have already been
6718 // implicitly instantiated; that's fine.
6719 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006720
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006721 case TSK_ExplicitSpecialization:
6722 // C++ DR 259, C++0x [temp.explicit]p4:
6723 // For a given set of template parameters, if an explicit
6724 // instantiation of a template appears after a declaration of
6725 // an explicit specialization for that template, the explicit
6726 // instantiation has no effect.
6727 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006728 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006729 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006730 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006731 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006732 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6733 diag::ext_explicit_instantiation_after_specialization)
6734 << PrevDecl;
6735 Diag(PrevDecl->getLocation(),
6736 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006737 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006738 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006739
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006740 case TSK_ExplicitInstantiationDeclaration:
6741 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006742 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006743
6744 // C++0x [temp.explicit]p4:
6745 // For a given set of template parameters, if an explicit instantiation
6746 // of a template appears after a declaration of an explicit
6747 // specialization for that template, the explicit instantiation has no
6748 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006749 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006750 // Is there any previous explicit specialization declaration?
6751 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6752 HasNoEffect = true;
6753 break;
6754 }
6755 }
6756
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006757 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006758
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006759 case TSK_ExplicitInstantiationDefinition:
6760 // C++0x [temp.spec]p5:
6761 // For a given template and a given set of template-arguments,
6762 // - an explicit instantiation definition shall appear at most once
6763 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006764
6765 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6766 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006767 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006768 : diag::err_explicit_instantiation_duplicate)
6769 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006770 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006771 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006772 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006773 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006774 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006775 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006776
David Blaikie83d382b2011-09-23 05:06:16 +00006777 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006778}
6779
John McCallb9c78482010-04-08 09:05:18 +00006780/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006781/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006782///
James Dennettf14a6e52012-06-15 22:23:43 +00006783/// The only possible way to get a dependent function template specialization
6784/// is with a friend declaration, like so:
6785///
6786/// \code
6787/// template \<class T> void foo(T);
6788/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006789/// friend void foo<>(T);
6790/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006791/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006792///
6793/// There really isn't any useful analysis we can do here, so we
6794/// just store the information.
6795bool
6796Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6797 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6798 LookupResult &Previous) {
6799 // Remove anything from Previous that isn't a function template in
6800 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006801 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006802 LookupResult::Filter F = Previous.makeFilter();
6803 while (F.hasNext()) {
6804 NamedDecl *D = F.next()->getUnderlyingDecl();
6805 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006806 !FDLookupContext->InEnclosingNamespaceSetOf(
6807 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006808 F.erase();
6809 }
6810 F.done();
6811
6812 // Should this be diagnosed here?
6813 if (Previous.empty()) return true;
6814
6815 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6816 ExplicitTemplateArgs);
6817 return false;
6818}
6819
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006820/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006821/// specialization.
6822///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006823/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006824/// explicit function template specialization. On successful completion,
6825/// the function declaration \p FD will become a function template
6826/// specialization.
6827///
6828/// \param FD the function declaration, which will be updated to become a
6829/// function template specialization.
6830///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006831/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6832/// if any. Note that this may be valid info even when 0 arguments are
6833/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6834/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006835///
Francois Pichet3a44e432011-07-08 06:21:47 +00006836/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006837/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006838bool Sema::CheckFunctionTemplateSpecialization(
6839 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6840 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006841 // The set of function template specializations that could match this
6842 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006843 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006844 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6845 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006846
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006847 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6848 ConvertedTemplateArgs;
6849
Sebastian Redl50c68252010-08-31 00:36:30 +00006850 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006851 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6852 I != E; ++I) {
6853 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6854 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006855 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006856 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006857 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6858 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006859 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006860
Richard Smith574f4f62013-01-14 05:37:29 +00006861 // When matching a constexpr member function template specialization
6862 // against the primary template, we don't yet know whether the
6863 // specialization has an implicit 'const' (because we don't know whether
6864 // it will be a static member function until we know which template it
6865 // specializes), so adjust it now assuming it specializes this template.
6866 QualType FT = FD->getType();
6867 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006868 CXXMethodDecl *OldMD =
6869 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006870 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006871 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006872 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6873 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006874 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006875 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006876 }
6877 }
6878
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006879 TemplateArgumentListInfo Args;
6880 if (ExplicitTemplateArgs)
6881 Args = *ExplicitTemplateArgs;
6882
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006883 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006884 // A trailing template-argument can be left unspecified in the
6885 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006886 // provided it can be deduced from the function argument type.
6887 // Perform template argument deduction to determine whether we may be
6888 // specializing this template.
6889 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006890 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006891 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006892 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6893 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006894 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006895 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006896 // that we can provide nifty diagnostics.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006897 FailedCandidates.addCandidate()
6898 .set(FunTmpl->getTemplatedDecl(),
6899 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006900 (void)TDK;
6901 continue;
6902 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006903
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006904 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006905 if (ExplicitTemplateArgs)
6906 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00006907 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006908 }
6909 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006910
Douglas Gregor5de279c2009-09-26 03:41:46 +00006911 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006912 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006913 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006914 FD->getLocation(),
6915 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6916 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006917 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006918 PDiag(diag::note_function_template_spec_matched));
6919
John McCall58cc69d2010-01-27 01:50:18 +00006920 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006921 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006922
6923 // Ignore access information; it doesn't figure into redeclaration checking.
6924 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006925
Nathan Wilson83839122016-04-09 02:55:27 +00006926 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6927 // an explicit specialization (14.8.3) [...] of a concept definition.
6928 if (Specialization->getPrimaryTemplate()->isConcept()) {
6929 Diag(FD->getLocation(), diag::err_concept_specialized)
6930 << 0 /*function*/ << 1 /*explicitly specialized*/;
6931 Diag(Specialization->getLocation(), diag::note_previous_declaration);
6932 return true;
6933 }
6934
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006935 FunctionTemplateSpecializationInfo *SpecInfo
6936 = Specialization->getTemplateSpecializationInfo();
6937 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006938
6939 // Note: do not overwrite location info if previous template
6940 // specialization kind was explicit.
6941 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006942 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006943 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006944 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6945 // function can differ from the template declaration with respect to
6946 // the constexpr specifier.
6947 Specialization->setConstexpr(FD->isConstexpr());
6948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006949
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006950 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006951 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006952
6953 // If this is a friend declaration, then we're not really declaring
6954 // an explicit specialization.
6955 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006956
Douglas Gregor54888652009-10-07 00:13:32 +00006957 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006958 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006959 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006960 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006961 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006962 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006963 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006964
6965 // C++ [temp.expl.spec]p6:
6966 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006968 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006969 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006970 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006971 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006972 if (!isFriend &&
6973 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006974 TSK_ExplicitSpecialization,
6975 Specialization,
6976 SpecInfo->getTemplateSpecializationKind(),
6977 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006978 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006979 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006980
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006981 // Mark the prior declaration as an explicit specialization, so that later
6982 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006983 if (!isFriend) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00006984 // Explicit specializations do not inherit '=delete' from their primary
6985 // function template.
6986 if (Specialization->isDeleted()) {
6987 assert(!SpecInfo->isExplicitSpecialization());
6988 assert(Specialization->getCanonicalDecl() == Specialization);
6989 Specialization->setDeletedAsWritten(false);
6990 }
John McCall816d75b2010-03-24 07:46:06 +00006991 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006992 MarkUnusedFileScopedDecl(Specialization);
6993 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006994
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006995 // Turn the given function declaration into a function template
6996 // specialization, with the template arguments from the previous
6997 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006998 // Take copies of (semantic and syntactic) template argument lists.
6999 const TemplateArgumentList* TemplArgs = new (Context)
7000 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007001 FD->setFunctionTemplateSpecialization(
7002 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7003 SpecInfo->getTemplateSpecializationKind(),
7004 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007005
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007006 // The "previous declaration" for this function template specialization is
7007 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007008 Previous.clear();
7009 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007010 return false;
7011}
7012
Douglas Gregor86d142a2009-10-08 07:24:58 +00007013/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007014/// specialization.
7015///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007016/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007017/// explicit member function specialization. On successful completion,
7018/// the function declaration \p FD will become a member function
7019/// specialization.
7020///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007021/// \param Member the member declaration, which will be updated to become a
7022/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007023///
John McCall1f82f242009-11-18 22:49:29 +00007024/// \param Previous the set of declarations, one of which may be specialized
7025/// by this function specialization; the set will be modified to contain the
7026/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007027bool
John McCall1f82f242009-11-18 22:49:29 +00007028Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007029 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007030
Douglas Gregor86d142a2009-10-08 07:24:58 +00007031 // Try to find the member we are instantiating.
Craig Topperc3ec1492014-05-26 06:22:03 +00007032 NamedDecl *Instantiation = nullptr;
7033 NamedDecl *InstantiatedFrom = nullptr;
7034 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007035
John McCall1f82f242009-11-18 22:49:29 +00007036 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007037 // Nowhere to look anyway.
7038 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007039 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7040 I != E; ++I) {
7041 NamedDecl *D = (*I)->getUnderlyingDecl();
7042 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007043 QualType Adjusted = Function->getType();
7044 if (!hasExplicitCallingConv(Adjusted))
7045 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7046 if (Context.hasSameType(Adjusted, Method->getType())) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007047 Instantiation = Method;
7048 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007049 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007050 break;
7051 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007052 }
7053 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007054 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007055 VarDecl *PrevVar;
7056 if (Previous.isSingleResult() &&
7057 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007058 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00007059 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007060 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007061 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007062 }
7063 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007064 CXXRecordDecl *PrevRecord;
7065 if (Previous.isSingleResult() &&
7066 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
7067 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007068 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007069 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007070 }
Richard Smith7d137e32012-03-23 03:33:32 +00007071 } else if (isa<EnumDecl>(Member)) {
7072 EnumDecl *PrevEnum;
7073 if (Previous.isSingleResult() &&
7074 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
7075 Instantiation = PrevEnum;
7076 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7077 MSInfo = PrevEnum->getMemberSpecializationInfo();
7078 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007080
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007081 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007082 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007083 // specializations are always out-of-line, the caller will complain about
7084 // this mismatch later.
7085 return false;
7086 }
John McCalle820e5e2010-04-13 20:37:33 +00007087
7088 // If this is a friend, just bail out here before we start turning
7089 // things into explicit specializations.
7090 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7091 // Preserve instantiation information.
7092 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7093 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7094 cast<CXXMethodDecl>(InstantiatedFrom),
7095 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7096 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7097 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7098 cast<CXXRecordDecl>(InstantiatedFrom),
7099 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7100 }
7101
7102 Previous.clear();
7103 Previous.addDecl(Instantiation);
7104 return false;
7105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007106
Douglas Gregor86d142a2009-10-08 07:24:58 +00007107 // Make sure that this is a specialization of a member.
7108 if (!InstantiatedFrom) {
7109 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7110 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007111 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7112 return true;
7113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007114
Douglas Gregor06db9f52009-10-12 20:18:28 +00007115 // C++ [temp.expl.spec]p6:
7116 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007117 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007118 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007119 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007120 // use occurs; no diagnostic is required.
7121 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007122
Abramo Bagnara8075c852010-06-12 07:44:57 +00007123 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007124 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7125 TSK_ExplicitSpecialization,
7126 Instantiation,
7127 MSInfo->getTemplateSpecializationKind(),
7128 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007129 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007130 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007131
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007132 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007133 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007134 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007135 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007136 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007137 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007138
Douglas Gregor86d142a2009-10-08 07:24:58 +00007139 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007140 // the original declaration to note that it is an explicit specialization
7141 // (if it was previously an implicit instantiation). This latter step
7142 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007143 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007144 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7145 if (InstantiationFunction->getTemplateSpecializationKind() ==
7146 TSK_ImplicitInstantiation) {
7147 InstantiationFunction->setTemplateSpecializationKind(
7148 TSK_ExplicitSpecialization);
7149 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007150 // Explicit specializations of member functions of class templates do not
7151 // inherit '=delete' from the member function they are specializing.
7152 if (InstantiationFunction->isDeleted()) {
7153 assert(InstantiationFunction->getCanonicalDecl() ==
7154 InstantiationFunction);
7155 InstantiationFunction->setDeletedAsWritten(false);
7156 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007158
Douglas Gregor86d142a2009-10-08 07:24:58 +00007159 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7160 cast<CXXMethodDecl>(InstantiatedFrom),
7161 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007162 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007163 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007164 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7165 if (InstantiationVar->getTemplateSpecializationKind() ==
7166 TSK_ImplicitInstantiation) {
7167 InstantiationVar->setTemplateSpecializationKind(
7168 TSK_ExplicitSpecialization);
7169 InstantiationVar->setLocation(Member->getLocation());
7170 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007171
Larisse Voufo39a1e502013-08-06 01:03:05 +00007172 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7173 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007174 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007175 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007176 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7177 if (InstantiationClass->getTemplateSpecializationKind() ==
7178 TSK_ImplicitInstantiation) {
7179 InstantiationClass->setTemplateSpecializationKind(
7180 TSK_ExplicitSpecialization);
7181 InstantiationClass->setLocation(Member->getLocation());
7182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007183
Douglas Gregor86d142a2009-10-08 07:24:58 +00007184 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007185 cast<CXXRecordDecl>(InstantiatedFrom),
7186 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007187 } else {
7188 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7189 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7190 if (InstantiationEnum->getTemplateSpecializationKind() ==
7191 TSK_ImplicitInstantiation) {
7192 InstantiationEnum->setTemplateSpecializationKind(
7193 TSK_ExplicitSpecialization);
7194 InstantiationEnum->setLocation(Member->getLocation());
7195 }
7196
7197 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7198 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007200
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007201 // Save the caller the trouble of having to figure out which declaration
7202 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007203 Previous.clear();
7204 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007205 return false;
7206}
7207
Douglas Gregore47f5a72009-10-14 23:41:34 +00007208/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007209///
7210/// \returns true if a serious error occurs, false otherwise.
7211static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007212 SourceLocation InstLoc,
7213 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007214 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7215 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007216
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007217 if (CurContext->isRecord()) {
7218 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7219 << D;
7220 return true;
7221 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007222
Richard Smith050d2612011-10-18 02:28:33 +00007223 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007224 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007225 // template. If the name declared in the explicit instantiation is an
7226 // unqualified name, the explicit instantiation shall appear in the
7227 // namespace where its template is declared or, if that namespace is inline
7228 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007229 //
7230 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007231 if (WasQualifiedName) {
7232 if (CurContext->Encloses(OrigContext))
7233 return false;
7234 } else {
7235 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7236 return false;
7237 }
7238
7239 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7240 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007241 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007242 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007243 diag::err_explicit_instantiation_out_of_scope :
7244 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007245 << D << NS;
7246 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007247 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007248 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007249 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7250 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7251 << D << NS;
7252 } else
7253 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007254 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007255 diag::err_explicit_instantiation_must_be_global :
7256 diag::warn_explicit_instantiation_must_be_global_0x)
7257 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007258 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007259 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007260}
7261
7262/// \brief Determine whether the given scope specifier has a template-id in it.
7263static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7264 if (!SS.isSet())
7265 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007266
Richard Smith050d2612011-10-18 02:28:33 +00007267 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007268 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007269 // or a static data member of a class template specialization, the name of
7270 // the class template specialization in the qualified-id for the member
7271 // name shall be a simple-template-id.
7272 //
7273 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007274 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7275 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007276 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007277 if (isa<TemplateSpecializationType>(T))
7278 return true;
7279
7280 return false;
7281}
7282
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007283// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007284DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007285Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007286 SourceLocation ExternLoc,
7287 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007288 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007289 SourceLocation KWLoc,
7290 const CXXScopeSpec &SS,
7291 TemplateTy TemplateD,
7292 SourceLocation TemplateNameLoc,
7293 SourceLocation LAngleLoc,
7294 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007295 SourceLocation RAngleLoc,
7296 AttributeList *Attr) {
7297 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007298 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007299 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007300 // Check that the specialization uses the same tag kind as the
7301 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007302 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7303 assert(Kind != TTK_Enum &&
7304 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007305
Richard Trieu265c3442016-04-05 21:13:54 +00007306 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7307
7308 if (!ClassTemplate) {
7309 unsigned ErrorKind = 0;
7310 if (isa<TypeAliasTemplateDecl>(TD)) {
7311 ErrorKind = 4;
7312 } else if (isa<TemplateTemplateParmDecl>(TD)) {
7313 ErrorKind = 5;
7314 }
7315
7316 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << ErrorKind;
7317 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00007318 return true;
7319 }
7320
Douglas Gregord9034f02009-05-14 16:41:31 +00007321 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007322 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007323 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007324 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007325 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007326 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007327 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007328 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007329 diag::note_previous_use);
7330 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7331 }
7332
Douglas Gregore47f5a72009-10-14 23:41:34 +00007333 // C++0x [temp.explicit]p2:
7334 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007335 // definition and an explicit instantiation declaration. An explicit
7336 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007337 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7338 ? TSK_ExplicitInstantiationDefinition
7339 : TSK_ExplicitInstantiationDeclaration;
7340
7341 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7342 // Check for dllexport class template instantiation declarations.
7343 for (AttributeList *A = Attr; A; A = A->getNext()) {
7344 if (A->getKind() == AttributeList::AT_DLLExport) {
7345 Diag(ExternLoc,
7346 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7347 Diag(A->getLoc(), diag::note_attribute);
7348 break;
7349 }
7350 }
7351
7352 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7353 Diag(ExternLoc,
7354 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7355 Diag(A->getLocation(), diag::note_attribute);
7356 }
7357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007358
Douglas Gregora1f49972009-05-13 00:25:59 +00007359 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007360 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007361 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007362
7363 // Check that the template argument list is well-formed for this
7364 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007365 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007366 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7367 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007368 return true;
7369
Douglas Gregora1f49972009-05-13 00:25:59 +00007370 // Find the class template specialization declaration that
7371 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007372 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007373 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007374 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007375
Abramo Bagnara8075c852010-06-12 07:44:57 +00007376 TemplateSpecializationKind PrevDecl_TSK
7377 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7378
Douglas Gregor54888652009-10-07 00:13:32 +00007379 // C++0x [temp.explicit]p2:
7380 // [...] An explicit instantiation shall appear in an enclosing
7381 // namespace of its template. [...]
7382 //
7383 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007384 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7385 SS.isSet()))
7386 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007387
Craig Topperc3ec1492014-05-26 06:22:03 +00007388 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007389
Abramo Bagnara8075c852010-06-12 07:44:57 +00007390 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007391 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007392 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007393 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007394 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007395 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007396 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007397
Abramo Bagnara8075c852010-06-12 07:44:57 +00007398 // Even though HasNoEffect == true means that this explicit instantiation
7399 // has no effect on semantics, we go on to put its syntax in the AST.
7400
7401 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7402 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007403 // Since the only prior class template specialization with these
7404 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007405 // declaration node as our own, updating the source location
7406 // for the template name to reflect our new declaration.
7407 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007408 Specialization = PrevDecl;
7409 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007410 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007411 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007412 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007413
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007414 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007415 // Create a new class template specialization declaration node for
7416 // this explicit specialization.
7417 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007418 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007419 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007420 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007421 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007422 Converted.data(),
7423 Converted.size(),
7424 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007425 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007426
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007427 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007428 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007429 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007430 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007431 }
7432
7433 // Build the fully-sugared type for this explicit instantiation as
7434 // the user wrote in the explicit instantiation itself. This means
7435 // that we'll pretty-print the type retrieved from the
7436 // specialization's declaration the way that the user actually wrote
7437 // the explicit instantiation, rather than formatting the name based
7438 // on the "canonical" representation used to store the template
7439 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007440 TypeSourceInfo *WrittenTy
7441 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7442 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007443 Context.getTypeDeclType(Specialization));
7444 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007445
Abramo Bagnara8075c852010-06-12 07:44:57 +00007446 // Set source locations for keywords.
7447 Specialization->setExternLoc(ExternLoc);
7448 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007449 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007450
Rafael Espindola0b062072012-01-03 06:04:21 +00007451 if (Attr)
7452 ProcessDeclAttributeList(S, Specialization, Attr);
7453
Abramo Bagnara8075c852010-06-12 07:44:57 +00007454 // Add the explicit instantiation into its lexical context. However,
7455 // since explicit instantiations are never found by name lookup, we
7456 // just put it into the declaration context directly.
7457 Specialization->setLexicalDeclContext(CurContext);
7458 CurContext->addDecl(Specialization);
7459
7460 // Syntax is now OK, so return if it has no other effect on semantics.
7461 if (HasNoEffect) {
7462 // Set the template specialization kind.
7463 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007464 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007465 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007466
7467 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007468 // A definition of a class template or class member template
7469 // shall be in scope at the point of the explicit instantiation of
7470 // the class template or class member template.
7471 //
7472 // This check comes when we actually try to perform the
7473 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007474 ClassTemplateSpecializationDecl *Def
7475 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007476 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007477 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007478 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007479 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007480 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007481 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7482 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007483
Douglas Gregor1d957a32009-10-27 18:42:08 +00007484 // Instantiate the members of this class template specialization.
7485 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007486 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007487 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007488 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7489
7490 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7491 // TSK_ExplicitInstantiationDefinition
7492 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00007493 TSK == TSK_ExplicitInstantiationDefinition) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007494 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007495 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007496
Hans Wennborgc0875502015-06-09 00:39:05 +00007497 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7498 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7499 // In the MS ABI, an explicit instantiation definition can add a dll
7500 // attribute to a template with a previous instantiation declaration.
7501 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007502 auto *A = cast<InheritableAttr>(
7503 getDLLAttr(Specialization)->clone(getASTContext()));
7504 A->setInherited(true);
7505 Def->addAttr(A);
Reid Kleckner5b640342016-02-26 19:51:02 +00007506
7507 // We reject explicit instantiations in class scope, so there should
7508 // never be any delayed exported classes to worry about.
7509 assert(DelayedDllExportClasses.empty() &&
7510 "delayed exports present at explicit instantiation");
Hans Wennborg17f9b442015-05-27 00:06:45 +00007511 checkClassLevelDLLAttribute(Def);
Reid Kleckner5b640342016-02-26 19:51:02 +00007512 referenceDLLExportedClassMethods();
Hans Wennborgfce87ca2015-06-09 00:39:09 +00007513
7514 // Propagate attribute to base class templates.
7515 for (auto &B : Def->bases()) {
7516 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7517 B.getType()->getAsCXXRecordDecl()))
7518 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7519 }
Hans Wennborg17f9b442015-05-27 00:06:45 +00007520 }
7521 }
7522
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007523 // Set the template specialization kind. Make sure it is set before
7524 // instantiating the members which will trigger ASTConsumer callbacks.
7525 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007526 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007527 } else {
7528
7529 // Set the template specialization kind.
7530 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007531 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007532
John McCall48871652010-08-21 09:40:31 +00007533 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007534}
7535
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007536// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007537DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007538Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007539 SourceLocation ExternLoc,
7540 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007541 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007542 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007543 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007544 IdentifierInfo *Name,
7545 SourceLocation NameLoc,
7546 AttributeList *Attr) {
7547
Douglas Gregord6ab8742009-05-28 23:31:59 +00007548 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007549 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007550 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007551 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007552 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007553 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007554 SourceLocation(), false, TypeResult(),
7555 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007556 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7557
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007558 if (!TagD)
7559 return true;
7560
John McCall48871652010-08-21 09:40:31 +00007561 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007562 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007563
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007564 if (Tag->isInvalidDecl())
7565 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007566
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007567 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7568 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7569 if (!Pattern) {
7570 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7571 << Context.getTypeDeclType(Record);
7572 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7573 return true;
7574 }
7575
Douglas Gregore47f5a72009-10-14 23:41:34 +00007576 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007577 // If the explicit instantiation is for a class or member class, the
7578 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007579 // simple-template-id.
7580 //
7581 // C++98 has the same restriction, just worded differently.
7582 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007583 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007584 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007585
Douglas Gregore47f5a72009-10-14 23:41:34 +00007586 // C++0x [temp.explicit]p2:
7587 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007588 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007589 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007590 TemplateSpecializationKind TSK
7591 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7592 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007593
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007594 // C++0x [temp.explicit]p2:
7595 // [...] An explicit instantiation shall appear in an enclosing
7596 // namespace of its template. [...]
7597 //
7598 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007599 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007600
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007601 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007602 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007603 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007604 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007605 PrevDecl = Record;
7606 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007607 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007608 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007609 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007610 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007611 PrevDecl,
7612 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007613 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007614 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007615 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007616 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007617 return TagD;
7618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007619
Douglas Gregor12e49d32009-10-15 22:53:21 +00007620 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007621 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007622 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007623 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007624 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007625 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007626 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007627 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007628 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007629 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7630 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007631 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7632 << Pattern;
7633 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007634 } else {
7635 if (InstantiateClass(NameLoc, Record, Def,
7636 getTemplateInstantiationArgs(Record),
7637 TSK))
7638 return true;
7639
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007640 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007641 if (!RecordDef)
7642 return true;
7643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007644 }
7645
Douglas Gregor1d957a32009-10-27 18:42:08 +00007646 // Instantiate all of the members of the class.
7647 InstantiateClassMembers(NameLoc, RecordDef,
7648 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007649
Douglas Gregor88d292c2010-05-13 16:44:06 +00007650 if (TSK == TSK_ExplicitInstantiationDefinition)
7651 MarkVTableUsed(NameLoc, RecordDef, true);
7652
Mike Stump87c57ac2009-05-16 07:39:55 +00007653 // FIXME: We don't have any representation for explicit instantiations of
7654 // member classes. Such a representation is not needed for compilation, but it
7655 // should be available for clients that want to see all of the declarations in
7656 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007657 return TagD;
7658}
7659
John McCallfaf5fb42010-08-26 23:41:50 +00007660DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7661 SourceLocation ExternLoc,
7662 SourceLocation TemplateLoc,
7663 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007664 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007665 // TODO: check if/when DNInfo should replace Name.
7666 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7667 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007668 if (!Name) {
7669 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007670 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007671 diag::err_explicit_instantiation_requires_name)
7672 << D.getDeclSpec().getSourceRange()
7673 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007674
Douglas Gregor450f00842009-09-25 18:43:00 +00007675 return true;
7676 }
7677
7678 // The scope passed in may not be a decl scope. Zip up the scope tree until
7679 // we find one that is.
7680 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7681 (S->getFlags() & Scope::TemplateParamScope) != 0)
7682 S = S->getParent();
7683
7684 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007685 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7686 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007687 if (R.isNull())
7688 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007689
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007690 // C++ [dcl.stc]p1:
7691 // A storage-class-specifier shall not be specified in [...] an explicit
7692 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007693 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007694 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7695 << Name;
7696 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007697 } else if (D.getDeclSpec().getStorageClassSpec()
7698 != DeclSpec::SCS_unspecified) {
7699 // Complain about then remove the storage class specifier.
7700 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7701 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7702
7703 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007704 }
7705
Douglas Gregor3c74d412009-10-14 20:14:33 +00007706 // C++0x [temp.explicit]p1:
7707 // [...] An explicit instantiation of a function template shall not use the
7708 // inline or constexpr specifiers.
7709 // Presumably, this also applies to member functions of class templates as
7710 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007711 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007712 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007713 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007714 diag::err_explicit_instantiation_inline :
7715 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007716 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007717 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007718 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7719 // not already specified.
7720 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7721 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007722
Nathan Wilsonde498452016-02-08 05:34:00 +00007723 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7724 // applied only to the definition of a function template or variable template,
7725 // declared in namespace scope.
7726 if (D.getDeclSpec().isConceptSpecified()) {
7727 Diag(D.getDeclSpec().getConceptSpecLoc(),
7728 diag::err_concept_specified_specialization) << 0;
7729 return true;
7730 }
7731
Douglas Gregore47f5a72009-10-14 23:41:34 +00007732 // C++0x [temp.explicit]p2:
7733 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007734 // definition and an explicit instantiation declaration. An explicit
7735 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007736 TemplateSpecializationKind TSK
7737 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7738 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007739
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007740 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007741 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007742
7743 if (!R->isFunctionType()) {
7744 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007745 // A [...] static data member of a class template can be explicitly
7746 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007747 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007748 // C++1y [temp.explicit]p1:
7749 // A [...] variable [...] template specialization can be explicitly
7750 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007751 if (Previous.isAmbiguous())
7752 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007753
John McCall67c00872009-12-02 08:25:40 +00007754 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007755 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007756
Larisse Voufo39a1e502013-08-06 01:03:05 +00007757 if (!PrevTemplate) {
7758 if (!Prev || !Prev->isStaticDataMember()) {
7759 // We expect to see a data data member here.
7760 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7761 << Name;
7762 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7763 P != PEnd; ++P)
7764 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7765 return true;
7766 }
7767
7768 if (!Prev->getInstantiatedFromStaticDataMember()) {
7769 // FIXME: Check for explicit specialization?
7770 Diag(D.getIdentifierLoc(),
7771 diag::err_explicit_instantiation_data_member_not_instantiated)
7772 << Prev;
7773 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7774 // FIXME: Can we provide a note showing where this was declared?
7775 return true;
7776 }
7777 } else {
7778 // Explicitly instantiate a variable template.
7779
7780 // C++1y [dcl.spec.auto]p6:
7781 // ... A program that uses auto or decltype(auto) in a context not
7782 // explicitly allowed in this section is ill-formed.
7783 //
7784 // This includes auto-typed variable template instantiations.
7785 if (R->isUndeducedType()) {
7786 Diag(T->getTypeLoc().getLocStart(),
7787 diag::err_auto_not_allowed_var_inst);
7788 return true;
7789 }
7790
Richard Smithef985ac2013-09-18 02:10:12 +00007791 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7792 // C++1y [temp.explicit]p3:
7793 // If the explicit instantiation is for a variable, the unqualified-id
7794 // in the declaration shall be a template-id.
7795 Diag(D.getIdentifierLoc(),
7796 diag::err_explicit_instantiation_without_template_id)
7797 << PrevTemplate;
7798 Diag(PrevTemplate->getLocation(),
7799 diag::note_explicit_instantiation_here);
7800 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007801 }
7802
Nathan Wilson83839122016-04-09 02:55:27 +00007803 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
7804 // explicit instantiation (14.8.2) [...] of a concept definition.
7805 if (PrevTemplate->isConcept()) {
7806 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
7807 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
7808 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
7809 return true;
7810 }
7811
Richard Smithef985ac2013-09-18 02:10:12 +00007812 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007813 TemplateArgumentListInfo TemplateArgs =
7814 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007815
Larisse Voufo39a1e502013-08-06 01:03:05 +00007816 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7817 D.getIdentifierLoc(), TemplateArgs);
7818 if (Res.isInvalid())
7819 return true;
7820
7821 // Ignore access control bits, we don't need them for redeclaration
7822 // checking.
7823 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007824 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007825
Douglas Gregore47f5a72009-10-14 23:41:34 +00007826 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007827 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007828 // or a static data member of a class template specialization, the name of
7829 // the class template specialization in the qualified-id for the member
7830 // name shall be a simple-template-id.
7831 //
7832 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007833 //
Richard Smith5977d872013-09-18 21:55:14 +00007834 // This does not apply to variable template specializations, where the
7835 // template-id is in the unqualified-id instead.
7836 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007837 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007838 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007839 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007840
Douglas Gregore47f5a72009-10-14 23:41:34 +00007841 // Check the scope of this explicit instantiation.
7842 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007843
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007844 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007845 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7846 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007847 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007848 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007849 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007850 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007851
Larisse Voufo39a1e502013-08-06 01:03:05 +00007852 if (!HasNoEffect) {
7853 // Instantiate static data member or variable template.
7854
7855 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7856 if (PrevTemplate) {
7857 // Merge attributes.
7858 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7859 ProcessDeclAttributeList(S, Prev, Attr);
7860 }
7861 if (TSK == TSK_ExplicitInstantiationDefinition)
7862 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7863 }
7864
7865 // Check the new variable specialization against the parsed input.
7866 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7867 Diag(T->getTypeLoc().getLocStart(),
7868 diag::err_invalid_var_template_spec_type)
7869 << 0 << PrevTemplate << R << Prev->getType();
7870 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7871 << 2 << PrevTemplate->getDeclName();
7872 return true;
7873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007874
Douglas Gregor450f00842009-09-25 18:43:00 +00007875 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007876 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007877 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007878
7879 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007880 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007881 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007882 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007883 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007884 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007885 HasExplicitTemplateArgs = true;
7886 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007887
Douglas Gregor450f00842009-09-25 18:43:00 +00007888 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007889 // A [...] function [...] can be explicitly instantiated from its template.
7890 // A member function [...] of a class template can be explicitly
7891 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007892 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007893 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007894 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007895 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7896 P != PEnd; ++P) {
7897 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007898 if (!HasExplicitTemplateArgs) {
7899 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007900 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7901 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007902 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007903
John McCall58cc69d2010-01-27 01:50:18 +00007904 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007905 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7906 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007907 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007908 }
7909 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007910
Douglas Gregor450f00842009-09-25 18:43:00 +00007911 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7912 if (!FunTmpl)
7913 continue;
7914
Larisse Voufo98b20f12013-07-19 23:00:19 +00007915 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007916 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007917 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007918 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007919 (HasExplicitTemplateArgs ? &TemplateArgs
7920 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007921 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007922 // Keep track of almost-matches.
7923 FailedCandidates.addCandidate()
7924 .set(FunTmpl->getTemplatedDecl(),
7925 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007926 (void)TDK;
7927 continue;
7928 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007929
John McCall58cc69d2010-01-27 01:50:18 +00007930 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007932
Douglas Gregor450f00842009-09-25 18:43:00 +00007933 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007934 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007935 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007936 D.getIdentifierLoc(),
7937 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7938 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7939 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007940
John McCall58cc69d2010-01-27 01:50:18 +00007941 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007942 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007943
7944 // Ignore access control bits, we don't need them for redeclaration checking.
7945 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007946
Alexey Bataev73983912014-11-06 10:10:50 +00007947 // C++11 [except.spec]p4
7948 // In an explicit instantiation an exception-specification may be specified,
7949 // but is not required.
7950 // If an exception-specification is specified in an explicit instantiation
7951 // directive, it shall be compatible with the exception-specifications of
7952 // other declarations of that function.
7953 if (auto *FPT = R->getAs<FunctionProtoType>())
7954 if (FPT->hasExceptionSpec()) {
7955 unsigned DiagID =
7956 diag::err_mismatched_exception_spec_explicit_instantiation;
7957 if (getLangOpts().MicrosoftExt)
7958 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7959 bool Result = CheckEquivalentExceptionSpec(
7960 PDiag(DiagID) << Specialization->getType(),
7961 PDiag(diag::note_explicit_instantiation_here),
7962 Specialization->getType()->getAs<FunctionProtoType>(),
7963 Specialization->getLocation(), FPT, D.getLocStart());
7964 // In Microsoft mode, mismatching exception specifications just cause a
7965 // warning.
7966 if (!getLangOpts().MicrosoftExt && Result)
7967 return true;
7968 }
7969
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007970 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007971 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007972 diag::err_explicit_instantiation_member_function_not_instantiated)
7973 << Specialization
7974 << (Specialization->getTemplateSpecializationKind() ==
7975 TSK_ExplicitSpecialization);
7976 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7977 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007978 }
7979
Douglas Gregorec9fd132012-01-14 16:38:05 +00007980 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00007981 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7982 PrevDecl = Specialization;
7983
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007984 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007985 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007986 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007987 PrevDecl,
7988 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007989 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007990 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007991 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007992
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007993 // FIXME: We may still want to build some representation of this
7994 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007995 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00007996 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007997 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00007998
7999 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008000 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
8001 if (Attr)
8002 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008003
Richard Smitheb36ddf2014-04-24 22:45:46 +00008004 if (Specialization->isDefined()) {
8005 // Let the ASTConsumer know that this function has been explicitly
8006 // instantiated now, and its linkage might have changed.
8007 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8008 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008009 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008010
Douglas Gregore47f5a72009-10-14 23:41:34 +00008011 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008012 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008013 // or a static data member of a class template specialization, the name of
8014 // the class template specialization in the qualified-id for the member
8015 // name shall be a simple-template-id.
8016 //
8017 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008018 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008019 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008020 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008021 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008022 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008023 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008024 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008025
Nathan Wilson83839122016-04-09 02:55:27 +00008026 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8027 // explicit instantiation (14.8.2) [...] of a concept definition.
8028 if (FunTmpl && FunTmpl->isConcept() &&
8029 !D.getDeclSpec().isConceptSpecified()) {
8030 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8031 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8032 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8033 return true;
8034 }
8035
Douglas Gregore47f5a72009-10-14 23:41:34 +00008036 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008037 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008038 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008039 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008040 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008041
Douglas Gregor450f00842009-09-25 18:43:00 +00008042 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008043 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008044}
8045
John McCallfaf5fb42010-08-26 23:41:50 +00008046TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008047Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8048 const CXXScopeSpec &SS, IdentifierInfo *Name,
8049 SourceLocation TagLoc, SourceLocation NameLoc) {
8050 // This has to hold, because SS is expected to be defined.
8051 assert(Name && "Expected a name in a dependent tag");
8052
Aaron Ballman4a979672014-01-03 13:56:08 +00008053 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008054 if (!NNS)
8055 return true;
8056
Abramo Bagnara6150c882010-05-11 21:36:43 +00008057 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008058
Douglas Gregorba41d012010-04-24 16:38:41 +00008059 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8060 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008061 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008062 return true;
8063 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008064
Douglas Gregore7c20652011-03-02 00:47:37 +00008065 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008066 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008067 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8068
8069 // Create type-source location information for this type.
8070 TypeLocBuilder TLB;
8071 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008072 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008073 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8074 TL.setNameLoc(NameLoc);
8075 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008076}
8077
John McCallfaf5fb42010-08-26 23:41:50 +00008078TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008079Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8080 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008081 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008082 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008083 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008084
Richard Smith0bf8a4922011-10-18 20:49:44 +00008085 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8086 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008087 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008088 diag::warn_cxx98_compat_typename_outside_of_template :
8089 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008090 << FixItHint::CreateRemoval(TypenameLoc);
8091
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008092 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008093 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8094 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008095 if (T.isNull())
8096 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008097
8098 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8099 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008100 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008101 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008102 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008103 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008104 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008105 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008106 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008107 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008108 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008109 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008110
John McCallba7bf592010-08-24 05:47:05 +00008111 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008112}
8113
John McCallfaf5fb42010-08-26 23:41:50 +00008114TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008115Sema::ActOnTypenameType(Scope *S,
8116 SourceLocation TypenameLoc,
8117 const CXXScopeSpec &SS,
8118 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008119 TemplateTy TemplateIn,
8120 SourceLocation TemplateNameLoc,
8121 SourceLocation LAngleLoc,
8122 ASTTemplateArgsPtr TemplateArgsIn,
8123 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008124 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8125 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008126 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008127 diag::warn_cxx98_compat_typename_outside_of_template :
8128 diag::ext_typename_outside_of_template)
8129 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008130
8131 // Translate the parser's template argument list in our AST format.
8132 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8133 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8134
8135 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008136 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8137 // Construct a dependent template specialization type.
8138 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008139 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008140 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8141 DTN->getQualifier(),
8142 DTN->getIdentifier(),
8143 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008144
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008145 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008146 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008147 DependentTemplateSpecializationTypeLoc SpecTL
8148 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008149 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8150 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008151 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008152 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008153 SpecTL.setLAngleLoc(LAngleLoc);
8154 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008155 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8156 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008157 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008158 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008159
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008160 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8161 if (T.isNull())
8162 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008163
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008164 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008165 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008166 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008167 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008168 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8169 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008170 SpecTL.setLAngleLoc(LAngleLoc);
8171 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008172 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8173 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8174
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008175 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8176 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008177 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008178 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8179
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008180 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8181 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008182}
8183
Douglas Gregorb09518c2011-02-27 22:46:49 +00008184
Richard Smith6f8d2c62012-05-09 05:17:00 +00008185/// Determine whether this failed name lookup should be treated as being
8186/// disabled by a usage of std::enable_if.
8187static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8188 SourceRange &CondRange) {
8189 // We must be looking for a ::type...
8190 if (!II.isStr("type"))
8191 return false;
8192
8193 // ... within an explicitly-written template specialization...
8194 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8195 return false;
8196 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008197 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8198 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8199 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008200 return false;
8201 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008202 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008203
8204 // ... which names a complete class template declaration...
8205 const TemplateDecl *EnableIfDecl =
8206 EnableIfTST->getTemplateName().getAsTemplateDecl();
8207 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8208 return false;
8209
8210 // ... called "enable_if".
8211 const IdentifierInfo *EnableIfII =
8212 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8213 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8214 return false;
8215
8216 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008217 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008218 return true;
8219}
8220
Douglas Gregor333489b2009-03-27 23:10:48 +00008221/// \brief Build the type that describes a C++ typename specifier,
8222/// e.g., "typename T::type".
8223QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008224Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8225 SourceLocation KeywordLoc,
8226 NestedNameSpecifierLoc QualifierLoc,
8227 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008228 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008229 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008230 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008231
John McCall0b66eb32010-05-01 00:40:08 +00008232 DeclContext *Ctx = computeDeclContext(SS);
8233 if (!Ctx) {
8234 // If the nested-name-specifier is dependent and couldn't be
8235 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008236 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8237 return Context.getDependentNameType(Keyword,
8238 QualifierLoc.getNestedNameSpecifier(),
8239 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008240 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008241
John McCall0b66eb32010-05-01 00:40:08 +00008242 // If the nested-name-specifier refers to the current instantiation,
8243 // the "typename" keyword itself is superfluous. In C++03, the
8244 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8245 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008246 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008247
John McCall0b66eb32010-05-01 00:40:08 +00008248 if (RequireCompleteDeclContext(SS, Ctx))
8249 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008250
8251 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008252 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008253 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008254 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008255 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008256 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008257 case LookupResult::NotFound: {
8258 // If we're looking up 'type' within a template named 'enable_if', produce
8259 // a more specific diagnostic.
8260 SourceRange CondRange;
8261 if (isEnableIf(QualifierLoc, II, CondRange)) {
8262 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8263 << Ctx << CondRange;
8264 return QualType();
8265 }
8266
Douglas Gregore40876a2009-10-13 21:16:44 +00008267 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008268 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008269 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008270
8271 case LookupResult::FoundUnresolvedValue: {
8272 // We found a using declaration that is a value. Most likely, the using
8273 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008274 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008275 IILoc);
8276 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8277 << Name << Ctx << FullRange;
8278 if (UnresolvedUsingValueDecl *Using
8279 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008280 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008281 Diag(Loc, diag::note_using_value_decl_missing_typename)
8282 << FixItHint::CreateInsertion(Loc, "typename ");
8283 }
8284 }
8285 // Fall through to create a dependent typename type, from which we can recover
8286 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008287
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008288 case LookupResult::NotFoundInCurrentInstantiation:
8289 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008290 return Context.getDependentNameType(Keyword,
8291 QualifierLoc.getNestedNameSpecifier(),
8292 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008293
8294 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008295 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008296 // We found a type. Build an ElaboratedType, since the
8297 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008298 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008299 return Context.getElaboratedType(ETK_Typename,
8300 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008301 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008302 }
8303
8304 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008305 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008306 break;
8307
8308 case LookupResult::FoundOverloaded:
8309 DiagID = diag::err_typename_nested_not_type;
8310 Referenced = *Result.begin();
8311 break;
8312
John McCall6538c932009-10-10 05:48:19 +00008313 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008314 return QualType();
8315 }
8316
8317 // If we get here, it's because name lookup did not find a
8318 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008319 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008320 IILoc);
8321 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008322 if (Referenced)
8323 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8324 << Name;
8325 return QualType();
8326}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008327
8328namespace {
8329 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008330 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008331 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008332 SourceLocation Loc;
8333 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008334
Douglas Gregor15acfb92009-08-06 16:20:37 +00008335 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008336 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008337
Mike Stump11289f42009-09-09 15:08:12 +00008338 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008339 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008340 DeclarationName Entity)
8341 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008342 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008343
8344 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008345 /// transformed.
8346 ///
8347 /// For the purposes of type reconstruction, a type has already been
8348 /// transformed if it is NULL or if it is not dependent.
8349 bool AlreadyTransformed(QualType T) {
8350 return T.isNull() || !T->isDependentType();
8351 }
Mike Stump11289f42009-09-09 15:08:12 +00008352
8353 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008354 /// rebuilt.
8355 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008356
Douglas Gregor15acfb92009-08-06 16:20:37 +00008357 /// \brief Returns the name of the entity whose type is being rebuilt.
8358 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008359
Douglas Gregoref6ab412009-10-27 06:26:26 +00008360 /// \brief Sets the "base" location and entity when that
8361 /// information is known based on another transformation.
8362 void setBase(SourceLocation Loc, DeclarationName Entity) {
8363 this->Loc = Loc;
8364 this->Entity = Entity;
8365 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008366
8367 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8368 // Lambdas never need to be transformed.
8369 return E;
8370 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008371 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008372} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008373
Douglas Gregor15acfb92009-08-06 16:20:37 +00008374/// \brief Rebuilds a type within the context of the current instantiation.
8375///
Mike Stump11289f42009-09-09 15:08:12 +00008376/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008377/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008378/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008379/// partial specialization thereof). This routine will rebuild that type now
8380/// that we have entered the declarator's scope, which may produce different
8381/// canonical types, e.g.,
8382///
8383/// \code
8384/// template<typename T>
8385/// struct X {
8386/// typedef T* pointer;
8387/// pointer data();
8388/// };
8389///
8390/// template<typename T>
8391/// typename X<T>::pointer X<T>::data() { ... }
8392/// \endcode
8393///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008394/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008395/// since we do not know that we can look into X<T> when we parsed the type.
8396/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008397/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008398/// as the canonical type of T*, allowing the return types of the out-of-line
8399/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008400TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8401 SourceLocation Loc,
8402 DeclarationName Name) {
8403 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008404 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008405
Douglas Gregor15acfb92009-08-06 16:20:37 +00008406 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8407 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008408}
Douglas Gregorbe999392009-09-15 16:23:51 +00008409
John McCalldadc5752010-08-24 06:29:42 +00008410ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008411 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8412 DeclarationName());
8413 return Rebuilder.TransformExpr(E);
8414}
8415
John McCall99b2fe52010-04-29 23:50:39 +00008416bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008417 if (SS.isInvalid())
8418 return true;
John McCall2408e322010-04-27 00:57:59 +00008419
Douglas Gregor10176412011-02-25 16:07:42 +00008420 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008421 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8422 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008423 NestedNameSpecifierLoc Rebuilt
8424 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8425 if (!Rebuilt)
8426 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008427
Douglas Gregor10176412011-02-25 16:07:42 +00008428 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008429 return false;
John McCall2408e322010-04-27 00:57:59 +00008430}
8431
Douglas Gregor041b0842011-10-14 15:31:12 +00008432/// \brief Rebuild the template parameters now that we know we're in a current
8433/// instantiation.
8434bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8435 TemplateParameterList *Params) {
8436 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8437 Decl *Param = Params->getParam(I);
8438
8439 // There is nothing to rebuild in a type parameter.
8440 if (isa<TemplateTypeParmDecl>(Param))
8441 continue;
8442
8443 // Rebuild the template parameter list of a template template parameter.
8444 if (TemplateTemplateParmDecl *TTP
8445 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8446 if (RebuildTemplateParamsInCurrentInstantiation(
8447 TTP->getTemplateParameters()))
8448 return true;
8449
8450 continue;
8451 }
8452
8453 // Rebuild the type of a non-type template parameter.
8454 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8455 TypeSourceInfo *NewTSI
8456 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8457 NTTP->getLocation(),
8458 NTTP->getDeclName());
8459 if (!NewTSI)
8460 return true;
8461
8462 if (NewTSI != NTTP->getTypeSourceInfo()) {
8463 NTTP->setTypeSourceInfo(NewTSI);
8464 NTTP->setType(NewTSI->getType());
8465 }
8466 }
8467
8468 return false;
8469}
8470
Douglas Gregorbe999392009-09-15 16:23:51 +00008471/// \brief Produces a formatted string that describes the binding of
8472/// template parameters to template arguments.
8473std::string
8474Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8475 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008476 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008477}
8478
8479std::string
8480Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8481 const TemplateArgument *Args,
8482 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008483 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008484 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008485
Douglas Gregore62e6a02009-11-11 19:13:48 +00008486 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008487 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008488
Douglas Gregorbe999392009-09-15 16:23:51 +00008489 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008490 if (I >= NumArgs)
8491 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008492
Douglas Gregorbe999392009-09-15 16:23:51 +00008493 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008494 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008495 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008496 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008497
Douglas Gregorbe999392009-09-15 16:23:51 +00008498 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008499 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008500 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008501 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008503
Douglas Gregor0192c232010-12-20 16:52:59 +00008504 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008505 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008506 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008507
8508 Out << ']';
8509 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008510}
Francois Pichet1c229c02011-04-22 22:18:13 +00008511
Richard Smithe40f2ba2013-08-07 21:41:30 +00008512void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8513 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008514 if (!FD)
8515 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008516
8517 LateParsedTemplate *LPT = new LateParsedTemplate;
8518
8519 // Take tokens to avoid allocations
8520 LPT->Toks.swap(Toks);
8521 LPT->D = FnD;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00008522 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008523
8524 FD->setLateTemplateParsed(true);
8525}
8526
8527void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8528 if (!FD)
8529 return;
8530 FD->setLateTemplateParsed(false);
8531}
Francois Pichet1c229c02011-04-22 22:18:13 +00008532
8533bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8534 DeclContext *DC = CurContext;
8535
8536 while (DC) {
8537 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8538 const FunctionDecl *FD = RD->isLocalClass();
8539 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8540 } else if (DC->isTranslationUnit() || DC->isNamespace())
8541 return false;
8542
8543 DC = DC->getParent();
8544 }
8545 return false;
8546}