blob: 0b4b083ffbda9ad4b31bf1fb25dd1af5ad66c8b7 [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()) {
803 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
804 << 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
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000820/// ActOnTemplateParameterList - Builds a TemplateParameterList that
821/// contains the template parameters in Params/NumParams.
Richard Trieu9becef62011-09-09 03:18:59 +0000822TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000823Sema::ActOnTemplateParameterList(unsigned Depth,
824 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000825 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000826 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000827 ArrayRef<Decl *> Params,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000828 SourceLocation RAngleLoc) {
829 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000830 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000831
David Majnemer902f8c62015-12-27 07:16:27 +0000832 return TemplateParameterList::Create(
833 Context, TemplateLoc, LAngleLoc,
834 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
835 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000836}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000837
John McCall3e11ebe2010-03-15 10:12:16 +0000838static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
839 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000840 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000841}
842
John McCallfaf5fb42010-08-26 23:41:50 +0000843DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000844Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000845 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000846 IdentifierInfo *Name, SourceLocation NameLoc,
847 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000848 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000849 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000850 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000851 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000852 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000853 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000854 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000855 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000856 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000857 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000858
859 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000860 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000861 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000862
Abramo Bagnara6150c882010-05-11 21:36:43 +0000863 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
864 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000865
866 // There is no such thing as an unnamed class template.
867 if (!Name) {
868 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000869 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000870 }
871
Richard Smith6483d222012-04-21 01:27:54 +0000872 // Find any previous declaration with this name. For a friend with no
873 // scope explicitly specified, we only look for tag declarations (per
874 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000875 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000876 LookupResult Previous(*this, Name, NameLoc,
877 (SS.isEmpty() && TUK == TUK_Friend)
878 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000879 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000880 if (SS.isNotEmpty() && !SS.isInvalid()) {
881 SemanticContext = computeDeclContext(SS, true);
882 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000883 // FIXME: Horrible, horrible hack! We can't currently represent this
884 // in the AST, and historically we have just ignored such friend
885 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000886 Diag(NameLoc, TUK == TUK_Friend
887 ? diag::warn_template_qualified_friend_ignored
888 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000889 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000890 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000891 }
Mike Stump11289f42009-09-09 15:08:12 +0000892
John McCall0b66eb32010-05-01 00:40:08 +0000893 if (RequireCompleteDeclContext(SS, SemanticContext))
894 return true;
895
Douglas Gregor041b0842011-10-14 15:31:12 +0000896 // If we're adding a template to a dependent context, we may need to
897 // rebuilding some of the types used within the template parameter list,
898 // now that we know what the current instantiation is.
899 if (SemanticContext->isDependentContext()) {
900 ContextRAII SavedContext(*this, SemanticContext);
901 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
902 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000903 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
904 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000905
John McCall27b18f82009-11-17 02:14:36 +0000906 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000907 } else {
908 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +0000909
910 // C++14 [class.mem]p14:
911 // If T is the name of a class, then each of the following shall have a
912 // name different from T:
913 // -- every member template of class T
914 if (TUK != TUK_Friend &&
915 DiagnoseClassNameShadow(SemanticContext,
916 DeclarationNameInfo(Name, NameLoc)))
917 return true;
918
John McCall27b18f82009-11-17 02:14:36 +0000919 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000920 }
Mike Stump11289f42009-09-09 15:08:12 +0000921
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000922 if (Previous.isAmbiguous())
923 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000924
Craig Topperc3ec1492014-05-26 06:22:03 +0000925 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000926 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000927 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000928
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000929 // If there is a previous declaration with the same name, check
930 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000931 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000932 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000933
934 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000935 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000936 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000937 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000938 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
939 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000940 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000941 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
942 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
943 PrevClassTemplate
944 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
945 ->getSpecializedTemplate();
946 }
947 }
948
John McCalld43784f2009-12-18 11:25:59 +0000949 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000950 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000951 // [...] When looking for a prior declaration of a class or a function
952 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000953 // function is neither a qualified name nor a template-id, scopes outside
954 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000955 if (!SS.isSet()) {
956 DeclContext *OutermostContext = CurContext;
957 while (!OutermostContext->isFileContext())
958 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000959
Richard Smith61e582f2012-04-20 07:12:26 +0000960 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000961 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
962 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
963 SemanticContext = PrevDecl->getDeclContext();
964 } else {
965 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000966 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000967 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +0000968 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +0000969 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000970
971 // Check that the chosen semantic context doesn't already contain a
972 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +0000973 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +0000974 DeclContext *LookupContext = SemanticContext;
975 while (LookupContext->isTransparentContext())
976 LookupContext = LookupContext->getLookupParent();
977 LookupQualifiedName(Previous, LookupContext);
978
979 if (Previous.isAmbiguous())
980 return true;
981
982 if (Previous.begin() != Previous.end())
983 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000984 }
John McCall90d3bb92009-12-17 23:21:11 +0000985 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000986 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +0000987 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
988 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000989 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000990
Richard Smithfc805ca2015-07-06 04:43:58 +0000991 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
992 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
993 if (SS.isEmpty() &&
994 !(PrevClassTemplate &&
995 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
996 SemanticContext->getRedeclContext()))) {
997 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
998 Diag(Shadow->getTargetDecl()->getLocation(),
999 diag::note_using_decl_target);
1000 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1001 // Recover by ignoring the old declaration.
1002 PrevDecl = PrevClassTemplate = nullptr;
1003 }
1004 }
1005
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001006 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001007 // Ensure that the template parameter lists are compatible. Skip this check
1008 // for a friend in a dependent context: the template parameter list itself
1009 // could be dependent.
1010 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1011 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001012 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001013 /*Complain=*/true,
1014 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001015 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001016
1017 // C++ [temp.class]p4:
1018 // In a redeclaration, partial specialization, explicit
1019 // specialization or explicit instantiation of a class template,
1020 // the class-key shall agree in kind with the original class
1021 // template declaration (7.1.5.3).
1022 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001023 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001024 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001025 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001026 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001027 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001028 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001029 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001030 }
1031
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001032 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001033 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001034 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001035 // If we have a prior definition that is not visible, treat this as
1036 // simply making that previous definition visible.
1037 NamedDecl *Hidden = nullptr;
1038 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001039 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001040 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1041 assert(Tmpl && "original definition of a class template is not a "
1042 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001043 makeMergedDefinitionVisible(Hidden, KWLoc);
1044 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001045 return Def;
1046 }
1047
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001048 Diag(NameLoc, diag::err_redefinition) << Name;
1049 Diag(Def->getLocation(), diag::note_previous_definition);
1050 // FIXME: Would it make sense to try to "forget" the previous
1051 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001052 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001053 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001054 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001055 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1056 // Maybe we will complain about the shadowed template parameter.
1057 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1058 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001059 PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001060 } else if (PrevDecl) {
1061 // C++ [temp]p5:
1062 // A class template shall not have the same name as any other
1063 // template, class, function, object, enumeration, enumerator,
1064 // namespace, or type in the same scope (3.3), except as specified
1065 // in (14.5.4).
1066 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1067 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001068 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001069 }
1070
Douglas Gregordba32632009-02-10 19:49:53 +00001071 // Check the template parameter list of this declaration, possibly
1072 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001073 // template declaration. Skip this check for a friend in a dependent
1074 // context, because the template parameter list might be dependent.
1075 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001076 CheckTemplateParameterList(
1077 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001078 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1079 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001080 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1081 SemanticContext->isDependentContext())
1082 ? TPC_ClassTemplateMember
1083 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1084 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001085 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001086
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001087 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001088 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001089 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001090 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1091 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001092 : diag::err_member_decl_does_not_match)
1093 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001094 Invalid = true;
1095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001096 }
1097
Mike Stump11289f42009-09-09 15:08:12 +00001098 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001099 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001100 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001101 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001102 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001103 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001104 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001105 NewClass->setTemplateParameterListsInfo(
1106 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1107 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001108
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001109 // Add alignment attributes if necessary; these attributes are checked when
1110 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001111 if (TUK == TUK_Definition) {
1112 AddAlignmentAttributesForRecord(NewClass);
1113 AddMsStructLayoutForRecord(NewClass);
1114 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001115
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001116 ClassTemplateDecl *NewTemplate
1117 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1118 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001119 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001120 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001121
Douglas Gregor21823bf2011-12-20 18:11:52 +00001122 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001123 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001124
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001125 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001126 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001127 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001128 assert(T->isDependentType() && "Class template type is not dependent?");
1129 (void)T;
1130
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001131 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001132 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001133 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001134 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1135 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136
Anders Carlsson137108d2009-03-26 01:24:28 +00001137 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001138 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001139 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001140
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001141 // Set the lexical context of these templates
1142 NewClass->setLexicalDeclContext(CurContext);
1143 NewTemplate->setLexicalDeclContext(CurContext);
1144
John McCall9bb74a52009-07-31 02:45:11 +00001145 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001146 NewClass->startDefinition();
1147
1148 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001149 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001150
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001151 if (PrevClassTemplate)
1152 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1153
Rafael Espindola385c0422012-07-13 18:04:45 +00001154 AddPushedVisibilityAttribute(NewClass);
1155
Richard Smith234ff472014-08-23 00:49:01 +00001156 if (TUK != TUK_Friend) {
1157 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1158 Scope *Outer = S;
1159 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1160 Outer = Outer->getParent();
1161 PushOnScopeChains(NewTemplate, Outer);
1162 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001163 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001164 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001165 NewClass->setAccess(PrevClassTemplate->getAccess());
1166 }
John McCall27b5c252009-09-14 21:59:20 +00001167
Richard Smith64017682013-07-17 23:53:16 +00001168 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001169
John McCall27b5c252009-09-14 21:59:20 +00001170 // Friend templates are visible in fairly strange ways.
1171 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001172 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001173 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001174 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1175 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001176 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001177 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001178
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001179 FriendDecl *Friend = FriendDecl::Create(
1180 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001181 Friend->setAccess(AS_public);
1182 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001183 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001184
Douglas Gregordba32632009-02-10 19:49:53 +00001185 if (Invalid) {
1186 NewTemplate->setInvalidDecl();
1187 NewClass->setInvalidDecl();
1188 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001189
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001190 ActOnDocumentableDecl(NewTemplate);
1191
John McCall48871652010-08-21 09:40:31 +00001192 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001193}
1194
Douglas Gregored5731f2009-11-25 17:50:39 +00001195/// \brief Diagnose the presence of a default template argument on a
1196/// template parameter, which is ill-formed in certain contexts.
1197///
1198/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001199static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001200 Sema::TemplateParamListContext TPC,
1201 SourceLocation ParamLoc,
1202 SourceRange DefArgRange) {
1203 switch (TPC) {
1204 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001205 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001206 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001207 return false;
1208
1209 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001210 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001211 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001212 // A default template-argument shall not be specified in a
1213 // function template declaration or a function template
1214 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001215 // If a friend function template declaration specifies a default
1216 // template-argument, that declaration shall be a definition and shall be
1217 // the only declaration of the function template in the translation unit.
1218 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001219 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001220 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1221 : diag::ext_template_parameter_default_in_function_template)
1222 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001223 return false;
1224
1225 case Sema::TPC_ClassTemplateMember:
1226 // C++0x [temp.param]p9:
1227 // A default template-argument shall not be specified in the
1228 // template-parameter-lists of the definition of a member of a
1229 // class template that appears outside of the member's class.
1230 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1231 << DefArgRange;
1232 return true;
1233
David Majnemerba8f17a2013-06-25 22:08:55 +00001234 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001235 case Sema::TPC_FriendFunctionTemplate:
1236 // C++ [temp.param]p9:
1237 // A default template-argument shall not be specified in a
1238 // friend template declaration.
1239 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1240 << DefArgRange;
1241 return true;
1242
1243 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1244 // for friend function templates if there is only a single
1245 // declaration (and it is a definition). Strange!
1246 }
1247
David Blaikie8a40f702012-01-17 06:56:22 +00001248 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001249}
1250
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001251/// \brief Check for unexpanded parameter packs within the template parameters
1252/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001253static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1254 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001255 // A template template parameter which is a parameter pack is also a pack
1256 // expansion.
1257 if (TTP->isParameterPack())
1258 return false;
1259
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001260 TemplateParameterList *Params = TTP->getTemplateParameters();
1261 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1262 NamedDecl *P = Params->getParam(I);
1263 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001264 if (!NTTP->isParameterPack() &&
1265 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001266 NTTP->getTypeSourceInfo(),
1267 Sema::UPPC_NonTypeTemplateParameterType))
1268 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001269
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001270 continue;
1271 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001272
1273 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001274 = dyn_cast<TemplateTemplateParmDecl>(P))
1275 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1276 return true;
1277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001279 return false;
1280}
1281
Douglas Gregordba32632009-02-10 19:49:53 +00001282/// \brief Checks the validity of a template parameter list, possibly
1283/// considering the template parameter list from a previous
1284/// declaration.
1285///
1286/// If an "old" template parameter list is provided, it must be
1287/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1288/// template parameter list.
1289///
1290/// \param NewParams Template parameter list for a new template
1291/// declaration. This template parameter list will be updated with any
1292/// default arguments that are carried through from the previous
1293/// template parameter list.
1294///
1295/// \param OldParams If provided, template parameter list from a
1296/// previous declaration of the same template. Default template
1297/// arguments will be merged from the old template parameter list to
1298/// the new template parameter list.
1299///
Douglas Gregored5731f2009-11-25 17:50:39 +00001300/// \param TPC Describes the context in which we are checking the given
1301/// template parameter list.
1302///
Douglas Gregordba32632009-02-10 19:49:53 +00001303/// \returns true if an error occurred, false otherwise.
1304bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001305 TemplateParameterList *OldParams,
1306 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001307 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001308
Douglas Gregordba32632009-02-10 19:49:53 +00001309 // C++ [temp.param]p10:
1310 // The set of default template-arguments available for use with a
1311 // template declaration or definition is obtained by merging the
1312 // default arguments from the definition (if in scope) and all
1313 // declarations in scope in the same way default function
1314 // arguments are (8.3.6).
1315 bool SawDefaultArgument = false;
1316 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001317
Mike Stumpc89c8e32009-02-11 23:03:27 +00001318 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001319 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001320 if (OldParams)
1321 OldParam = OldParams->begin();
1322
Douglas Gregor0693def2011-01-27 01:40:17 +00001323 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001324 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1325 NewParamEnd = NewParams->end();
1326 NewParam != NewParamEnd; ++NewParam) {
1327 // Variables used to diagnose redundant default arguments
1328 bool RedundantDefaultArg = false;
1329 SourceLocation OldDefaultLoc;
1330 SourceLocation NewDefaultLoc;
1331
David Blaikie651c73c2011-10-19 05:19:50 +00001332 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001333 bool MissingDefaultArg = false;
1334
David Blaikie651c73c2011-10-19 05:19:50 +00001335 // Variable used to diagnose non-final parameter packs
1336 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001337
Douglas Gregordba32632009-02-10 19:49:53 +00001338 if (TemplateTypeParmDecl *NewTypeParm
1339 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001340 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001341 if (NewTypeParm->hasDefaultArgument() &&
1342 DiagnoseDefaultTemplateArgument(*this, TPC,
1343 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001344 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001345 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001346 NewTypeParm->removeDefaultArgument();
1347
1348 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001349 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001350 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001351 if (NewTypeParm->isParameterPack()) {
1352 assert(!NewTypeParm->hasDefaultArgument() &&
1353 "Parameter packs can't have a default argument!");
1354 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001355 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001356 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001357 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1358 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1359 SawDefaultArgument = true;
1360 RedundantDefaultArg = true;
1361 PreviousDefaultArgLoc = NewDefaultLoc;
1362 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1363 // Merge the default argument from the old declaration to the
1364 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001365 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001366 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1367 } else if (NewTypeParm->hasDefaultArgument()) {
1368 SawDefaultArgument = true;
1369 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1370 } else if (SawDefaultArgument)
1371 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001372 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001373 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001374 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001375 if (!NewNonTypeParm->isParameterPack() &&
1376 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001377 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001378 UPPC_NonTypeTemplateParameterType)) {
1379 Invalid = true;
1380 continue;
1381 }
1382
Douglas Gregored5731f2009-11-25 17:50:39 +00001383 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001384 if (NewNonTypeParm->hasDefaultArgument() &&
1385 DiagnoseDefaultTemplateArgument(*this, TPC,
1386 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001387 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001388 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001389 }
1390
Mike Stump12b8ce12009-08-04 21:02:39 +00001391 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001392 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001393 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001394 if (NewNonTypeParm->isParameterPack()) {
1395 assert(!NewNonTypeParm->hasDefaultArgument() &&
1396 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001397 if (!NewNonTypeParm->isPackExpansion())
1398 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001399 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001400 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001401 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1402 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1403 SawDefaultArgument = true;
1404 RedundantDefaultArg = true;
1405 PreviousDefaultArgLoc = NewDefaultLoc;
1406 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1407 // Merge the default argument from the old declaration to the
1408 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001409 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001410 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1411 } else if (NewNonTypeParm->hasDefaultArgument()) {
1412 SawDefaultArgument = true;
1413 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1414 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001415 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001416 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001417 TemplateTemplateParmDecl *NewTemplateParm
1418 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001419
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001420 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001421 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001422 Invalid = true;
1423 continue;
1424 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001425
David Blaikie651c73c2011-10-19 05:19:50 +00001426 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001427 if (NewTemplateParm->hasDefaultArgument() &&
1428 DiagnoseDefaultTemplateArgument(*this, TPC,
1429 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001430 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001431 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001432
1433 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001434 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001435 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001436 if (NewTemplateParm->isParameterPack()) {
1437 assert(!NewTemplateParm->hasDefaultArgument() &&
1438 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001439 if (!NewTemplateParm->isPackExpansion())
1440 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001441 } else if (OldTemplateParm &&
1442 hasVisibleDefaultArgument(OldTemplateParm) &&
1443 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001444 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1445 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001446 SawDefaultArgument = true;
1447 RedundantDefaultArg = true;
1448 PreviousDefaultArgLoc = NewDefaultLoc;
1449 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1450 // Merge the default argument from the old declaration to the
1451 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001452 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001453 PreviousDefaultArgLoc
1454 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001455 } else if (NewTemplateParm->hasDefaultArgument()) {
1456 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001457 PreviousDefaultArgLoc
1458 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001459 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001460 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001461 }
1462
Richard Smith1fde8ec2012-09-07 02:06:42 +00001463 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001464 // If a template parameter of a primary class template or alias template
1465 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001466 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001467 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1468 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001469 Diag((*NewParam)->getLocation(),
1470 diag::err_template_param_pack_must_be_last_template_parameter);
1471 Invalid = true;
1472 }
1473
Douglas Gregordba32632009-02-10 19:49:53 +00001474 if (RedundantDefaultArg) {
1475 // C++ [temp.param]p12:
1476 // A template-parameter shall not be given default arguments
1477 // by two different declarations in the same scope.
1478 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1479 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1480 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001481 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001482 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001483 // If a template-parameter of a class template has a default
1484 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001485 // have a default template-argument supplied or be a template parameter
1486 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001487 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001488 diag::err_template_param_default_arg_missing);
1489 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1490 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001491 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001492 }
1493
1494 // If we have an old template parameter list that we're merging
1495 // in, move on to the next parameter.
1496 if (OldParams)
1497 ++OldParam;
1498 }
1499
Douglas Gregor0693def2011-01-27 01:40:17 +00001500 // We were missing some default arguments at the end of the list, so remove
1501 // all of the default arguments.
1502 if (RemoveDefaultArguments) {
1503 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1504 NewParamEnd = NewParams->end();
1505 NewParam != NewParamEnd; ++NewParam) {
1506 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1507 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001508 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001509 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1510 NTTP->removeDefaultArgument();
1511 else
1512 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1513 }
1514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001515
Douglas Gregordba32632009-02-10 19:49:53 +00001516 return Invalid;
1517}
Douglas Gregord32e0282009-02-09 23:23:08 +00001518
John McCalla020a012010-10-20 05:44:58 +00001519namespace {
1520
1521/// A class which looks for a use of a certain level of template
1522/// parameter.
1523struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1524 typedef RecursiveASTVisitor<DependencyChecker> super;
1525
1526 unsigned Depth;
1527 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001528 SourceLocation MatchLoc;
1529
1530 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001531
1532 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1533 NamedDecl *ND = Params->getParam(0);
1534 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1535 Depth = PD->getDepth();
1536 } else if (NonTypeTemplateParmDecl *PD =
1537 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1538 Depth = PD->getDepth();
1539 } else {
1540 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1541 }
1542 }
1543
Richard Smith6056d5e2014-02-09 00:54:43 +00001544 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001545 if (ParmDepth >= Depth) {
1546 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001547 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001548 return true;
1549 }
1550 return false;
1551 }
1552
Richard Smith6056d5e2014-02-09 00:54:43 +00001553 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1554 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1555 }
1556
John McCalla020a012010-10-20 05:44:58 +00001557 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1558 return !Matches(T->getDepth());
1559 }
1560
1561 bool TraverseTemplateName(TemplateName N) {
1562 if (TemplateTemplateParmDecl *PD =
1563 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001564 if (Matches(PD->getDepth()))
1565 return false;
John McCalla020a012010-10-20 05:44:58 +00001566 return super::TraverseTemplateName(N);
1567 }
1568
1569 bool VisitDeclRefExpr(DeclRefExpr *E) {
1570 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001571 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1572 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001573 return false;
John McCalla020a012010-10-20 05:44:58 +00001574 return super::VisitDeclRefExpr(E);
1575 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001576
1577 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1578 return TraverseType(T->getReplacementType());
1579 }
1580
1581 bool
1582 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1583 return TraverseTemplateArgument(T->getArgumentPack());
1584 }
1585
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001586 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1587 return TraverseType(T->getInjectedSpecializationType());
1588 }
John McCalla020a012010-10-20 05:44:58 +00001589};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001590} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001591
Douglas Gregor972fe532011-05-10 18:27:06 +00001592/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001593/// list.
1594static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001595DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001596 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001597 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001598 return Checker.Match;
1599}
1600
Douglas Gregor972fe532011-05-10 18:27:06 +00001601// Find the source range corresponding to the named type in the given
1602// nested-name-specifier, if any.
1603static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1604 QualType T,
1605 const CXXScopeSpec &SS) {
1606 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1607 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1608 if (const Type *CurType = NNS->getAsType()) {
1609 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1610 return NNSLoc.getTypeLoc().getSourceRange();
1611 } else
1612 break;
1613
1614 NNSLoc = NNSLoc.getPrefix();
1615 }
1616
1617 return SourceRange();
1618}
1619
Mike Stump11289f42009-09-09 15:08:12 +00001620/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001621/// specifier, returning the template parameter list that applies to the
1622/// name.
1623///
1624/// \param DeclStartLoc the start of the declaration that has a scope
1625/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001626///
Douglas Gregor972fe532011-05-10 18:27:06 +00001627/// \param DeclLoc The location of the declaration itself.
1628///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001629/// \param SS the scope specifier that will be matched to the given template
1630/// parameter lists. This scope specifier precedes a qualified name that is
1631/// being declared.
1632///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001633/// \param TemplateId The template-id following the scope specifier, if there
1634/// is one. Used to check for a missing 'template<>'.
1635///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001636/// \param ParamLists the template parameter lists, from the outermost to the
1637/// innermost template parameter lists.
1638///
John McCalle820e5e2010-04-13 20:37:33 +00001639/// \param IsFriend Whether to apply the slightly different rules for
1640/// matching template parameters to scope specifiers in friend
1641/// declarations.
1642///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001643/// \param IsExplicitSpecialization will be set true if the entity being
1644/// declared is an explicit specialization, false otherwise.
1645///
Mike Stump11289f42009-09-09 15:08:12 +00001646/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001647/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001648/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001649/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001650/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001651/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001652TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1653 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001654 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001655 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1656 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001657 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001658 Invalid = false;
1659
1660 // The sequence of nested types to which we will match up the template
1661 // parameter lists. We first build this list by starting with the type named
1662 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001663 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001664 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001665 if (SS.getScopeRep()) {
1666 if (CXXRecordDecl *Record
1667 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1668 T = Context.getTypeDeclType(Record);
1669 else
1670 T = QualType(SS.getScopeRep()->getAsType(), 0);
1671 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001672
1673 // If we found an explicit specialization that prevents us from needing
1674 // 'template<>' headers, this will be set to the location of that
1675 // explicit specialization.
1676 SourceLocation ExplicitSpecLoc;
1677
1678 while (!T.isNull()) {
1679 NestedTypes.push_back(T);
1680
1681 // Retrieve the parent of a record type.
1682 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1683 // If this type is an explicit specialization, we're done.
1684 if (ClassTemplateSpecializationDecl *Spec
1685 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1686 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1687 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1688 ExplicitSpecLoc = Spec->getLocation();
1689 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001690 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001691 } else if (Record->getTemplateSpecializationKind()
1692 == TSK_ExplicitSpecialization) {
1693 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001694 break;
1695 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001696
1697 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1698 T = Context.getTypeDeclType(Parent);
1699 else
1700 T = QualType();
1701 continue;
1702 }
1703
1704 if (const TemplateSpecializationType *TST
1705 = T->getAs<TemplateSpecializationType>()) {
1706 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1707 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1708 T = Context.getTypeDeclType(Parent);
1709 else
1710 T = QualType();
1711 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001712 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001713 }
1714
1715 // Look one step prior in a dependent template specialization type.
1716 if (const DependentTemplateSpecializationType *DependentTST
1717 = T->getAs<DependentTemplateSpecializationType>()) {
1718 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1719 T = QualType(NNS->getAsType(), 0);
1720 else
1721 T = QualType();
1722 continue;
1723 }
1724
1725 // Look one step prior in a dependent name type.
1726 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1727 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1728 T = QualType(NNS->getAsType(), 0);
1729 else
1730 T = QualType();
1731 continue;
1732 }
1733
1734 // Retrieve the parent of an enumeration type.
1735 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1736 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1737 // check here.
1738 EnumDecl *Enum = EnumT->getDecl();
1739
1740 // Get to the parent type.
1741 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1742 T = Context.getTypeDeclType(Parent);
1743 else
1744 T = QualType();
1745 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001746 }
Mike Stump11289f42009-09-09 15:08:12 +00001747
Douglas Gregor972fe532011-05-10 18:27:06 +00001748 T = QualType();
1749 }
1750 // Reverse the nested types list, since we want to traverse from the outermost
1751 // to the innermost while checking template-parameter-lists.
1752 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001753
Douglas Gregor972fe532011-05-10 18:27:06 +00001754 // C++0x [temp.expl.spec]p17:
1755 // A member or a member template may be nested within many
1756 // enclosing class templates. In an explicit specialization for
1757 // such a member, the member declaration shall be preceded by a
1758 // template<> for each enclosing class template that is
1759 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001760 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001761
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001762 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001763 if (SawNonEmptyTemplateParameterList) {
1764 Diag(DeclLoc, diag::err_specialize_member_of_template)
1765 << !Recovery << Range;
1766 Invalid = true;
1767 IsExplicitSpecialization = false;
1768 return true;
1769 }
1770
1771 return false;
1772 };
1773
1774 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1775 // Check that we can have an explicit specialization here.
1776 if (CheckExplicitSpecialization(Range, true))
1777 return true;
1778
1779 // We don't have a template header, but we should.
1780 SourceLocation ExpectedTemplateLoc;
1781 if (!ParamLists.empty())
1782 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1783 else
1784 ExpectedTemplateLoc = DeclStartLoc;
1785
1786 Diag(DeclLoc, diag::err_template_spec_needs_header)
1787 << Range
1788 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1789 return false;
1790 };
1791
Douglas Gregor972fe532011-05-10 18:27:06 +00001792 unsigned ParamIdx = 0;
1793 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1794 ++TypeIdx) {
1795 T = NestedTypes[TypeIdx];
1796
1797 // Whether we expect a 'template<>' header.
1798 bool NeedEmptyTemplateHeader = false;
1799
1800 // Whether we expect a template header with parameters.
1801 bool NeedNonemptyTemplateHeader = false;
1802
1803 // For a dependent type, the set of template parameters that we
1804 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001805 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001806
Douglas Gregor373af9b2011-05-11 23:26:17 +00001807 // C++0x [temp.expl.spec]p15:
1808 // A member or a member template may be nested within many enclosing
1809 // class templates. In an explicit specialization for such a member, the
1810 // member declaration shall be preceded by a template<> for each
1811 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001812 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1813 if (ClassTemplatePartialSpecializationDecl *Partial
1814 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1815 ExpectedTemplateParams = Partial->getTemplateParameters();
1816 NeedNonemptyTemplateHeader = true;
1817 } else if (Record->isDependentType()) {
1818 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001819 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001820 ->getTemplateParameters();
1821 NeedNonemptyTemplateHeader = true;
1822 }
1823 } else if (ClassTemplateSpecializationDecl *Spec
1824 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1825 // C++0x [temp.expl.spec]p4:
1826 // Members of an explicitly specialized class template are defined
1827 // in the same manner as members of normal classes, and not using
1828 // the template<> syntax.
1829 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1830 NeedEmptyTemplateHeader = true;
1831 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001832 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001833 } else if (Record->getTemplateSpecializationKind()) {
1834 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001835 != TSK_ExplicitSpecialization &&
1836 TypeIdx == NumTypes - 1)
1837 IsExplicitSpecialization = true;
1838
1839 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001840 }
1841 } else if (const TemplateSpecializationType *TST
1842 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001843 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001844 ExpectedTemplateParams = Template->getTemplateParameters();
1845 NeedNonemptyTemplateHeader = true;
1846 }
1847 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1848 // FIXME: We actually could/should check the template arguments here
1849 // against the corresponding template parameter list.
1850 NeedNonemptyTemplateHeader = false;
1851 }
1852
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001853 // C++ [temp.expl.spec]p16:
1854 // In an explicit specialization declaration for a member of a class
1855 // template or a member template that ap- pears in namespace scope, the
1856 // member template and some of its enclosing class templates may remain
1857 // unspecialized, except that the declaration shall not explicitly
1858 // specialize a class member template if its en- closing class templates
1859 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001860 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001861 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001862 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1863 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001864 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001865 } else
1866 SawNonEmptyTemplateParameterList = true;
1867 }
1868
Douglas Gregor972fe532011-05-10 18:27:06 +00001869 if (NeedEmptyTemplateHeader) {
1870 // If we're on the last of the types, and we need a 'template<>' header
1871 // here, then it's an explicit specialization.
1872 if (TypeIdx == NumTypes - 1)
1873 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001874
1875 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001876 if (ParamLists[ParamIdx]->size() > 0) {
1877 // The header has template parameters when it shouldn't. Complain.
1878 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1879 diag::err_template_param_list_matches_nontemplate)
1880 << T
1881 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1882 ParamLists[ParamIdx]->getRAngleLoc())
1883 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1884 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001885 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001886 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001887
Douglas Gregor972fe532011-05-10 18:27:06 +00001888 // Consume this template header.
1889 ++ParamIdx;
1890 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001891 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001892
1893 if (!IsFriend)
1894 if (DiagnoseMissingExplicitSpecialization(
1895 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001896 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001897
Douglas Gregor972fe532011-05-10 18:27:06 +00001898 continue;
1899 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001900
Douglas Gregor972fe532011-05-10 18:27:06 +00001901 if (NeedNonemptyTemplateHeader) {
1902 // In friend declarations we can have template-ids which don't
1903 // depend on the corresponding template parameter lists. But
1904 // assume that empty parameter lists are supposed to match this
1905 // template-id.
1906 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001907 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001908 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001909 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001910 else
1911 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001912 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001913
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001914 if (ParamIdx < ParamLists.size()) {
1915 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001916 if (ExpectedTemplateParams &&
1917 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1918 ExpectedTemplateParams,
1919 true, TPL_TemplateMatch))
1920 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001921
Douglas Gregor972fe532011-05-10 18:27:06 +00001922 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001923 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001924 TPC_ClassTemplateMember))
1925 Invalid = true;
1926
1927 ++ParamIdx;
1928 continue;
1929 }
1930
1931 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1932 << T
1933 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1934 Invalid = true;
1935 continue;
1936 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001937 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001938
Douglas Gregord8d297c2009-07-21 23:53:31 +00001939 // If there were at least as many template-ids as there were template
1940 // parameter lists, then there are no template parameter lists remaining for
1941 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001942 if (ParamIdx >= ParamLists.size()) {
1943 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001944 // We don't have a template header for the declaration itself, but we
1945 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001946 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001947 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1948 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001949
1950 // Fabricate an empty template parameter list for the invented header.
1951 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00001952 SourceLocation(), None,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001953 SourceLocation());
1954 }
1955
Craig Topperc3ec1492014-05-26 06:22:03 +00001956 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001957 }
Mike Stump11289f42009-09-09 15:08:12 +00001958
Douglas Gregord8d297c2009-07-21 23:53:31 +00001959 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001960 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001961 bool HasAnyExplicitSpecHeader = false;
1962 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001963 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001964 if (ParamLists[I]->size() == 0)
1965 HasAnyExplicitSpecHeader = true;
1966 else
1967 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001968 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001969
Douglas Gregor972fe532011-05-10 18:27:06 +00001970 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001971 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1972 : diag::err_template_spec_extra_headers)
1973 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1974 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001975
1976 // If there was a specialization somewhere, such that 'template<>' is
1977 // not required, and there were any 'template<>' headers, note where the
1978 // specialization occurred.
1979 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1980 Diag(ExplicitSpecLoc,
1981 diag::note_explicit_template_spec_does_not_need_header)
1982 << NestedTypes.back();
1983
1984 // We have a template parameter list with no corresponding scope, which
1985 // means that the resulting template declaration can't be instantiated
1986 // properly (we'll end up with dependent nodes when we shouldn't).
1987 if (!AllExplicitSpecHeaders)
1988 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001989 }
Mike Stump11289f42009-09-09 15:08:12 +00001990
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001991 // C++ [temp.expl.spec]p16:
1992 // In an explicit specialization declaration for a member of a class
1993 // template or a member template that ap- pears in namespace scope, the
1994 // member template and some of its enclosing class templates may remain
1995 // unspecialized, except that the declaration shall not explicitly
1996 // specialize a class member template if its en- closing class templates
1997 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00001998 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001999 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2000 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002001 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002002
Douglas Gregord8d297c2009-07-21 23:53:31 +00002003 // Return the last template parameter list, which corresponds to the
2004 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002005 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002006}
2007
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002008void Sema::NoteAllFoundTemplates(TemplateName Name) {
2009 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2010 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002011 << (isa<FunctionTemplateDecl>(Template)
2012 ? 0
2013 : isa<ClassTemplateDecl>(Template)
2014 ? 1
2015 : isa<VarTemplateDecl>(Template)
2016 ? 2
2017 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2018 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002019 return;
2020 }
2021
2022 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2023 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2024 IEnd = OST->end();
2025 I != IEnd; ++I)
2026 Diag((*I)->getLocation(), diag::note_template_declared_here)
2027 << 0 << (*I)->getDeclName();
2028
2029 return;
2030 }
2031}
2032
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002033static QualType
2034checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2035 const SmallVectorImpl<TemplateArgument> &Converted,
2036 SourceLocation TemplateLoc,
2037 TemplateArgumentListInfo &TemplateArgs) {
2038 ASTContext &Context = SemaRef.getASTContext();
2039 switch (BTD->getBuiltinTemplateKind()) {
2040 case BTK__make_integer_seq:
2041 // Specializations of __make_integer_seq<S, T, N> are treated like
2042 // S<T, 0, ..., N-1>.
2043
2044 // C++14 [inteseq.intseq]p1:
2045 // T shall be an integer type.
2046 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2047 SemaRef.Diag(TemplateArgs[1].getLocation(),
2048 diag::err_integer_sequence_integral_element_type);
2049 return QualType();
2050 }
2051
2052 // C++14 [inteseq.make]p1:
2053 // If N is negative the program is ill-formed.
2054 TemplateArgument NumArgsArg = Converted[2];
2055 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2056 if (NumArgs < 0) {
2057 SemaRef.Diag(TemplateArgs[2].getLocation(),
2058 diag::err_integer_sequence_negative_length);
2059 return QualType();
2060 }
2061
2062 QualType ArgTy = NumArgsArg.getIntegralType();
2063 TemplateArgumentListInfo SyntheticTemplateArgs;
2064 // The type argument gets reused as the first template argument in the
2065 // synthetic template argument list.
2066 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2067 // Expand N into 0 ... N-1.
2068 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2069 I < NumArgs; ++I) {
2070 TemplateArgument TA(Context, I, ArgTy);
2071 Expr *E = SemaRef.BuildExpressionFromIntegralTemplateArgument(
2072 TA, TemplateArgs[2].getLocation())
2073 .getAs<Expr>();
2074 SyntheticTemplateArgs.addArgument(
2075 TemplateArgumentLoc(TemplateArgument(E), E));
2076 }
2077 // The first template argument will be reused as the template decl that
2078 // our synthetic template arguments will be applied to.
2079 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2080 TemplateLoc, SyntheticTemplateArgs);
2081 }
2082 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2083}
2084
Douglas Gregordc572a32009-03-30 22:58:21 +00002085QualType Sema::CheckTemplateIdType(TemplateName Name,
2086 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002087 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002088 DependentTemplateName *DTN
2089 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002090 if (DTN && DTN->isIdentifier())
2091 // When building a template-id where the template-name is dependent,
2092 // assume the template is a type template. Either our assumption is
2093 // correct, or the code is ill-formed and will be diagnosed when the
2094 // dependent name is substituted.
2095 return Context.getDependentTemplateSpecializationType(ETK_None,
2096 DTN->getQualifier(),
2097 DTN->getIdentifier(),
2098 TemplateArgs);
2099
Douglas Gregordc572a32009-03-30 22:58:21 +00002100 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002101 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2102 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002103 // We might have a substituted template template parameter pack. If so,
2104 // build a template specialization type for it.
2105 if (Name.getAsSubstTemplateTemplateParmPack())
2106 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002107
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002108 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2109 << Name;
2110 NoteAllFoundTemplates(Name);
2111 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002112 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002113
Douglas Gregorc40290e2009-03-09 23:48:35 +00002114 // Check that the template argument list is well-formed for this
2115 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002116 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002117 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002118 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002119 return QualType();
2120
Douglas Gregorc40290e2009-03-09 23:48:35 +00002121 QualType CanonType;
2122
Douglas Gregor678d76c2011-07-01 01:22:09 +00002123 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002124 if (TypeAliasTemplateDecl *AliasTemplate =
2125 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002126 // Find the canonical type for this type alias template specialization.
2127 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2128 if (Pattern->isInvalidDecl())
2129 return QualType();
2130
2131 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2132 Converted.data(), Converted.size());
2133
2134 // Only substitute for the innermost template argument list.
2135 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002136 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002137 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2138 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002139 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002140
Richard Smith802c4b72012-08-23 06:16:52 +00002141 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002142 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002143 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002144 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002145
Richard Smith3f1b5d02011-05-05 21:57:07 +00002146 CanonType = SubstType(Pattern->getUnderlyingType(),
2147 TemplateArgLists, AliasTemplate->getLocation(),
2148 AliasTemplate->getDeclName());
2149 if (CanonType.isNull())
2150 return QualType();
2151 } else if (Name.isDependent() ||
2152 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002153 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002154 // This class template specialization is a dependent
2155 // type. Therefore, its canonical type is another class template
2156 // specialization type that contains all of the converted
2157 // arguments in canonical form. This ensures that, e.g., A<T> and
2158 // A<T, T> have identical types when A is declared as:
2159 //
2160 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002161 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002162 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002163 Converted.data(),
2164 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002165
Douglas Gregora8e02e72009-07-28 23:00:59 +00002166 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002167 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002168 // In the future, we need to teach getTemplateSpecializationType to only
2169 // build the canonical type and return that to us.
2170 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002171
2172 // This might work out to be a current instantiation, in which
2173 // case the canonical type needs to be the InjectedClassNameType.
2174 //
2175 // TODO: in theory this could be a simple hashtable lookup; most
2176 // changes to CurContext don't change the set of current
2177 // instantiations.
2178 if (isa<ClassTemplateDecl>(Template)) {
2179 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2180 // If we get out to a namespace, we're done.
2181 if (Ctx->isFileContext()) break;
2182
2183 // If this isn't a record, keep looking.
2184 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2185 if (!Record) continue;
2186
2187 // Look for one of the two cases with InjectedClassNameTypes
2188 // and check whether it's the same template.
2189 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2190 !Record->getDescribedClassTemplate())
2191 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002192
John McCall2408e322010-04-27 00:57:59 +00002193 // Fetch the injected class name type and check whether its
2194 // injected type is equal to the type we just built.
2195 QualType ICNT = Context.getTypeDeclType(Record);
2196 QualType Injected = cast<InjectedClassNameType>(ICNT)
2197 ->getInjectedSpecializationType();
2198
2199 if (CanonType != Injected->getCanonicalTypeInternal())
2200 continue;
2201
2202 // If so, the canonical type of this TST is the injected
2203 // class name type of the record we just found.
2204 assert(ICNT.isCanonical());
2205 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002206 break;
2207 }
2208 }
Mike Stump11289f42009-09-09 15:08:12 +00002209 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002210 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002211 // Find the class template specialization declaration that
2212 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002213 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002214 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002215 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002216 if (!Decl) {
2217 // This is the first time we have referenced this class template
2218 // specialization. Create the canonical declaration and add it to
2219 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002220 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002221 ClassTemplate->getTemplatedDecl()->getTagKind(),
2222 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002223 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002224 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002225 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002226 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002227 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002228 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002229 if (ClassTemplate->isOutOfLine())
2230 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002231 }
2232
Chandler Carruth2acfb222013-09-27 22:14:40 +00002233 // Diagnose uses of this specialization.
2234 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2235
Douglas Gregorc40290e2009-03-09 23:48:35 +00002236 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002237 assert(isa<RecordType>(CanonType) &&
2238 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002239 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2240 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2241 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002242 }
Mike Stump11289f42009-09-09 15:08:12 +00002243
Douglas Gregorc40290e2009-03-09 23:48:35 +00002244 // Build the fully-sugared type for this class template
2245 // specialization, which refers back to the class template
2246 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002247 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002248}
2249
John McCallfaf5fb42010-08-26 23:41:50 +00002250TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002251Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002252 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002253 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002254 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002255 SourceLocation RAngleLoc,
2256 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002257 if (SS.isInvalid())
2258 return true;
2259
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002260 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002261
Douglas Gregorc40290e2009-03-09 23:48:35 +00002262 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002263 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002264 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002265
Douglas Gregor5a064722011-02-28 17:23:35 +00002266 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002267 QualType T
2268 = Context.getDependentTemplateSpecializationType(ETK_None,
2269 DTN->getQualifier(),
2270 DTN->getIdentifier(),
2271 TemplateArgs);
2272 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002273 TypeLocBuilder TLB;
2274 DependentTemplateSpecializationTypeLoc SpecTL
2275 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002276 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2277 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002278 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002279 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002280 SpecTL.setLAngleLoc(LAngleLoc);
2281 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002282 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2283 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2284 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2285 }
2286
John McCall6b51f282009-11-23 01:53:49 +00002287 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002288
2289 if (Result.isNull())
2290 return true;
2291
Douglas Gregore7c20652011-03-02 00:47:37 +00002292 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002293 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002294 TemplateSpecializationTypeLoc SpecTL
2295 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002296 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002297 SpecTL.setTemplateNameLoc(TemplateLoc);
2298 SpecTL.setLAngleLoc(LAngleLoc);
2299 SpecTL.setRAngleLoc(RAngleLoc);
2300 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2301 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002302
Abramo Bagnara4244b432012-01-27 08:46:19 +00002303 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2304 // constructor or destructor name (in such a case, the scope specifier
2305 // will be attached to the enclosing Decl or Expr node).
2306 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002307 // Create an elaborated-type-specifier containing the nested-name-specifier.
2308 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2309 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002310 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002311 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2312 }
2313
2314 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002315}
John McCall06f6fe8d2009-09-04 01:14:41 +00002316
Douglas Gregore7c20652011-03-02 00:47:37 +00002317TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002318 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002319 SourceLocation TagLoc,
2320 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002321 SourceLocation TemplateKWLoc,
2322 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002323 SourceLocation TemplateLoc,
2324 SourceLocation LAngleLoc,
2325 ASTTemplateArgsPtr TemplateArgsIn,
2326 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002327 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002328
2329 // Translate the parser's template argument list in our AST format.
2330 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2331 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2332
2333 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002334 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002335 ElaboratedTypeKeyword Keyword
2336 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002337
Douglas Gregore7c20652011-03-02 00:47:37 +00002338 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2339 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2340 DTN->getQualifier(),
2341 DTN->getIdentifier(),
2342 TemplateArgs);
2343
2344 // Build type-source information.
2345 TypeLocBuilder TLB;
2346 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002347 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2348 SpecTL.setElaboratedKeywordLoc(TagLoc);
2349 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002350 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002351 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002352 SpecTL.setLAngleLoc(LAngleLoc);
2353 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002354 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2355 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2356 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2357 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002358
2359 if (TypeAliasTemplateDecl *TAT =
2360 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2361 // C++0x [dcl.type.elab]p2:
2362 // If the identifier resolves to a typedef-name or the simple-template-id
2363 // resolves to an alias template specialization, the
2364 // elaborated-type-specifier is ill-formed.
2365 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2366 Diag(TAT->getLocation(), diag::note_declared_at);
2367 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002368
2369 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2370 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002371 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002372
2373 // Check the tag kind
2374 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002375 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002376
John McCalld8fe9af2009-09-08 17:47:29 +00002377 IdentifierInfo *Id = D->getIdentifier();
2378 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002379
Richard Trieucaa33d32011-06-10 03:11:26 +00002380 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002381 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002382 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002383 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002384 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002385 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002386 }
2387 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002388
Douglas Gregore7c20652011-03-02 00:47:37 +00002389 // Provide source-location information for the template specialization.
2390 TypeLocBuilder TLB;
2391 TemplateSpecializationTypeLoc SpecTL
2392 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002393 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002394 SpecTL.setTemplateNameLoc(TemplateLoc);
2395 SpecTL.setLAngleLoc(LAngleLoc);
2396 SpecTL.setRAngleLoc(RAngleLoc);
2397 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2398 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002399
Douglas Gregore7c20652011-03-02 00:47:37 +00002400 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002401 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002402 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2403 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002404 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002405 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2406 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002407}
2408
Larisse Voufo39a1e502013-08-06 01:03:05 +00002409static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002410 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2411 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002412
2413static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2414 NamedDecl *PrevDecl,
2415 SourceLocation Loc,
2416 bool IsPartialSpecialization);
2417
2418static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002419
Richard Smith300e0c32013-09-24 04:49:23 +00002420static bool isTemplateArgumentTemplateParameter(
2421 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2422 switch (Arg.getKind()) {
2423 case TemplateArgument::Null:
2424 case TemplateArgument::NullPtr:
2425 case TemplateArgument::Integral:
2426 case TemplateArgument::Declaration:
2427 case TemplateArgument::Pack:
2428 case TemplateArgument::TemplateExpansion:
2429 return false;
2430
2431 case TemplateArgument::Type: {
2432 QualType Type = Arg.getAsType();
2433 const TemplateTypeParmType *TPT =
2434 Arg.getAsType()->getAs<TemplateTypeParmType>();
2435 return TPT && !Type.hasQualifiers() &&
2436 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2437 }
2438
2439 case TemplateArgument::Expression: {
2440 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2441 if (!DRE || !DRE->getDecl())
2442 return false;
2443 const NonTypeTemplateParmDecl *NTTP =
2444 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2445 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2446 }
2447
2448 case TemplateArgument::Template:
2449 const TemplateTemplateParmDecl *TTP =
2450 dyn_cast_or_null<TemplateTemplateParmDecl>(
2451 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2452 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2453 }
2454 llvm_unreachable("unexpected kind of template argument");
2455}
2456
2457static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2458 ArrayRef<TemplateArgument> Args) {
2459 if (Params->size() != Args.size())
2460 return false;
2461
2462 unsigned Depth = Params->getDepth();
2463
2464 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2465 TemplateArgument Arg = Args[I];
2466
2467 // If the parameter is a pack expansion, the argument must be a pack
2468 // whose only element is a pack expansion.
2469 if (Params->getParam(I)->isParameterPack()) {
2470 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2471 !Arg.pack_begin()->isPackExpansion())
2472 return false;
2473 Arg = Arg.pack_begin()->getPackExpansionPattern();
2474 }
2475
2476 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2477 return false;
2478 }
2479
2480 return true;
2481}
2482
Richard Smith4b55a9c2014-04-17 03:29:33 +00002483/// Convert the parser's template argument list representation into our form.
2484static TemplateArgumentListInfo
2485makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2486 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2487 TemplateId.RAngleLoc);
2488 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2489 TemplateId.NumArgs);
2490 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2491 return TemplateArgs;
2492}
2493
Larisse Voufo39a1e502013-08-06 01:03:05 +00002494DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002495 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002496 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002497 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002498 // D must be variable template id.
2499 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2500 "Variable template specialization is declared with a template it.");
2501
2502 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002503 TemplateArgumentListInfo TemplateArgs =
2504 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002505 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2506 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2507 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002508
Richard Smithbeef3452014-01-16 23:39:20 +00002509 TemplateName Name = TemplateId->Template.get();
2510
2511 // The template-id must name a variable template.
2512 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002513 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2514 if (!VarTemplate) {
2515 NamedDecl *FnTemplate;
2516 if (auto *OTS = Name.getAsOverloadedTemplate())
2517 FnTemplate = *OTS->begin();
2518 else
2519 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2520 if (FnTemplate)
2521 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2522 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002523 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2524 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002525 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002526
2527 // Check for unexpanded parameter packs in any of the template arguments.
2528 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2529 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2530 UPPC_PartialSpecialization))
2531 return true;
2532
2533 // Check that the template argument list is well-formed for this
2534 // template.
2535 SmallVector<TemplateArgument, 4> Converted;
2536 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2537 false, Converted))
2538 return true;
2539
Larisse Voufo39a1e502013-08-06 01:03:05 +00002540 // Find the variable template (partial) specialization declaration that
2541 // corresponds to these arguments.
2542 if (IsPartialSpecialization) {
2543 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002544 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2545 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002546 return true;
2547
2548 bool InstantiationDependent;
2549 if (!Name.isDependent() &&
2550 !TemplateSpecializationType::anyDependentTemplateArguments(
2551 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2552 InstantiationDependent)) {
2553 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2554 << VarTemplate->getDeclName();
2555 IsPartialSpecialization = false;
2556 }
Richard Smith300e0c32013-09-24 04:49:23 +00002557
2558 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2559 Converted)) {
2560 // C++ [temp.class.spec]p9b3:
2561 //
2562 // -- The argument list of the specialization shall not be identical
2563 // to the implicit argument list of the primary template.
2564 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2565 << /*variable template*/ 1
2566 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2567 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2568 // FIXME: Recover from this by treating the declaration as a redeclaration
2569 // of the primary template.
2570 return true;
2571 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002572 }
2573
Craig Topperc3ec1492014-05-26 06:22:03 +00002574 void *InsertPos = nullptr;
2575 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002576
2577 if (IsPartialSpecialization)
2578 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002579 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002580 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002581 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002582
Craig Topperc3ec1492014-05-26 06:22:03 +00002583 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002584
2585 // Check whether we can declare a variable template specialization in
2586 // the current scope.
2587 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2588 TemplateNameLoc,
2589 IsPartialSpecialization))
2590 return true;
2591
2592 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2593 // Since the only prior variable template specialization with these
2594 // arguments was referenced but not declared, reuse that
2595 // declaration node as our own, updating its source location and
2596 // the list of outer template parameters to reflect our new declaration.
2597 Specialization = PrevDecl;
2598 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002599 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002600 } else if (IsPartialSpecialization) {
2601 // Create a new class template partial specialization declaration node.
2602 VarTemplatePartialSpecializationDecl *PrevPartial =
2603 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002604 VarTemplatePartialSpecializationDecl *Partial =
2605 VarTemplatePartialSpecializationDecl::Create(
2606 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2607 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002608 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002609
2610 if (!PrevPartial)
2611 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2612 Specialization = Partial;
2613
2614 // If we are providing an explicit specialization of a member variable
2615 // template specialization, make a note of that.
2616 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002617 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002618
2619 // Check that all of the template parameters of the variable template
2620 // partial specialization are deducible from the template
2621 // arguments. If not, this variable template partial specialization
2622 // will never be used.
2623 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2624 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2625 TemplateParams->getDepth(), DeducibleParams);
2626
2627 if (!DeducibleParams.all()) {
2628 unsigned NumNonDeducible =
2629 DeducibleParams.size() - DeducibleParams.count();
2630 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002631 << /*variable template*/ 1 << (NumNonDeducible > 1)
2632 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002633 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2634 if (!DeducibleParams[I]) {
2635 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2636 if (Param->getDeclName())
2637 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2638 << Param->getDeclName();
2639 else
2640 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002641 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002642 }
2643 }
2644 }
2645 } else {
2646 // Create a new class template specialization declaration node for
2647 // this explicit specialization or friend declaration.
2648 Specialization = VarTemplateSpecializationDecl::Create(
2649 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2650 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2651 Specialization->setTemplateArgsInfo(TemplateArgs);
2652
2653 if (!PrevDecl)
2654 VarTemplate->AddSpecialization(Specialization, InsertPos);
2655 }
2656
2657 // C++ [temp.expl.spec]p6:
2658 // If a template, a member template or the member of a class template is
2659 // explicitly specialized then that specialization shall be declared
2660 // before the first use of that specialization that would cause an implicit
2661 // instantiation to take place, in every translation unit in which such a
2662 // use occurs; no diagnostic is required.
2663 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2664 bool Okay = false;
2665 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2666 // Is there any previous explicit specialization declaration?
2667 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2668 Okay = true;
2669 break;
2670 }
2671 }
2672
2673 if (!Okay) {
2674 SourceRange Range(TemplateNameLoc, RAngleLoc);
2675 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2676 << Name << Range;
2677
2678 Diag(PrevDecl->getPointOfInstantiation(),
2679 diag::note_instantiation_required_here)
2680 << (PrevDecl->getTemplateSpecializationKind() !=
2681 TSK_ImplicitInstantiation);
2682 return true;
2683 }
2684 }
2685
2686 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2687 Specialization->setLexicalDeclContext(CurContext);
2688
2689 // Add the specialization into its lexical context, so that it can
2690 // be seen when iterating through the list of declarations in that
2691 // context. However, specializations are not found by name lookup.
2692 CurContext->addDecl(Specialization);
2693
2694 // Note that this is an explicit specialization.
2695 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2696
2697 if (PrevDecl) {
2698 // Check that this isn't a redefinition of this specialization,
2699 // merging with previous declarations.
2700 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2701 ForRedeclaration);
2702 PrevSpec.addDecl(PrevDecl);
2703 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002704 } else if (Specialization->isStaticDataMember() &&
2705 Specialization->isOutOfLine()) {
2706 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002707 }
2708
2709 // Link instantiations of static data members back to the template from
2710 // which they were instantiated.
2711 if (Specialization->isStaticDataMember())
2712 Specialization->setInstantiationOfStaticDataMember(
2713 VarTemplate->getTemplatedDecl(),
2714 Specialization->getSpecializationKind());
2715
2716 return Specialization;
2717}
2718
2719namespace {
2720/// \brief A partial specialization whose template arguments have matched
2721/// a given template-id.
2722struct PartialSpecMatchResult {
2723 VarTemplatePartialSpecializationDecl *Partial;
2724 TemplateArgumentList *Args;
2725};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002726} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00002727
2728DeclResult
2729Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2730 SourceLocation TemplateNameLoc,
2731 const TemplateArgumentListInfo &TemplateArgs) {
2732 assert(Template && "A variable template id without template?");
2733
2734 // Check that the template argument list is well-formed for this template.
2735 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002736 if (CheckTemplateArgumentList(
2737 Template, TemplateNameLoc,
2738 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002739 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002740 return true;
2741
2742 // Find the variable template specialization declaration that
2743 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002744 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002745 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00002746 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002747 // If we already have a variable template specialization, return it.
2748 return Spec;
2749
2750 // This is the first time we have referenced this variable template
2751 // specialization. Create the canonical declaration and add it to
2752 // the set of specializations, based on the closest partial specialization
2753 // that it represents. That is,
2754 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2755 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2756 Converted.data(), Converted.size());
2757 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2758 bool AmbiguousPartialSpec = false;
2759 typedef PartialSpecMatchResult MatchResult;
2760 SmallVector<MatchResult, 4> Matched;
2761 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002762 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2763 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002764
2765 // 1. Attempt to find the closest partial specialization that this
2766 // specializes, if any.
2767 // If any of the template arguments is dependent, then this is probably
2768 // a placeholder for an incomplete declarative context; which must be
2769 // complete by instantiation time. Thus, do not search through the partial
2770 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002771 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2772 // Perhaps better after unification of DeduceTemplateArguments() and
2773 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002774 bool InstantiationDependent = false;
2775 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2776 TemplateArgs, InstantiationDependent)) {
2777
2778 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2779 Template->getPartialSpecializations(PartialSpecs);
2780
2781 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2782 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2783 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2784
2785 if (TemplateDeductionResult Result =
2786 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2787 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002788 // TODO: Actually use the failed-deduction info?
Larisse Voufo39a1e502013-08-06 01:03:05 +00002789 FailedCandidates.addCandidate()
2790 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2791 (void)Result;
2792 } else {
2793 Matched.push_back(PartialSpecMatchResult());
2794 Matched.back().Partial = Partial;
2795 Matched.back().Args = Info.take();
2796 }
2797 }
2798
Larisse Voufo39a1e502013-08-06 01:03:05 +00002799 if (Matched.size() >= 1) {
2800 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2801 if (Matched.size() == 1) {
2802 // -- If exactly one matching specialization is found, the
2803 // instantiation is generated from that specialization.
2804 // We don't need to do anything for this.
2805 } else {
2806 // -- If more than one matching specialization is found, the
2807 // partial order rules (14.5.4.2) are used to determine
2808 // whether one of the specializations is more specialized
2809 // than the others. If none of the specializations is more
2810 // specialized than all of the other matching
2811 // specializations, then the use of the variable template is
2812 // ambiguous and the program is ill-formed.
2813 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2814 PEnd = Matched.end();
2815 P != PEnd; ++P) {
2816 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2817 PointOfInstantiation) ==
2818 P->Partial)
2819 Best = P;
2820 }
2821
2822 // Determine if the best partial specialization is more specialized than
2823 // the others.
2824 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2825 PEnd = Matched.end();
2826 P != PEnd; ++P) {
2827 if (P != Best && getMoreSpecializedPartialSpecialization(
2828 P->Partial, Best->Partial,
2829 PointOfInstantiation) != Best->Partial) {
2830 AmbiguousPartialSpec = true;
2831 break;
2832 }
2833 }
2834 }
2835
2836 // Instantiate using the best variable template partial specialization.
2837 InstantiationPattern = Best->Partial;
2838 InstantiationArgs = Best->Args;
2839 } else {
2840 // -- If no match is found, the instantiation is generated
2841 // from the primary template.
2842 // InstantiationPattern = Template->getTemplatedDecl();
2843 }
2844 }
2845
Larisse Voufo39a1e502013-08-06 01:03:05 +00002846 // 2. Create the canonical declaration.
2847 // Note that we do not instantiate the variable just yet, since
2848 // instantiation is handled in DoMarkVarDeclReferenced().
2849 // FIXME: LateAttrs et al.?
2850 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2851 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2852 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2853 if (!Decl)
2854 return true;
2855
2856 if (AmbiguousPartialSpec) {
2857 // Partial ordering did not produce a clear winner. Complain.
2858 Decl->setInvalidDecl();
2859 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2860 << Decl;
2861
2862 // Print the matching partial specializations.
2863 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2864 PEnd = Matched.end();
2865 P != PEnd; ++P)
2866 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2867 << getTemplateArgumentBindingsText(
2868 P->Partial->getTemplateParameters(), *P->Args);
2869 return true;
2870 }
2871
2872 if (VarTemplatePartialSpecializationDecl *D =
2873 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2874 Decl->setInstantiationOf(D, InstantiationArgs);
2875
2876 assert(Decl && "No variable template specialization?");
2877 return Decl;
2878}
2879
2880ExprResult
2881Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2882 const DeclarationNameInfo &NameInfo,
2883 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2884 const TemplateArgumentListInfo *TemplateArgs) {
2885
2886 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2887 *TemplateArgs);
2888 if (Decl.isInvalid())
2889 return ExprError();
2890
2891 VarDecl *Var = cast<VarDecl>(Decl.get());
2892 if (!Var->getTemplateSpecializationKind())
2893 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2894 NameInfo.getLoc());
2895
2896 // Build an ordinary singleton decl ref.
2897 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002898 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002899}
2900
John McCalldadc5752010-08-24 06:29:42 +00002901ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002902 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002903 LookupResult &R,
2904 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002905 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002906 // FIXME: Can we do any checking at this point? I guess we could check the
2907 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002908 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002909 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002910 // foo<int> could identify a single function unambiguously
2911 // This approach does NOT work, since f<int>(1);
2912 // gets resolved prior to resorting to overload resolution
2913 // i.e., template<class T> void f(double);
2914 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002915
2916 // These should be filtered out by our callers.
2917 assert(!R.empty() && "empty lookup results when building templateid");
2918 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2919
Larisse Voufo39a1e502013-08-06 01:03:05 +00002920 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002921 bool InstantiationDependent;
2922 if (R.getAsSingle<VarTemplateDecl>() &&
2923 !TemplateSpecializationType::anyDependentTemplateArguments(
2924 *TemplateArgs, InstantiationDependent)) {
2925 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2926 R.getAsSingle<VarTemplateDecl>(),
2927 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002928 }
2929
John McCall58cc69d2010-01-27 01:50:18 +00002930 // We don't want lookup warnings at this point.
2931 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002932
John McCalle66edc12009-11-24 19:00:30 +00002933 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002934 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002935 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002936 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002937 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002938 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002939 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002940
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002941 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00002942}
2943
John McCalle66edc12009-11-24 19:00:30 +00002944// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002945ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002946Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002947 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002948 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002949 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002950
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002951 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002952 DeclContext *DC;
2953 if (!(DC = computeDeclContext(SS, false)) ||
2954 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002955 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00002956 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002957
Douglas Gregor786123d2010-05-21 23:18:07 +00002958 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002959 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00002960 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002961 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002962
John McCalle66edc12009-11-24 19:00:30 +00002963 if (R.isAmbiguous())
2964 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002965
John McCalle66edc12009-11-24 19:00:30 +00002966 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002967 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2968 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002969 return ExprError();
2970 }
2971
2972 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002973 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00002974 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00002975 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002976 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2977 return ExprError();
2978 }
2979
Abramo Bagnara7945c982012-01-27 09:46:47 +00002980 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00002981}
2982
Douglas Gregorb67535d2009-03-31 00:43:58 +00002983/// \brief Form a dependent template name.
2984///
2985/// This action forms a dependent template name given the template
2986/// name and its (presumably dependent) scope specifier. For
2987/// example, given "MetaFun::template apply", the scope specifier \p
2988/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2989/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002990TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00002991 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002992 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00002993 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00002994 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00002995 bool EnteringContext,
2996 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00002997 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2998 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002999 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003000 diag::warn_cxx98_compat_template_outside_of_template :
3001 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003002 << FixItHint::CreateRemoval(TemplateKWLoc);
3003
Craig Topperc3ec1492014-05-26 06:22:03 +00003004 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003005 if (SS.isSet())
3006 LookupCtx = computeDeclContext(SS, EnteringContext);
3007 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003008 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003009 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003010 // C++0x [temp.names]p5:
3011 // If a name prefixed by the keyword template is not the name of
3012 // a template, the program is ill-formed. [Note: the keyword
3013 // template may not be applied to non-template members of class
3014 // templates. -end note ] [ Note: as is the case with the
3015 // typename prefix, the template prefix is allowed in cases
3016 // where it is not strictly necessary; i.e., when the
3017 // nested-name-specifier or the expression on the left of the ->
3018 // or . is not dependent on a template-parameter, or the use
3019 // does not appear in the scope of a template. -end note]
3020 //
3021 // Note: C++03 was more strict here, because it banned the use of
3022 // the "template" keyword prior to a template-name that was not a
3023 // dependent name. C++ DR468 relaxed this requirement (the
3024 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003025 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003026 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003027 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003028 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003029 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003030 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3031 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003032 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3033 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003034 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003035 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003036 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003037 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003038 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003039 << Name.getSourceRange()
3040 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003041 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003042 } else {
3043 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003044 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003045 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003046 }
3047
Aaron Ballman4a979672014-01-03 13:56:08 +00003048 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003049
Douglas Gregor3cf81312009-11-03 23:16:33 +00003050 switch (Name.getKind()) {
3051 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003052 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003053 Name.Identifier));
3054 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003055
Douglas Gregor71395fa2009-11-04 00:56:37 +00003056 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003057 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003058 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003059 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003060
3061 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003062 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003063
Douglas Gregor3cf81312009-11-03 23:16:33 +00003064 default:
3065 break;
3066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003067
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003068 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003069 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003070 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003071 << Name.getSourceRange()
3072 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003073 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003074}
3075
Mike Stump11289f42009-09-09 15:08:12 +00003076bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003077 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003078 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003079 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003080 QualType ArgType;
3081 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003082
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003083 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003084 switch(Arg.getKind()) {
3085 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003086 // C++ [temp.arg.type]p1:
3087 // A template-argument for a template-parameter which is a
3088 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003089 ArgType = Arg.getAsType();
3090 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003091 break;
3092 case TemplateArgument::Template: {
3093 // We have a template type parameter but the template argument
3094 // is a template without any arguments.
3095 SourceRange SR = AL.getSourceRange();
3096 TemplateName Name = Arg.getAsTemplate();
3097 Diag(SR.getBegin(), diag::err_template_missing_args)
3098 << Name << SR;
3099 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3100 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003101
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003102 return true;
3103 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003104 case TemplateArgument::Expression: {
3105 // We have a template type parameter but the template argument is an
3106 // expression; see if maybe it is missing the "typename" keyword.
3107 CXXScopeSpec SS;
3108 DeclarationNameInfo NameInfo;
3109
3110 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3111 SS.Adopt(ArgExpr->getQualifierLoc());
3112 NameInfo = ArgExpr->getNameInfo();
3113 } else if (DependentScopeDeclRefExpr *ArgExpr =
3114 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3115 SS.Adopt(ArgExpr->getQualifierLoc());
3116 NameInfo = ArgExpr->getNameInfo();
3117 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3118 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003119 if (ArgExpr->isImplicitAccess()) {
3120 SS.Adopt(ArgExpr->getQualifierLoc());
3121 NameInfo = ArgExpr->getMemberNameInfo();
3122 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003123 }
3124
Reid Kleckner377c1592014-06-10 23:29:48 +00003125 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003126 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3127 LookupParsedName(Result, CurScope, &SS);
3128
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003129 if (Result.getAsSingle<TypeDecl>() ||
3130 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003131 LookupResult::NotFoundInCurrentInstantiation) {
3132 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003133 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003134 Diag(Loc, getLangOpts().MSVCCompat
3135 ? diag::ext_ms_template_type_arg_missing_typename
3136 : diag::err_template_arg_must_be_type_suggest)
3137 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003138 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003139
3140 // Recover by synthesizing a type using the location information that we
3141 // already have.
3142 ArgType =
3143 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3144 TypeLocBuilder TLB;
3145 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3146 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3147 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3148 TL.setNameLoc(NameInfo.getLoc());
3149 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3150
3151 // Overwrite our input TemplateArgumentLoc so that we can recover
3152 // properly.
3153 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3154 TemplateArgumentLocInfo(TSI));
3155
3156 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003157 }
3158 }
3159 // fallthrough
3160 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003161 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003162 // We have a template type parameter but the template argument
3163 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003164 SourceRange SR = AL.getSourceRange();
3165 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003166 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003167
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003168 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003169 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003170 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003171
Reid Kleckner377c1592014-06-10 23:29:48 +00003172 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003173 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003174
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003175 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003176 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003177
3178 // Objective-C ARC:
3179 // If an explicitly-specified template argument type is a lifetime type
3180 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003181 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003182 ArgType->isObjCLifetimeType() &&
3183 !ArgType.getObjCLifetime()) {
3184 Qualifiers Qs;
3185 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3186 ArgType = Context.getQualifiedType(ArgType, Qs);
3187 }
3188
3189 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003190 return false;
3191}
3192
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003193/// \brief Substitute template arguments into the default template argument for
3194/// the given template type parameter.
3195///
3196/// \param SemaRef the semantic analysis object for which we are performing
3197/// the substitution.
3198///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003199/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003200/// for.
3201///
3202/// \param TemplateLoc the location of the template name that started the
3203/// template-id we are checking.
3204///
3205/// \param RAngleLoc the location of the right angle bracket ('>') that
3206/// terminates the template-id.
3207///
3208/// \param Param the template template parameter whose default we are
3209/// substituting into.
3210///
3211/// \param Converted the list of template arguments provided for template
3212/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003213/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003214static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003215SubstDefaultTemplateArgument(Sema &SemaRef,
3216 TemplateDecl *Template,
3217 SourceLocation TemplateLoc,
3218 SourceLocation RAngleLoc,
3219 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003220 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003221 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003222
3223 // If the argument type is dependent, instantiate it now based
3224 // on the previously-computed template arguments.
3225 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003226 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003227 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003228 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003229 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003230 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003231
David Majnemer89189202013-08-28 23:48:32 +00003232 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3233 Converted.data(), Converted.size());
3234
3235 // Only substitute for the innermost template argument list.
3236 MultiLevelTemplateArgumentList TemplateArgLists;
3237 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3238 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3239 TemplateArgLists.addOuterTemplateArguments(None);
3240
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003241 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003242 ArgType =
3243 SemaRef.SubstType(ArgType, TemplateArgLists,
3244 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003245 }
3246
3247 return ArgType;
3248}
3249
3250/// \brief Substitute template arguments into the default template argument for
3251/// the given non-type template parameter.
3252///
3253/// \param SemaRef the semantic analysis object for which we are performing
3254/// the substitution.
3255///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003256/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003257/// for.
3258///
3259/// \param TemplateLoc the location of the template name that started the
3260/// template-id we are checking.
3261///
3262/// \param RAngleLoc the location of the right angle bracket ('>') that
3263/// terminates the template-id.
3264///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003265/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003266/// substituting into.
3267///
3268/// \param Converted the list of template arguments provided for template
3269/// parameters that precede \p Param in the template parameter list.
3270///
3271/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003272static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003273SubstDefaultTemplateArgument(Sema &SemaRef,
3274 TemplateDecl *Template,
3275 SourceLocation TemplateLoc,
3276 SourceLocation RAngleLoc,
3277 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003278 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003279 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003280 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003281 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003282 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003283 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003284
David Majnemer89189202013-08-28 23:48:32 +00003285 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3286 Converted.data(), Converted.size());
3287
3288 // Only substitute for the innermost template argument list.
3289 MultiLevelTemplateArgumentList TemplateArgLists;
3290 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3291 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3292 TemplateArgLists.addOuterTemplateArguments(None);
3293
Faisal Vali48401eb2015-11-19 19:20:17 +00003294 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3295 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003296 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003297}
3298
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003299/// \brief Substitute template arguments into the default template argument for
3300/// the given template template parameter.
3301///
3302/// \param SemaRef the semantic analysis object for which we are performing
3303/// the substitution.
3304///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003305/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003306/// for.
3307///
3308/// \param TemplateLoc the location of the template name that started the
3309/// template-id we are checking.
3310///
3311/// \param RAngleLoc the location of the right angle bracket ('>') that
3312/// terminates the template-id.
3313///
3314/// \param Param the template template parameter whose default we are
3315/// substituting into.
3316///
3317/// \param Converted the list of template arguments provided for template
3318/// parameters that precede \p Param in the template parameter list.
3319///
Douglas Gregordf846d12011-03-02 18:46:51 +00003320/// \param QualifierLoc Will be set to the nested-name-specifier (with
3321/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003322///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003323/// \returns the substituted template argument, or NULL if an error occurred.
3324static TemplateName
3325SubstDefaultTemplateArgument(Sema &SemaRef,
3326 TemplateDecl *Template,
3327 SourceLocation TemplateLoc,
3328 SourceLocation RAngleLoc,
3329 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003330 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003331 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003332 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003333 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003334 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003335 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336
David Majnemer89189202013-08-28 23:48:32 +00003337 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3338 Converted.data(), Converted.size());
3339
3340 // Only substitute for the innermost template argument list.
3341 MultiLevelTemplateArgumentList TemplateArgLists;
3342 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3343 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3344 TemplateArgLists.addOuterTemplateArguments(None);
3345
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003346 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003347 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003348 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003349 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003350 QualifierLoc =
3351 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003352 if (!QualifierLoc)
3353 return TemplateName();
3354 }
David Majnemer89189202013-08-28 23:48:32 +00003355
3356 return SemaRef.SubstTemplateName(
3357 QualifierLoc,
3358 Param->getDefaultArgument().getArgument().getAsTemplate(),
3359 Param->getDefaultArgument().getTemplateNameLoc(),
3360 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003361}
3362
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003363/// \brief If the given template parameter has a default template
3364/// argument, substitute into that default template argument and
3365/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003367Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3368 SourceLocation TemplateLoc,
3369 SourceLocation RAngleLoc,
3370 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003371 SmallVectorImpl<TemplateArgument>
3372 &Converted,
3373 bool &HasDefaultArg) {
3374 HasDefaultArg = false;
3375
3376 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003377 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003378 return TemplateArgumentLoc();
3379
Richard Smithc87b9382013-07-04 01:01:24 +00003380 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003381 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003382 TemplateLoc,
3383 RAngleLoc,
3384 TypeParm,
3385 Converted);
3386 if (DI)
3387 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3388
3389 return TemplateArgumentLoc();
3390 }
3391
3392 if (NonTypeTemplateParmDecl *NonTypeParm
3393 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003394 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003395 return TemplateArgumentLoc();
3396
Richard Smithc87b9382013-07-04 01:01:24 +00003397 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003398 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003399 TemplateLoc,
3400 RAngleLoc,
3401 NonTypeParm,
3402 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003403 if (Arg.isInvalid())
3404 return TemplateArgumentLoc();
3405
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003406 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003407 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3408 }
3409
3410 TemplateTemplateParmDecl *TempTempParm
3411 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003412 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003413 return TemplateArgumentLoc();
3414
Richard Smithc87b9382013-07-04 01:01:24 +00003415 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003416 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003417 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003418 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003419 RAngleLoc,
3420 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003421 Converted,
3422 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003423 if (TName.isNull())
3424 return TemplateArgumentLoc();
3425
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003426 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003427 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003428 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3429}
3430
Douglas Gregorda0fb532009-11-11 19:31:23 +00003431/// \brief Check that the given template argument corresponds to the given
3432/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003433///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003434/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003435/// checked.
3436///
Richard Trieu15b66532015-01-24 02:48:32 +00003437/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003438///
3439/// \param Template The template in which the template argument resides.
3440///
3441/// \param TemplateLoc The location of the template name for the template
3442/// whose argument list we're matching.
3443///
3444/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3445/// the template argument list.
3446///
3447/// \param ArgumentPackIndex The index into the argument pack where this
3448/// argument will be placed. Only valid if the parameter is a parameter pack.
3449///
3450/// \param Converted The checked, converted argument will be added to the
3451/// end of this small vector.
3452///
3453/// \param CTAK Describes how we arrived at this particular template argument:
3454/// explicitly written, deduced, etc.
3455///
3456/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003457bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003458 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003459 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003460 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003461 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003462 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003463 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003464 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003465 // Check template type parameters.
3466 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003467 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003468
Douglas Gregoreebed722009-11-11 19:41:09 +00003469 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003470 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003471 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003472 // with the template arguments we've seen thus far. But if the
3473 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003474 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003475 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3476 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003477
Peter Collingbourne01687632010-12-10 17:08:53 +00003478 if (NTTPType->isDependentType() &&
3479 !isa<TemplateTemplateParmDecl>(Template) &&
3480 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003481 // Do substitution on the type of the non-type template parameter.
3482 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003483 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003484 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003485 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003486 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003487
3488 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003489 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003490 NTTPType = SubstType(NTTPType,
3491 MultiLevelTemplateArgumentList(TemplateArgs),
3492 NTTP->getLocation(),
3493 NTTP->getDeclName());
3494 // If that worked, check the non-type template parameter type
3495 // for validity.
3496 if (!NTTPType.isNull())
3497 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3498 NTTP->getLocation());
3499 if (NTTPType.isNull())
3500 return true;
3501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502
Douglas Gregorda0fb532009-11-11 19:31:23 +00003503 switch (Arg.getArgument().getKind()) {
3504 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003505 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
Douglas Gregorda0fb532009-11-11 19:31:23 +00003507 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003508 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003509 ExprResult Res =
3510 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3511 Result, CTAK);
3512 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003513 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514
Richard Trieu15b66532015-01-24 02:48:32 +00003515 // If the resulting expression is new, then use it in place of the
3516 // old expression in the template argument.
3517 if (Res.get() != Arg.getArgument().getAsExpr()) {
3518 TemplateArgument TA(Res.get());
3519 Arg = TemplateArgumentLoc(TA, Res.get());
3520 }
3521
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003522 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003523 break;
3524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525
Douglas Gregorda0fb532009-11-11 19:31:23 +00003526 case TemplateArgument::Declaration:
3527 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003528 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003529 // We've already checked this template argument, so just copy
3530 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003531 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003532 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003533
Douglas Gregorda0fb532009-11-11 19:31:23 +00003534 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003535 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003536 // We were given a template template argument. It may not be ill-formed;
3537 // see below.
3538 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003539 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3540 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003541 // We have a template argument such as \c T::template X, which we
3542 // parsed as a template template argument. However, since we now
3543 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003544 // template name into an expression.
3545
3546 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3547 Arg.getTemplateNameLoc());
3548
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003549 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003550 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003551 // FIXME: the template-template arg was a DependentTemplateName,
3552 // so it was provided with a template keyword. However, its source
3553 // location is not stored in the template argument structure.
3554 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003555 ExprResult E = DependentScopeDeclRefExpr::Create(
3556 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3557 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003558
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003559 // If we parsed the template argument as a pack expansion, create a
3560 // pack expansion expression.
3561 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003562 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003563 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003564 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566
Douglas Gregorda0fb532009-11-11 19:31:23 +00003567 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003568 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003569 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003570 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003572 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003573 break;
3574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003575
Douglas Gregorda0fb532009-11-11 19:31:23 +00003576 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003577 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003578 // therefore cannot be a non-type template argument.
3579 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3580 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003581
Douglas Gregorda0fb532009-11-11 19:31:23 +00003582 Diag(Param->getLocation(), diag::note_template_param_here);
3583 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003584
Douglas Gregorda0fb532009-11-11 19:31:23 +00003585 case TemplateArgument::Type: {
3586 // We have a non-type template parameter but the template
3587 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003588
Douglas Gregorda0fb532009-11-11 19:31:23 +00003589 // C++ [temp.arg]p2:
3590 // In a template-argument, an ambiguity between a type-id and
3591 // an expression is resolved to a type-id, regardless of the
3592 // form of the corresponding template-parameter.
3593 //
3594 // We warn specifically about this case, since it can be rather
3595 // confusing for users.
3596 QualType T = Arg.getArgument().getAsType();
3597 SourceRange SR = Arg.getSourceRange();
3598 if (T->isFunctionType())
3599 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3600 else
3601 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3602 Diag(Param->getLocation(), diag::note_template_param_here);
3603 return true;
3604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003605
Douglas Gregorda0fb532009-11-11 19:31:23 +00003606 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003607 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003609
Douglas Gregorda0fb532009-11-11 19:31:23 +00003610 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003611 }
3612
3613
Douglas Gregorda0fb532009-11-11 19:31:23 +00003614 // Check template template parameters.
3615 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003616
Douglas Gregorda0fb532009-11-11 19:31:23 +00003617 // Substitute into the template parameter list of the template
3618 // template parameter, since previously-supplied template arguments
3619 // may appear within the template template parameter.
3620 {
3621 // Set up a template instantiation context.
3622 LocalInstantiationScope Scope(*this);
3623 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003624 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003625 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003626 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003627 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
3629 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003630 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003631 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003632 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003633 MultiLevelTemplateArgumentList(TemplateArgs)));
3634 if (!TempParm)
3635 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003637
Douglas Gregorda0fb532009-11-11 19:31:23 +00003638 switch (Arg.getArgument().getKind()) {
3639 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003640 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003641
Douglas Gregorda0fb532009-11-11 19:31:23 +00003642 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003643 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003644 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003645 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003646
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003647 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003648 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003649
Douglas Gregorda0fb532009-11-11 19:31:23 +00003650 case TemplateArgument::Expression:
3651 case TemplateArgument::Type:
3652 // We have a template template parameter but the template
3653 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003654 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003655 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003656 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003657
Douglas Gregorda0fb532009-11-11 19:31:23 +00003658 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003659 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003660 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003661 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003662 case TemplateArgument::NullPtr:
3663 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003664
Douglas Gregorda0fb532009-11-11 19:31:23 +00003665 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003666 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003667 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003668
Douglas Gregorda0fb532009-11-11 19:31:23 +00003669 return false;
3670}
3671
Douglas Gregor8e072612012-02-03 07:34:46 +00003672/// \brief Diagnose an arity mismatch in the
3673static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3674 SourceLocation TemplateLoc,
3675 TemplateArgumentListInfo &TemplateArgs) {
3676 TemplateParameterList *Params = Template->getTemplateParameters();
3677 unsigned NumParams = Params->size();
3678 unsigned NumArgs = TemplateArgs.size();
3679
3680 SourceRange Range;
3681 if (NumArgs > NumParams)
3682 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3683 TemplateArgs.getRAngleLoc());
3684 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3685 << (NumArgs > NumParams)
3686 << (isa<ClassTemplateDecl>(Template)? 0 :
3687 isa<FunctionTemplateDecl>(Template)? 1 :
3688 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3689 << Template << Range;
3690 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3691 << Params->getSourceRange();
3692 return true;
3693}
3694
Richard Smith1fde8ec2012-09-07 02:06:42 +00003695/// \brief Check whether the template parameter is a pack expansion, and if so,
3696/// determine the number of parameters produced by that expansion. For instance:
3697///
3698/// \code
3699/// template<typename ...Ts> struct A {
3700/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3701/// };
3702/// \endcode
3703///
3704/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3705/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003706static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003707 if (NonTypeTemplateParmDecl *NTTP
3708 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3709 if (NTTP->isExpandedParameterPack())
3710 return NTTP->getNumExpansionTypes();
3711 }
3712
3713 if (TemplateTemplateParmDecl *TTP
3714 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3715 if (TTP->isExpandedParameterPack())
3716 return TTP->getNumExpansionTemplateParameters();
3717 }
3718
David Blaikie7a30dc52013-02-21 01:47:18 +00003719 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003720}
3721
Richard Smith35c1df52015-06-17 20:16:32 +00003722/// Diagnose a missing template argument.
3723template<typename TemplateParmDecl>
3724static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3725 TemplateDecl *TD,
3726 const TemplateParmDecl *D,
3727 TemplateArgumentListInfo &Args) {
3728 // Dig out the most recent declaration of the template parameter; there may be
3729 // declarations of the template that are more recent than TD.
3730 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3731 ->getTemplateParameters()
3732 ->getParam(D->getIndex()));
3733
3734 // If there's a default argument that's not visible, diagnose that we're
3735 // missing a module import.
3736 llvm::SmallVector<Module*, 8> Modules;
3737 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3738 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3739 D->getDefaultArgumentLoc(), Modules,
3740 Sema::MissingImportKind::DefaultArgument,
3741 /*Recover*/ true);
3742 return true;
3743 }
3744
3745 // FIXME: If there's a more recent default argument that *is* visible,
3746 // diagnose that it was declared too late.
3747
3748 return diagnoseArityMismatch(S, TD, Loc, Args);
3749}
3750
Douglas Gregord32e0282009-02-09 23:23:08 +00003751/// \brief Check that the given template argument list is well-formed
3752/// for specializing the given template.
3753bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3754 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003755 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003756 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003757 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003758 // Make a copy of the template arguments for processing. Only make the
3759 // changes at the end when successful in matching the arguments to the
3760 // template.
3761 TemplateArgumentListInfo NewArgs = TemplateArgs;
3762
Douglas Gregord32e0282009-02-09 23:23:08 +00003763 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003764
Richard Trieu15b66532015-01-24 02:48:32 +00003765 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003766
Mike Stump11289f42009-09-09 15:08:12 +00003767 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003768 // [...] The type and form of each template-argument specified in
3769 // a template-id shall match the type and form specified for the
3770 // corresponding parameter declared by the template in its
3771 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003772 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003773 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003774 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003775 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003776 for (TemplateParameterList::iterator Param = Params->begin(),
3777 ParamEnd = Params->end();
3778 Param != ParamEnd; /* increment in loop */) {
3779 // If we have an expanded parameter pack, make sure we don't have too
3780 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003781 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003782 if (*Expansions == ArgumentPack.size()) {
3783 // We're done with this parameter pack. Pack up its arguments and add
3784 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003785 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00003786 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003787 ArgumentPack.clear();
3788
Richard Smith1fde8ec2012-09-07 02:06:42 +00003789 // This argument is assigned to the next parameter.
3790 ++Param;
3791 continue;
3792 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3793 // Not enough arguments for this parameter pack.
3794 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3795 << false
3796 << (isa<ClassTemplateDecl>(Template)? 0 :
3797 isa<FunctionTemplateDecl>(Template)? 1 :
3798 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3799 << Template;
3800 Diag(Template->getLocation(), diag::note_template_decl_here)
3801 << Params->getSourceRange();
3802 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003803 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003805
Richard Smith1fde8ec2012-09-07 02:06:42 +00003806 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003807 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003808 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003809 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003810 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003811 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003812
Richard Smith96d71c32014-11-12 23:38:38 +00003813 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003814 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003815 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3816 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003817 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003818 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003819 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003820 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003821 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003822 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003823 Diag((*Param)->getLocation(), diag::note_template_param_here);
3824 return true;
3825 }
3826
Richard Smith1fde8ec2012-09-07 02:06:42 +00003827 // We're now done with this argument.
3828 ++ArgIdx;
3829
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003830 if ((*Param)->isTemplateParameterPack()) {
3831 // The template parameter was a template parameter pack, so take the
3832 // deduced argument and place it on the argument pack. Note that we
3833 // stay on the same template parameter so that we can deduce more
3834 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003835 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003836 } else {
3837 // Move to the next template parameter.
3838 ++Param;
3839 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003840
Richard Smith96d71c32014-11-12 23:38:38 +00003841 // If we just saw a pack expansion into a non-pack, then directly convert
3842 // the remaining arguments, because we don't know what parameters they'll
3843 // match up with.
3844 if (PackExpansionIntoNonPack) {
3845 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003846 // If we were part way through filling in an expanded parameter pack,
3847 // fall back to just producing individual arguments.
3848 Converted.insert(Converted.end(),
3849 ArgumentPack.begin(), ArgumentPack.end());
3850 ArgumentPack.clear();
3851 }
3852
3853 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003854 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003855 ++ArgIdx;
3856 }
3857
Richard Smith1fde8ec2012-09-07 02:06:42 +00003858 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003859 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003860
Douglas Gregor84d49a22009-11-11 21:54:23 +00003861 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003862 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003863
Douglas Gregor2f157c92011-06-03 02:59:40 +00003864 // If we're checking a partial template argument list, we're done.
3865 if (PartialTemplateArgs) {
3866 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00003867 Converted.push_back(
3868 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3869
Richard Smith1fde8ec2012-09-07 02:06:42 +00003870 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003871 }
3872
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003873 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003874 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003875 if ((*Param)->isTemplateParameterPack()) {
3876 assert(!getExpandedPackSize(*Param) &&
3877 "Should have dealt with this already");
3878
3879 // A non-expanded parameter pack before the end of the parameter list
3880 // only occurs for an ill-formed template parameter list, unless we've
3881 // got a partial argument list for a function template, so just bail out.
3882 if (Param + 1 != ParamEnd)
3883 return true;
3884
Benjamin Kramercce63472015-08-05 09:40:22 +00003885 Converted.push_back(
3886 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003887 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003888
3889 ++Param;
3890 continue;
3891 }
3892
Douglas Gregor8e072612012-02-03 07:34:46 +00003893 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003894 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003895
Douglas Gregor84d49a22009-11-11 21:54:23 +00003896 // Retrieve the default template argument from the template
3897 // parameter. For each kind of template parameter, we substitute the
3898 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003899 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003900 // the default argument.
3901 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003902 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003903 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3904 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003905
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003906 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003907 Template,
3908 TemplateLoc,
3909 RAngleLoc,
3910 TTP,
3911 Converted);
3912 if (!ArgType)
3913 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003914
Douglas Gregor84d49a22009-11-11 21:54:23 +00003915 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3916 ArgType);
3917 } else if (NonTypeTemplateParmDecl *NTTP
3918 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003919 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003920 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3921 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003922
John McCalldadc5752010-08-24 06:29:42 +00003923 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003924 TemplateLoc,
3925 RAngleLoc,
3926 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003927 Converted);
3928 if (E.isInvalid())
3929 return true;
3930
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003931 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00003932 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3933 } else {
3934 TemplateTemplateParmDecl *TempParm
3935 = cast<TemplateTemplateParmDecl>(*Param);
3936
Richard Smith95d83952015-06-10 20:36:34 +00003937 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00003938 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3939 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003940
Douglas Gregordf846d12011-03-02 18:46:51 +00003941 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003942 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943 TemplateLoc,
3944 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003945 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003946 Converted,
3947 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003948 if (Name.isNull())
3949 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003950
Douglas Gregor9d802122011-03-02 17:09:35 +00003951 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3952 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003953 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003954
Douglas Gregor84d49a22009-11-11 21:54:23 +00003955 // Introduce an instantiation record that describes where we are using
3956 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003957 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3958 SourceRange(TemplateLoc, RAngleLoc));
3959 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003960 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003961
Douglas Gregor84d49a22009-11-11 21:54:23 +00003962 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003963 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003964 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003965 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966
Richard Trieu15b66532015-01-24 02:48:32 +00003967 // Core issue 150 (assumed resolution): if this is a template template
3968 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00003969 // template definition.
3970 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00003971 NewArgs.addArgument(Arg);
3972
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003973 // Move to the next template parameter and argument.
3974 ++Param;
3975 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003976 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003977
Richard Smith07f79912014-06-06 16:00:50 +00003978 // If we're performing a partial argument substitution, allow any trailing
3979 // pack expansions; they might be empty. This can happen even if
3980 // PartialTemplateArgs is false (the list of arguments is complete but
3981 // still dependent).
3982 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3983 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00003984 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3985 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00003986 }
3987
Douglas Gregor8e072612012-02-03 07:34:46 +00003988 // If we have any leftover arguments, then there were too many arguments.
3989 // Complain and fail.
3990 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00003991 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3992
3993 // No problems found with the new argument list, propagate changes back
3994 // to caller.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00003995 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003996
Richard Smith1fde8ec2012-09-07 02:06:42 +00003997 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00003998}
3999
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004000namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004001 class UnnamedLocalNoLinkageFinder
4002 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004003 {
4004 Sema &S;
4005 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004006
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004007 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004008
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004009 public:
4010 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4011
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004012 bool Visit(QualType T) {
4013 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004014 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004015
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004016#define TYPE(Class, Parent) \
4017 bool Visit##Class##Type(const Class##Type *);
4018#define ABSTRACT_TYPE(Class, Parent) \
4019 bool Visit##Class##Type(const Class##Type *) { return false; }
4020#define NON_CANONICAL_TYPE(Class, Parent) \
4021 bool Visit##Class##Type(const Class##Type *) { return false; }
4022#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004023
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004024 bool VisitTagDecl(const TagDecl *Tag);
4025 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4026 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004027} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004028
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004029bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004030 return false;
4031}
4032
4033bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4034 return Visit(T->getElementType());
4035}
4036
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004037bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004038 return Visit(T->getPointeeType());
4039}
4040
4041bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004042 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004043 return Visit(T->getPointeeType());
4044}
4045
4046bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004047 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004048 return Visit(T->getPointeeType());
4049}
4050
4051bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004052 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004053 return Visit(T->getPointeeType());
4054}
4055
4056bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004058 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4059}
4060
4061bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004062 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004063 return Visit(T->getElementType());
4064}
4065
4066bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004068 return Visit(T->getElementType());
4069}
4070
4071bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004072 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004073 return Visit(T->getElementType());
4074}
4075
4076bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004077 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004078 return Visit(T->getElementType());
4079}
4080
4081bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004082 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004083 return Visit(T->getElementType());
4084}
4085
4086bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4087 return Visit(T->getElementType());
4088}
4089
4090bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4091 return Visit(T->getElementType());
4092}
4093
4094bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4095 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004096 for (const auto &A : T->param_types()) {
4097 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004098 return true;
4099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004100
Alp Toker314cc812014-01-25 16:55:45 +00004101 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004102}
4103
4104bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4105 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004106 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004107}
4108
4109bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4110 const UnresolvedUsingType*) {
4111 return false;
4112}
4113
4114bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4115 return false;
4116}
4117
4118bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4119 return Visit(T->getUnderlyingType());
4120}
4121
4122bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4123 return false;
4124}
4125
Alexis Hunte852b102011-05-24 22:41:36 +00004126bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4127 const UnaryTransformType*) {
4128 return false;
4129}
4130
Richard Smith30482bc2011-02-20 03:19:35 +00004131bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4132 return Visit(T->getDeducedType());
4133}
4134
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004135bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4136 return VisitTagDecl(T->getDecl());
4137}
4138
4139bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4140 return VisitTagDecl(T->getDecl());
4141}
4142
4143bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4144 const TemplateTypeParmType*) {
4145 return false;
4146}
4147
Douglas Gregorada4b792011-01-14 02:55:32 +00004148bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4149 const SubstTemplateTypeParmPackType *) {
4150 return false;
4151}
4152
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004153bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4154 const TemplateSpecializationType*) {
4155 return false;
4156}
4157
4158bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4159 const InjectedClassNameType* T) {
4160 return VisitTagDecl(T->getDecl());
4161}
4162
4163bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4164 const DependentNameType* T) {
4165 return VisitNestedNameSpecifier(T->getQualifier());
4166}
4167
4168bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4169 const DependentTemplateSpecializationType* T) {
4170 return VisitNestedNameSpecifier(T->getQualifier());
4171}
4172
Douglas Gregord2fa7662010-12-20 02:24:11 +00004173bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4174 const PackExpansionType* T) {
4175 return Visit(T->getPattern());
4176}
4177
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004178bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4179 return false;
4180}
4181
4182bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4183 const ObjCInterfaceType *) {
4184 return false;
4185}
4186
4187bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4188 const ObjCObjectPointerType *) {
4189 return false;
4190}
4191
Eli Friedman0dfb8892011-10-06 23:00:33 +00004192bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4193 return Visit(T->getValueType());
4194}
4195
Xiuli Pan9c14e282016-01-09 12:53:17 +00004196bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4197 return false;
4198}
4199
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004200bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4201 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004202 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004203 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004204 diag::warn_cxx98_compat_template_arg_local_type :
4205 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004206 << S.Context.getTypeDeclType(Tag) << SR;
4207 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004208 }
4209
John McCall5ea95772013-03-09 00:54:27 +00004210 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004211 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004212 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004213 diag::warn_cxx98_compat_template_arg_unnamed_type :
4214 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004215 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4216 return true;
4217 }
4218
4219 return false;
4220}
4221
4222bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4223 NestedNameSpecifier *NNS) {
4224 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4225 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004227 switch (NNS->getKind()) {
4228 case NestedNameSpecifier::Identifier:
4229 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004230 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004231 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004232 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004233 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004234
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004235 case NestedNameSpecifier::TypeSpec:
4236 case NestedNameSpecifier::TypeSpecWithTemplate:
4237 return Visit(QualType(NNS->getAsType(), 0));
4238 }
David Blaikie8a40f702012-01-17 06:56:22 +00004239 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004240}
4241
Douglas Gregord32e0282009-02-09 23:23:08 +00004242/// \brief Check a template argument against its corresponding
4243/// template type parameter.
4244///
4245/// This routine implements the semantics of C++ [temp.arg.type]. It
4246/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004247bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004248 TypeSourceInfo *ArgInfo) {
4249 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004250 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004251 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004252
4253 if (Arg->isVariablyModifiedType()) {
4254 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004255 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004256 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004257 }
4258
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004259 // C++03 [temp.arg.type]p2:
4260 // A local type, a type with no linkage, an unnamed type or a type
4261 // compounded from any of these types shall not be used as a
4262 // template-argument for a template type-parameter.
4263 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004264 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004265 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004266 bool NeedsCheck;
4267 if (LangOpts.CPlusPlus11)
4268 NeedsCheck =
4269 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4270 SR.getBegin()) ||
4271 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4272 SR.getBegin());
4273 else
4274 NeedsCheck = Arg->hasUnnamedOrLocalType();
4275
4276 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004277 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4278 (void)Finder.Visit(Context.getCanonicalType(Arg));
4279 }
4280
Douglas Gregord32e0282009-02-09 23:23:08 +00004281 return false;
4282}
4283
Douglas Gregor20fdef32012-04-10 17:08:25 +00004284enum NullPointerValueKind {
4285 NPV_NotNullPointer,
4286 NPV_NullPointer,
4287 NPV_Error
4288};
4289
4290/// \brief Determine whether the given template argument is a null pointer
4291/// value of the appropriate type.
4292static NullPointerValueKind
4293isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4294 QualType ParamType, Expr *Arg) {
4295 if (Arg->isValueDependent() || Arg->isTypeDependent())
4296 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004297
Richard Smithdb0ac552015-12-18 22:40:25 +00004298 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004299 llvm_unreachable(
4300 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004301
David Majnemer5c734ad2014-08-14 00:49:23 +00004302 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004303 return NPV_NotNullPointer;
4304
4305 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004306 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4307 if (ArgRV.isInvalid())
4308 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004309 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004310
Douglas Gregor20fdef32012-04-10 17:08:25 +00004311 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004312 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004313 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004314 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004315 EvalResult.HasSideEffects) {
4316 SourceLocation DiagLoc = Arg->getExprLoc();
4317
4318 // If our only note is the usual "invalid subexpression" note, just point
4319 // the caret at its location rather than producing an essentially
4320 // redundant note.
4321 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4322 diag::note_invalid_subexpr_in_const_expr) {
4323 DiagLoc = Notes[0].first;
4324 Notes.clear();
4325 }
4326
4327 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4328 << Arg->getType() << Arg->getSourceRange();
4329 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4330 S.Diag(Notes[I].first, Notes[I].second);
4331
4332 S.Diag(Param->getLocation(), diag::note_template_param_here);
4333 return NPV_Error;
4334 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004335
4336 // C++11 [temp.arg.nontype]p1:
4337 // - an address constant expression of type std::nullptr_t
4338 if (Arg->getType()->isNullPtrType())
4339 return NPV_NullPointer;
4340
4341 // - a constant expression that evaluates to a null pointer value (4.10); or
4342 // - a constant expression that evaluates to a null member pointer value
4343 // (4.11); or
4344 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4345 (EvalResult.Val.isMemberPointer() &&
4346 !EvalResult.Val.getMemberPointerDecl())) {
4347 // If our expression has an appropriate type, we've succeeded.
4348 bool ObjCLifetimeConversion;
4349 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4350 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4351 ObjCLifetimeConversion))
4352 return NPV_NullPointer;
4353
4354 // The types didn't match, but we know we got a null pointer; complain,
4355 // then recover as if the types were correct.
4356 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4357 << Arg->getType() << ParamType << Arg->getSourceRange();
4358 S.Diag(Param->getLocation(), diag::note_template_param_here);
4359 return NPV_NullPointer;
4360 }
4361
4362 // If we don't have a null pointer value, but we do have a NULL pointer
4363 // constant, suggest a cast to the appropriate type.
4364 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4365 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4366 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004367 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4368 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4369 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004370 S.Diag(Param->getLocation(), diag::note_template_param_here);
4371 return NPV_NullPointer;
4372 }
4373
4374 // FIXME: If we ever want to support general, address-constant expressions
4375 // as non-type template arguments, we should return the ExprResult here to
4376 // be interpreted by the caller.
4377 return NPV_NotNullPointer;
4378}
4379
David Majnemer61c39a12013-08-23 05:39:39 +00004380/// \brief Checks whether the given template argument is compatible with its
4381/// template parameter.
4382static bool CheckTemplateArgumentIsCompatibleWithParameter(
4383 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4384 Expr *Arg, QualType ArgType) {
4385 bool ObjCLifetimeConversion;
4386 if (ParamType->isPointerType() &&
4387 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4388 S.IsQualificationConversion(ArgType, ParamType, false,
4389 ObjCLifetimeConversion)) {
4390 // For pointer-to-object types, qualification conversions are
4391 // permitted.
4392 } else {
4393 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4394 if (!ParamRef->getPointeeType()->isFunctionType()) {
4395 // C++ [temp.arg.nontype]p5b3:
4396 // For a non-type template-parameter of type reference to
4397 // object, no conversions apply. The type referred to by the
4398 // reference may be more cv-qualified than the (otherwise
4399 // identical) type of the template- argument. The
4400 // template-parameter is bound directly to the
4401 // template-argument, which shall be an lvalue.
4402
4403 // FIXME: Other qualifiers?
4404 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4405 unsigned ArgQuals = ArgType.getCVRQualifiers();
4406
4407 if ((ParamQuals | ArgQuals) != ParamQuals) {
4408 S.Diag(Arg->getLocStart(),
4409 diag::err_template_arg_ref_bind_ignores_quals)
4410 << ParamType << Arg->getType() << Arg->getSourceRange();
4411 S.Diag(Param->getLocation(), diag::note_template_param_here);
4412 return true;
4413 }
4414 }
4415 }
4416
4417 // At this point, the template argument refers to an object or
4418 // function with external linkage. We now need to check whether the
4419 // argument and parameter types are compatible.
4420 if (!S.Context.hasSameUnqualifiedType(ArgType,
4421 ParamType.getNonReferenceType())) {
4422 // We can't perform this conversion or binding.
4423 if (ParamType->isReferenceType())
4424 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4425 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4426 else
4427 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4428 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4429 S.Diag(Param->getLocation(), diag::note_template_param_here);
4430 return true;
4431 }
4432 }
4433
4434 return false;
4435}
4436
Douglas Gregorccb07762009-02-11 19:52:55 +00004437/// \brief Checks whether the given template argument is the address
4438/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004440CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4441 NonTypeTemplateParmDecl *Param,
4442 QualType ParamType,
4443 Expr *ArgIn,
4444 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004445 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004446 Expr *Arg = ArgIn;
4447 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004448
Douglas Gregorb242683d2010-04-01 18:32:35 +00004449 bool AddressTaken = false;
4450 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004451 if (S.getLangOpts().MicrosoftExt) {
4452 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4453 // dereference and address-of operators.
4454 Arg = Arg->IgnoreParenCasts();
4455
4456 bool ExtWarnMSTemplateArg = false;
4457 UnaryOperatorKind FirstOpKind;
4458 SourceLocation FirstOpLoc;
4459 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4460 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4461 if (UnOpKind == UO_Deref)
4462 ExtWarnMSTemplateArg = true;
4463 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4464 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4465 if (!AddrOpLoc.isValid()) {
4466 FirstOpKind = UnOpKind;
4467 FirstOpLoc = UnOp->getOperatorLoc();
4468 }
4469 } else
4470 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004471 }
David Majnemer61c39a12013-08-23 05:39:39 +00004472 if (FirstOpLoc.isValid()) {
4473 if (ExtWarnMSTemplateArg)
4474 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4475 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004476
David Majnemer61c39a12013-08-23 05:39:39 +00004477 if (FirstOpKind == UO_AddrOf)
4478 AddressTaken = true;
4479 else if (Arg->getType()->isPointerType()) {
4480 // We cannot let pointers get dereferenced here, that is obviously not a
4481 // constant expression.
4482 assert(FirstOpKind == UO_Deref);
4483 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4484 << Arg->getSourceRange();
4485 }
4486 }
4487 } else {
4488 // See through any implicit casts we added to fix the type.
4489 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004490
David Majnemer61c39a12013-08-23 05:39:39 +00004491 // C++ [temp.arg.nontype]p1:
4492 //
4493 // A template-argument for a non-type, non-template
4494 // template-parameter shall be one of: [...]
4495 //
4496 // -- the address of an object or function with external
4497 // linkage, including function templates and function
4498 // template-ids but excluding non-static class members,
4499 // expressed as & id-expression where the & is optional if
4500 // the name refers to a function or array, or if the
4501 // corresponding template-parameter is a reference; or
4502
4503 // In C++98/03 mode, give an extension warning on any extra parentheses.
4504 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4505 bool ExtraParens = false;
4506 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4507 if (!Invalid && !ExtraParens) {
4508 S.Diag(Arg->getLocStart(),
4509 S.getLangOpts().CPlusPlus11
4510 ? diag::warn_cxx98_compat_template_arg_extra_parens
4511 : diag::ext_template_arg_extra_parens)
4512 << Arg->getSourceRange();
4513 ExtraParens = true;
4514 }
4515
4516 Arg = Parens->getSubExpr();
4517 }
4518
4519 while (SubstNonTypeTemplateParmExpr *subst =
4520 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4521 Arg = subst->getReplacement()->IgnoreImpCasts();
4522
4523 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4524 if (UnOp->getOpcode() == UO_AddrOf) {
4525 Arg = UnOp->getSubExpr();
4526 AddressTaken = true;
4527 AddrOpLoc = UnOp->getOperatorLoc();
4528 }
4529 }
4530
4531 while (SubstNonTypeTemplateParmExpr *subst =
4532 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4533 Arg = subst->getReplacement()->IgnoreImpCasts();
4534 }
John McCall7c454bb2011-07-15 05:09:51 +00004535
David Majnemer07910d62014-06-26 07:48:46 +00004536 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4537 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4538
4539 // If our parameter has pointer type, check for a null template value.
4540 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4541 NullPointerValueKind NPV;
4542 // dllimport'd entities aren't constant but are available inside of template
4543 // arguments.
4544 if (Entity && Entity->hasAttr<DLLImportAttr>())
4545 NPV = NPV_NotNullPointer;
4546 else
4547 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4548 switch (NPV) {
4549 case NPV_NullPointer:
4550 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004551 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4552 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004553 return false;
4554
4555 case NPV_Error:
4556 return true;
4557
4558 case NPV_NotNullPointer:
4559 break;
4560 }
4561 }
4562
Chandler Carruth724a8a12010-01-31 10:01:20 +00004563 // Stop checking the precise nature of the argument if it is value dependent,
4564 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004565 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004566 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004567 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004568 }
David Majnemer61c39a12013-08-23 05:39:39 +00004569
4570 if (isa<CXXUuidofExpr>(Arg)) {
4571 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4572 ArgIn, Arg, ArgType))
4573 return true;
4574
4575 Converted = TemplateArgument(ArgIn);
4576 return false;
4577 }
4578
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004579 if (!DRE) {
4580 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4581 << Arg->getSourceRange();
4582 S.Diag(Param->getLocation(), diag::note_template_param_here);
4583 return true;
4584 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004585
Douglas Gregorccb07762009-02-11 19:52:55 +00004586 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004587 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004588 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004589 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004590 S.Diag(Param->getLocation(), diag::note_template_param_here);
4591 return true;
4592 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004593
4594 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004595 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004596 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004597 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004598 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004599 S.Diag(Param->getLocation(), diag::note_template_param_here);
4600 return true;
4601 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004602 }
Mike Stump11289f42009-09-09 15:08:12 +00004603
Richard Smith9380e0e2012-04-04 21:11:30 +00004604 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4605 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004606
Richard Smith9380e0e2012-04-04 21:11:30 +00004607 // A non-type template argument must refer to an object or function.
4608 if (!Func && !Var) {
4609 // We found something, but we don't know specifically what it is.
4610 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4611 << Arg->getSourceRange();
4612 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4613 return true;
4614 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004615
Richard Smith9380e0e2012-04-04 21:11:30 +00004616 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004617 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004618 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004619 diag::warn_cxx98_compat_template_arg_object_internal :
4620 diag::ext_template_arg_object_internal)
4621 << !Func << Entity << Arg->getSourceRange();
4622 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4623 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004624 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004625 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4626 << !Func << Entity << Arg->getSourceRange();
4627 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4628 << !Func;
4629 return true;
4630 }
4631
4632 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004633 // If the template parameter has pointer type, the function decays.
4634 if (ParamType->isPointerType() && !AddressTaken)
4635 ArgType = S.Context.getPointerType(Func->getType());
4636 else if (AddressTaken && ParamType->isReferenceType()) {
4637 // If we originally had an address-of operator, but the
4638 // parameter has reference type, complain and (if things look
4639 // like they will work) drop the address-of operator.
4640 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4641 ParamType.getNonReferenceType())) {
4642 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4643 << ParamType;
4644 S.Diag(Param->getLocation(), diag::note_template_param_here);
4645 return true;
4646 }
4647
4648 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4649 << ParamType
4650 << FixItHint::CreateRemoval(AddrOpLoc);
4651 S.Diag(Param->getLocation(), diag::note_template_param_here);
4652
4653 ArgType = Func->getType();
4654 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004655 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004656 // A value of reference type is not an object.
4657 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004658 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004659 diag::err_template_arg_reference_var)
4660 << Var->getType() << Arg->getSourceRange();
4661 S.Diag(Param->getLocation(), diag::note_template_param_here);
4662 return true;
4663 }
4664
Richard Smith9380e0e2012-04-04 21:11:30 +00004665 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004666 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004667 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4668 << Arg->getSourceRange();
4669 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4670 return true;
4671 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004672
4673 // If the template parameter has pointer type, we must have taken
4674 // the address of this object.
4675 if (ParamType->isReferenceType()) {
4676 if (AddressTaken) {
4677 // If we originally had an address-of operator, but the
4678 // parameter has reference type, complain and (if things look
4679 // like they will work) drop the address-of operator.
4680 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4681 ParamType.getNonReferenceType())) {
4682 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4683 << ParamType;
4684 S.Diag(Param->getLocation(), diag::note_template_param_here);
4685 return true;
4686 }
4687
4688 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4689 << ParamType
4690 << FixItHint::CreateRemoval(AddrOpLoc);
4691 S.Diag(Param->getLocation(), diag::note_template_param_here);
4692
4693 ArgType = Var->getType();
4694 }
4695 } else if (!AddressTaken && ParamType->isPointerType()) {
4696 if (Var->getType()->isArrayType()) {
4697 // Array-to-pointer decay.
4698 ArgType = S.Context.getArrayDecayedType(Var->getType());
4699 } else {
4700 // If the template parameter has pointer type but the address of
4701 // this object was not taken, complain and (possibly) recover by
4702 // taking the address of the entity.
4703 ArgType = S.Context.getPointerType(Var->getType());
4704 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4705 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4706 << ParamType;
4707 S.Diag(Param->getLocation(), diag::note_template_param_here);
4708 return true;
4709 }
4710
4711 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4712 << ParamType
4713 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4714
4715 S.Diag(Param->getLocation(), diag::note_template_param_here);
4716 }
4717 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004718 }
Mike Stump11289f42009-09-09 15:08:12 +00004719
David Majnemer61c39a12013-08-23 05:39:39 +00004720 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4721 Arg, ArgType))
4722 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004723
4724 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004725 Converted =
4726 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004727 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004728 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004729}
4730
4731/// \brief Checks whether the given template argument is a pointer to
4732/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004733static bool CheckTemplateArgumentPointerToMember(Sema &S,
4734 NonTypeTemplateParmDecl *Param,
4735 QualType ParamType,
4736 Expr *&ResultArg,
4737 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004738 bool Invalid = false;
4739
Douglas Gregor20fdef32012-04-10 17:08:25 +00004740 // Check for a null pointer value.
4741 Expr *Arg = ResultArg;
4742 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4743 case NPV_Error:
4744 return true;
4745 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004746 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004747 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4748 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004749 return false;
4750 case NPV_NotNullPointer:
4751 break;
4752 }
4753
4754 bool ObjCLifetimeConversion;
4755 if (S.IsQualificationConversion(Arg->getType(),
4756 ParamType.getNonReferenceType(),
4757 false, ObjCLifetimeConversion)) {
4758 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004759 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004760 ResultArg = Arg;
4761 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4762 ParamType.getNonReferenceType())) {
4763 // We can't perform this conversion.
4764 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4765 << Arg->getType() << ParamType << Arg->getSourceRange();
4766 S.Diag(Param->getLocation(), diag::note_template_param_here);
4767 return true;
4768 }
4769
Douglas Gregorccb07762009-02-11 19:52:55 +00004770 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004771 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004772 Arg = Cast->getSubExpr();
4773
4774 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004775 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004776 // A template-argument for a non-type, non-template
4777 // template-parameter shall be one of: [...]
4778 //
4779 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004780 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004781
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004782 // In C++98/03 mode, give an extension warning on any extra parentheses.
4783 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4784 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004785 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004786 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004787 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004788 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004789 diag::warn_cxx98_compat_template_arg_extra_parens :
4790 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004791 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004792 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004793 }
4794
4795 Arg = Parens->getSubExpr();
4796 }
4797
John McCall7c454bb2011-07-15 05:09:51 +00004798 while (SubstNonTypeTemplateParmExpr *subst =
4799 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4800 Arg = subst->getReplacement()->IgnoreImpCasts();
4801
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004802 // A pointer-to-member constant written &Class::member.
4803 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004804 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004805 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4806 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004807 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004808 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004809 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004810 // A constant of pointer-to-member type.
4811 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4812 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4813 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004814 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004815 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004816 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004817 } else {
4818 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004819 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004820 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004821 return Invalid;
4822 }
4823 }
4824 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004825
Craig Topperc3ec1492014-05-26 06:22:03 +00004826 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004827 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004828
Douglas Gregorccb07762009-02-11 19:52:55 +00004829 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004830 return S.Diag(Arg->getLocStart(),
4831 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004832 << Arg->getSourceRange();
4833
David Majnemer3ac84e62013-10-22 21:56:38 +00004834 if (isa<FieldDecl>(DRE->getDecl()) ||
4835 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4836 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004837 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004838 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004839 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4840 "Only non-static member pointers can make it here");
4841
4842 // Okay: this is the address of a non-static member, and therefore
4843 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004844 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004845 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004846 } else {
4847 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004848 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004849 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004850 return Invalid;
4851 }
4852
4853 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004854 S.Diag(Arg->getLocStart(),
4855 diag::err_template_arg_not_pointer_to_member_form)
4856 << Arg->getSourceRange();
4857 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004858 return true;
4859}
4860
Douglas Gregord32e0282009-02-09 23:23:08 +00004861/// \brief Check a template argument against its corresponding
4862/// non-type template parameter.
4863///
Douglas Gregor463421d2009-03-03 04:44:36 +00004864/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004865/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004866/// returns the converted template argument. \p ParamType is the
4867/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004868ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004869 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004870 TemplateArgument &Converted,
4871 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004872 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004873
Douglas Gregor86560402009-02-10 23:36:10 +00004874 // If either the parameter has a dependent type or the argument is
4875 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004876 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004877 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004878 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004879 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004880 }
Douglas Gregor86560402009-02-10 23:36:10 +00004881
Richard Smithd663fdd2014-12-17 20:42:37 +00004882 // We should have already dropped all cv-qualifiers by now.
4883 assert(!ParamType.hasQualifiers() &&
4884 "non-type template parameter type cannot be qualified");
4885
4886 if (CTAK == CTAK_Deduced &&
4887 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4888 // C++ [temp.deduct.type]p17:
4889 // If, in the declaration of a function template with a non-type
4890 // template-parameter, the non-type template-parameter is used
4891 // in an expression in the function parameter-list and, if the
4892 // corresponding template-argument is deduced, the
4893 // template-argument type shall match the type of the
4894 // template-parameter exactly, except that a template-argument
4895 // deduced from an array bound may be of any integral type.
4896 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4897 << Arg->getType().getUnqualifiedType()
4898 << ParamType.getUnqualifiedType();
4899 Diag(Param->getLocation(), diag::note_template_param_here);
4900 return ExprError();
4901 }
4902
Richard Smith410cc892014-11-26 03:26:53 +00004903 if (getLangOpts().CPlusPlus1z) {
4904 // FIXME: We can do some limited checking for a value-dependent but not
4905 // type-dependent argument.
4906 if (Arg->isValueDependent()) {
4907 Converted = TemplateArgument(Arg);
4908 return Arg;
4909 }
4910
4911 // C++1z [temp.arg.nontype]p1:
4912 // A template-argument for a non-type template parameter shall be
4913 // a converted constant expression of the type of the template-parameter.
4914 APValue Value;
4915 ExprResult ArgResult = CheckConvertedConstantExpression(
4916 Arg, ParamType, Value, CCEK_TemplateArg);
4917 if (ArgResult.isInvalid())
4918 return ExprError();
4919
Richard Smithd663fdd2014-12-17 20:42:37 +00004920 QualType CanonParamType = Context.getCanonicalType(ParamType);
4921
Richard Smith410cc892014-11-26 03:26:53 +00004922 // Convert the APValue to a TemplateArgument.
4923 switch (Value.getKind()) {
4924 case APValue::Uninitialized:
4925 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004926 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004927 break;
4928 case APValue::Int:
4929 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004930 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00004931 break;
4932 case APValue::MemberPointer: {
4933 assert(ParamType->isMemberPointerType());
4934
4935 // FIXME: We need TemplateArgument representation and mangling for these.
4936 if (!Value.getMemberPointerPath().empty()) {
4937 Diag(Arg->getLocStart(),
4938 diag::err_template_arg_member_ptr_base_derived_not_supported)
4939 << Value.getMemberPointerDecl() << ParamType
4940 << Arg->getSourceRange();
4941 return ExprError();
4942 }
4943
4944 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00004945 Converted = VD ? TemplateArgument(VD, CanonParamType)
4946 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004947 break;
4948 }
4949 case APValue::LValue: {
4950 // For a non-type template-parameter of pointer or reference type,
4951 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00004952 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4953 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00004954 // -- a temporary object
4955 // -- a string literal
4956 // -- the result of a typeid expression, or
4957 // -- a predefind __func__ variable
4958 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4959 if (isa<CXXUuidofExpr>(E)) {
4960 Converted = TemplateArgument(const_cast<Expr*>(E));
4961 break;
4962 }
4963 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4964 << Arg->getSourceRange();
4965 return ExprError();
4966 }
4967 auto *VD = const_cast<ValueDecl *>(
4968 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4969 // -- a subobject
4970 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4971 VD && VD->getType()->isArrayType() &&
4972 Value.getLValuePath()[0].ArrayIndex == 0 &&
4973 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4974 // Per defect report (no number yet):
4975 // ... other than a pointer to the first element of a complete array
4976 // object.
4977 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4978 Value.isLValueOnePastTheEnd()) {
4979 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4980 << Value.getAsString(Context, ParamType);
4981 return ExprError();
4982 }
Richard Smithd663fdd2014-12-17 20:42:37 +00004983 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00004984 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00004985 assert((!VD || !ParamType->isNullPtrType()) &&
4986 "non-null value of type nullptr_t?");
4987 Converted = VD ? TemplateArgument(VD, CanonParamType)
4988 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004989 break;
4990 }
4991 case APValue::AddrLabelDiff:
4992 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4993 case APValue::Float:
4994 case APValue::ComplexInt:
4995 case APValue::ComplexFloat:
4996 case APValue::Vector:
4997 case APValue::Array:
4998 case APValue::Struct:
4999 case APValue::Union:
5000 llvm_unreachable("invalid kind for template argument");
5001 }
5002
5003 return ArgResult.get();
5004 }
5005
Douglas Gregor86560402009-02-10 23:36:10 +00005006 // C++ [temp.arg.nontype]p5:
5007 // The following conversions are performed on each expression used
5008 // as a non-type template-argument. If a non-type
5009 // template-argument cannot be converted to the type of the
5010 // corresponding template-parameter then the program is
5011 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005012 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005013 // C++11:
5014 // -- for a non-type template-parameter of integral or
5015 // enumeration type, conversions permitted in a converted
5016 // constant expression are applied.
5017 //
5018 // C++98:
5019 // -- for a non-type template-parameter of integral or
5020 // enumeration type, integral promotions (4.5) and integral
5021 // conversions (4.7) are applied.
5022
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005023 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005024 // We can't check arbitrary value-dependent arguments.
5025 // FIXME: If there's no viable conversion to the template parameter type,
5026 // we should be able to diagnose that prior to instantiation.
5027 if (Arg->isValueDependent()) {
5028 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005029 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00005030 }
5031
5032 // C++ [temp.arg.nontype]p1:
5033 // A template-argument for a non-type, non-template template-parameter
5034 // shall be one of:
5035 //
5036 // -- for a non-type template-parameter of integral or enumeration
5037 // type, a converted constant expression of the type of the
5038 // template-parameter; or
5039 llvm::APSInt Value;
5040 ExprResult ArgResult =
5041 CheckConvertedConstantExpression(Arg, ParamType, Value,
5042 CCEK_TemplateArg);
5043 if (ArgResult.isInvalid())
5044 return ExprError();
5045
5046 // Widen the argument value to sizeof(parameter type). This is almost
5047 // always a no-op, except when the parameter type is bool. In
5048 // that case, this may extend the argument from 1 bit to 8 bits.
5049 QualType IntegerType = ParamType;
5050 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5051 IntegerType = Enum->getDecl()->getIntegerType();
5052 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5053
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005054 Converted = TemplateArgument(Context, Value,
5055 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005056 return ArgResult;
5057 }
5058
Richard Smith08b12f12011-10-27 22:11:44 +00005059 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5060 if (ArgResult.isInvalid())
5061 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005062 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005063
5064 QualType ArgType = Arg->getType();
5065
Douglas Gregor86560402009-02-10 23:36:10 +00005066 // C++ [temp.arg.nontype]p1:
5067 // A template-argument for a non-type, non-template
5068 // template-parameter shall be one of:
5069 //
5070 // -- an integral constant-expression of integral or enumeration
5071 // type; or
5072 // -- the name of a non-type template-parameter; or
5073 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005074 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005075 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005076 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005077 diag::err_template_arg_not_integral_or_enumeral)
5078 << ArgType << Arg->getSourceRange();
5079 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005080 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005081 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005082 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5083 QualType T;
5084
5085 public:
5086 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005087
5088 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5089 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005090 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5091 }
5092 } Diagnoser(ArgType);
5093
5094 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005095 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005096 if (!Arg)
5097 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005098 }
5099
Richard Smithd663fdd2014-12-17 20:42:37 +00005100 // From here on out, all we care about is the unqualified form
5101 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005102 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005103
5104 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005105 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005106 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005107 } else if (ParamType->isBooleanType()) {
5108 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005109 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005110 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5111 !ParamType->isEnumeralType()) {
5112 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005113 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005114 } else {
5115 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005116 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005117 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005118 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005119 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005120 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005121 }
5122
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005123 // Add the value of this argument to the list of converted
5124 // arguments. We use the bitwidth and signedness of the template
5125 // parameter.
5126 if (Arg->isValueDependent()) {
5127 // The argument is value-dependent. Create a new
5128 // TemplateArgument with the converted expression.
5129 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005130 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005131 }
5132
Douglas Gregor52aba872009-03-14 00:20:21 +00005133 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005134 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005135 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005136
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005137 if (ParamType->isBooleanType()) {
5138 // Value must be zero or one.
5139 Value = Value != 0;
5140 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5141 if (Value.getBitWidth() != AllowedBits)
5142 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005143 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005144 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005145 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005146
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005147 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005148 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005149 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005150 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005151 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005152 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005153
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005154 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005155 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005156 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005157 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005158 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5159 << Arg->getSourceRange();
5160 Diag(Param->getLocation(), diag::note_template_param_here);
5161 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005162
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005163 // Complain if we overflowed the template parameter's type.
5164 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005165 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005166 RequiredBits = OldValue.getActiveBits();
5167 else if (OldValue.isUnsigned())
5168 RequiredBits = OldValue.getActiveBits() + 1;
5169 else
5170 RequiredBits = OldValue.getMinSignedBits();
5171 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005172 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005173 diag::warn_template_arg_too_large)
5174 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5175 << Arg->getSourceRange();
5176 Diag(Param->getLocation(), diag::note_template_param_here);
5177 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005178 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005179
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005180 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005181 ParamType->isEnumeralType()
5182 ? Context.getCanonicalType(ParamType)
5183 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005184 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005185 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005186
Richard Smith08b12f12011-10-27 22:11:44 +00005187 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005188 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5189
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005190 // Handle pointer-to-function, reference-to-function, and
5191 // pointer-to-member-function all in (roughly) the same way.
5192 if (// -- For a non-type template-parameter of type pointer to
5193 // function, only the function-to-pointer conversion (4.3) is
5194 // applied. If the template-argument represents a set of
5195 // overloaded functions (or a pointer to such), the matching
5196 // function is selected from the set (13.4).
5197 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005198 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005199 // -- For a non-type template-parameter of type reference to
5200 // function, no conversions apply. If the template-argument
5201 // represents a set of overloaded functions, the matching
5202 // function is selected from the set (13.4).
5203 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005204 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005205 // -- For a non-type template-parameter of type pointer to
5206 // member function, no conversions apply. If the
5207 // template-argument represents a set of overloaded member
5208 // functions, the matching member function is selected from
5209 // the set (13.4).
5210 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005211 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005212 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005213
Douglas Gregor064fdb22010-04-14 23:11:21 +00005214 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005215 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005216 true,
5217 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005218 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005219 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005220
5221 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5222 ArgType = Arg->getType();
5223 } else
John Wiegley01296292011-04-08 18:41:53 +00005224 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005225 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005226
John Wiegley01296292011-04-08 18:41:53 +00005227 if (!ParamType->isMemberPointerType()) {
5228 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5229 ParamType,
5230 Arg, Converted))
5231 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005232 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005233 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005234
Douglas Gregor20fdef32012-04-10 17:08:25 +00005235 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5236 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005237 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005238 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005239 }
5240
Chris Lattner696197c2009-02-20 21:37:53 +00005241 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005242 // -- for a non-type template-parameter of type pointer to
5243 // object, qualification conversions (4.4) and the
5244 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005245 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005246 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005247 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005248
John Wiegley01296292011-04-08 18:41:53 +00005249 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5250 ParamType,
5251 Arg, Converted))
5252 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005253 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005254 }
Mike Stump11289f42009-09-09 15:08:12 +00005255
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005256 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005257 // -- For a non-type template-parameter of type reference to
5258 // object, no conversions apply. The type referred to by the
5259 // reference may be more cv-qualified than the (otherwise
5260 // identical) type of the template-argument. The
5261 // template-parameter is bound directly to the
5262 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005263 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005264 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005265
Douglas Gregor064fdb22010-04-14 23:11:21 +00005266 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005267 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5268 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005269 true,
5270 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005271 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005272 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005273
5274 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5275 ArgType = Arg->getType();
5276 } else
John Wiegley01296292011-04-08 18:41:53 +00005277 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005278 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005279
John Wiegley01296292011-04-08 18:41:53 +00005280 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5281 ParamType,
5282 Arg, Converted))
5283 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005284 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005285 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005286
Douglas Gregor20fdef32012-04-10 17:08:25 +00005287 // Deal with parameters of type std::nullptr_t.
5288 if (ParamType->isNullPtrType()) {
5289 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5290 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005291 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005292 }
5293
5294 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5295 case NPV_NotNullPointer:
5296 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5297 << Arg->getType() << ParamType;
5298 Diag(Param->getLocation(), diag::note_template_param_here);
5299 return ExprError();
5300
5301 case NPV_Error:
5302 return ExprError();
5303
5304 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005305 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005306 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5307 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005308 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005309 }
5310 }
5311
Douglas Gregor0e558532009-02-11 16:16:59 +00005312 // -- For a non-type template-parameter of type pointer to data
5313 // member, qualification conversions (4.4) are applied.
5314 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5315
Douglas Gregor20fdef32012-04-10 17:08:25 +00005316 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5317 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005318 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005319 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005320}
5321
5322/// \brief Check a template argument against its corresponding
5323/// template template parameter.
5324///
5325/// This routine implements the semantics of C++ [temp.arg.template].
5326/// It returns true if an error occurred, and false otherwise.
5327bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005328 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005329 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005330 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005331 TemplateDecl *Template = Name.getAsTemplateDecl();
5332 if (!Template) {
5333 // Any dependent template name is fine.
5334 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5335 return false;
5336 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005337
Richard Smith3f1b5d02011-05-05 21:57:07 +00005338 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005339 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005340 // the name of a class template or an alias template, expressed as an
5341 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005342 // primary class templates are considered when matching the
5343 // template template argument with the corresponding parameter;
5344 // partial specializations are not considered even if their
5345 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005346 //
5347 // Note that we also allow template template parameters here, which
5348 // will happen when we are dealing with, e.g., class template
5349 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005350 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005351 !isa<TemplateTemplateParmDecl>(Template) &&
5352 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005353 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005354 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005355 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005356 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005357 << Template;
5358 }
5359
Richard Smith1fde8ec2012-09-07 02:06:42 +00005360 TemplateParameterList *Params = Param->getTemplateParameters();
5361 if (Param->isExpandedParameterPack())
5362 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5363
Douglas Gregor85e0f662009-02-10 00:24:35 +00005364 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005365 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005366 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005367 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005368 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005369}
5370
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005371/// \brief Given a non-type template argument that refers to a
5372/// declaration and the type of its corresponding non-type template
5373/// parameter, produce an expression that properly refers to that
5374/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005375ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005376Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5377 QualType ParamType,
5378 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005379 // C++ [temp.param]p8:
5380 //
5381 // A non-type template-parameter of type "array of T" or
5382 // "function returning T" is adjusted to be of type "pointer to
5383 // T" or "pointer to function returning T", respectively.
5384 if (ParamType->isArrayType())
5385 ParamType = Context.getArrayDecayedType(ParamType);
5386 else if (ParamType->isFunctionType())
5387 ParamType = Context.getPointerType(ParamType);
5388
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005389 // For a NULL non-type template argument, return nullptr casted to the
5390 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005391 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005392 return ImpCastExprToType(
5393 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5394 ParamType,
5395 ParamType->getAs<MemberPointerType>()
5396 ? CK_NullToMemberPointer
5397 : CK_NullToPointer);
5398 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005399 assert(Arg.getKind() == TemplateArgument::Declaration &&
5400 "Only declaration template arguments permitted here");
5401
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005402 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5403
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005404 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005405 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5406 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005407 // If the value is a class member, we might have a pointer-to-member.
5408 // Determine whether the non-type template template parameter is of
5409 // pointer-to-member type. If so, we need to build an appropriate
5410 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5411 // would refer to the member itself.
5412 if (ParamType->isMemberPointerType()) {
5413 QualType ClassType
5414 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5415 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005416 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005417 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005418 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005419 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005420
5421 // The actual value-ness of this is unimportant, but for
5422 // internal consistency's sake, references to instance methods
5423 // are r-values.
5424 ExprValueKind VK = VK_LValue;
5425 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5426 VK = VK_RValue;
5427
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005428 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005429 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005430 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005431 Loc,
5432 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005433 if (RefExpr.isInvalid())
5434 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005435
John McCalle3027922010-08-25 11:45:40 +00005436 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005437
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005438 // We might need to perform a trailing qualification conversion, since
5439 // the element type on the parameter could be more qualified than the
5440 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005441 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005442 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005443 ParamType.getUnqualifiedType(), false,
5444 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005445 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005446
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005447 assert(!RefExpr.isInvalid() &&
5448 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005449 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005450 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005451 }
5452 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005453
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005454 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005455
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005456 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005457 // When the non-type template parameter is a pointer, take the
5458 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005459 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005460 if (RefExpr.isInvalid())
5461 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005462
5463 if (T->isFunctionType() || T->isArrayType()) {
5464 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005465 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005466 if (RefExpr.isInvalid())
5467 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005468
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005469 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005470 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005471
Douglas Gregorb242683d2010-04-01 18:32:35 +00005472 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005473 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005474 }
5475
John McCall7decc9e2010-11-18 06:31:45 +00005476 ExprValueKind VK = VK_RValue;
5477
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005478 // If the non-type template parameter has reference type, qualify the
5479 // resulting declaration reference with the extra qualifiers on the
5480 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005481 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5482 VK = VK_LValue;
5483 T = Context.getQualifiedType(T,
5484 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005485 } else if (isa<FunctionDecl>(VD)) {
5486 // References to functions are always lvalues.
5487 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005489
John McCall7decc9e2010-11-18 06:31:45 +00005490 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005491}
5492
5493/// \brief Construct a new expression that refers to the given
5494/// integral template argument with the given source-location
5495/// information.
5496///
5497/// This routine takes care of the mapping from an integral template
5498/// argument (which may have any integral type) to the appropriate
5499/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005500ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005501Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5502 SourceLocation Loc) {
5503 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005504 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005505 QualType OrigT = Arg.getIntegralType();
5506
5507 // If this is an enum type that we're instantiating, we need to use an integer
5508 // type the same size as the enumerator. We don't want to build an
5509 // IntegerLiteral with enum type. The integer type of an enum type can be of
5510 // any integral type with C++11 enum classes, make sure we create the right
5511 // type of literal for it.
5512 QualType T = OrigT;
5513 if (const EnumType *ET = OrigT->getAs<EnumType>())
5514 T = ET->getDecl()->getIntegerType();
5515
5516 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005517 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005518 // This does not need to handle u8 character literals because those are
5519 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005520 CharacterLiteral::CharacterKind Kind;
5521 if (T->isWideCharType())
5522 Kind = CharacterLiteral::Wide;
5523 else if (T->isChar16Type())
5524 Kind = CharacterLiteral::UTF16;
5525 else if (T->isChar32Type())
5526 Kind = CharacterLiteral::UTF32;
5527 else
5528 Kind = CharacterLiteral::Ascii;
5529
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005530 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5531 Kind, T, Loc);
5532 } else if (T->isBooleanType()) {
5533 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5534 T, Loc);
5535 } else if (T->isNullPtrType()) {
5536 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5537 } else {
5538 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005539 }
5540
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005541 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005542 // FIXME: This is a hack. We need a better way to handle substituted
5543 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005544 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5545 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005546 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005547 Loc, Loc);
5548 }
5549
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005550 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005551}
5552
Douglas Gregor641040a2011-01-12 23:45:44 +00005553/// \brief Match two template parameters within template parameter lists.
5554static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5555 bool Complain,
5556 Sema::TemplateParameterListEqualKind Kind,
5557 SourceLocation TemplateArgLoc) {
5558 // Check the actual kind (type, non-type, template).
5559 if (Old->getKind() != New->getKind()) {
5560 if (Complain) {
5561 unsigned NextDiag = diag::err_template_param_different_kind;
5562 if (TemplateArgLoc.isValid()) {
5563 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5564 NextDiag = diag::note_template_param_different_kind;
5565 }
5566 S.Diag(New->getLocation(), NextDiag)
5567 << (Kind != Sema::TPL_TemplateMatch);
5568 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5569 << (Kind != Sema::TPL_TemplateMatch);
5570 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005571
Douglas Gregor641040a2011-01-12 23:45:44 +00005572 return false;
5573 }
5574
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005575 // Check that both are parameter packs are neither are parameter packs.
5576 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005577 // template template parameter, the template template parameter can have
5578 // a parameter pack where the template template argument does not.
5579 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5580 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5581 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005582 if (Complain) {
5583 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5584 if (TemplateArgLoc.isValid()) {
5585 S.Diag(TemplateArgLoc,
5586 diag::err_template_arg_template_params_mismatch);
5587 NextDiag = diag::note_template_parameter_pack_non_pack;
5588 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005589
Douglas Gregor641040a2011-01-12 23:45:44 +00005590 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5591 : isa<NonTypeTemplateParmDecl>(New)? 1
5592 : 2;
5593 S.Diag(New->getLocation(), NextDiag)
5594 << ParamKind << New->isParameterPack();
5595 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5596 << ParamKind << Old->isParameterPack();
5597 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005598
Douglas Gregor641040a2011-01-12 23:45:44 +00005599 return false;
5600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005601
Douglas Gregor641040a2011-01-12 23:45:44 +00005602 // For non-type template parameters, check the type of the parameter.
5603 if (NonTypeTemplateParmDecl *OldNTTP
5604 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5605 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005606
Douglas Gregor641040a2011-01-12 23:45:44 +00005607 // If we are matching a template template argument to a template
5608 // template parameter and one of the non-type template parameter types
5609 // is dependent, then we must wait until template instantiation time
5610 // to actually compare the arguments.
5611 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5612 (OldNTTP->getType()->isDependentType() ||
5613 NewNTTP->getType()->isDependentType()))
5614 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005615
Douglas Gregor641040a2011-01-12 23:45:44 +00005616 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5617 if (Complain) {
5618 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5619 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005620 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005621 diag::err_template_arg_template_params_mismatch);
5622 NextDiag = diag::note_template_nontype_parm_different_type;
5623 }
5624 S.Diag(NewNTTP->getLocation(), NextDiag)
5625 << NewNTTP->getType()
5626 << (Kind != Sema::TPL_TemplateMatch);
5627 S.Diag(OldNTTP->getLocation(),
5628 diag::note_template_nontype_parm_prev_declaration)
5629 << OldNTTP->getType();
5630 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005631
Douglas Gregor641040a2011-01-12 23:45:44 +00005632 return false;
5633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005634
Douglas Gregor641040a2011-01-12 23:45:44 +00005635 return true;
5636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005637
Douglas Gregor641040a2011-01-12 23:45:44 +00005638 // For template template parameters, check the template parameter types.
5639 // The template parameter lists of template template
5640 // parameters must agree.
5641 if (TemplateTemplateParmDecl *OldTTP
5642 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005643 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005644 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5645 OldTTP->getTemplateParameters(),
5646 Complain,
5647 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005648 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005649 : Kind),
5650 TemplateArgLoc);
5651 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005652
Douglas Gregor641040a2011-01-12 23:45:44 +00005653 return true;
5654}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005655
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005656/// \brief Diagnose a known arity mismatch when comparing template argument
5657/// lists.
5658static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005659void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005660 TemplateParameterList *New,
5661 TemplateParameterList *Old,
5662 Sema::TemplateParameterListEqualKind Kind,
5663 SourceLocation TemplateArgLoc) {
5664 unsigned NextDiag = diag::err_template_param_list_different_arity;
5665 if (TemplateArgLoc.isValid()) {
5666 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5667 NextDiag = diag::note_template_param_list_different_arity;
5668 }
5669 S.Diag(New->getTemplateLoc(), NextDiag)
5670 << (New->size() > Old->size())
5671 << (Kind != Sema::TPL_TemplateMatch)
5672 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5673 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5674 << (Kind != Sema::TPL_TemplateMatch)
5675 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5676}
5677
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005678/// \brief Determine whether the given template parameter lists are
5679/// equivalent.
5680///
Mike Stump11289f42009-09-09 15:08:12 +00005681/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005682/// source code as part of a new template declaration.
5683///
5684/// \param Old The old template parameter list, typically found via
5685/// name lookup of the template declared with this template parameter
5686/// list.
5687///
5688/// \param Complain If true, this routine will produce a diagnostic if
5689/// the template parameter lists are not equivalent.
5690///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005691/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005692///
5693/// \param TemplateArgLoc If this source location is valid, then we
5694/// are actually checking the template parameter list of a template
5695/// argument (New) against the template parameter list of its
5696/// corresponding template template parameter (Old). We produce
5697/// slightly different diagnostics in this scenario.
5698///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005699/// \returns True if the template parameter lists are equal, false
5700/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005701bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005702Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5703 TemplateParameterList *Old,
5704 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005705 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005706 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005707 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5708 if (Complain)
5709 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5710 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005711
5712 return false;
5713 }
5714
Douglas Gregor641040a2011-01-12 23:45:44 +00005715 // C++0x [temp.arg.template]p3:
5716 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005717 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005718 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005719 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005720 // template-parameter-list of P. [...]
5721 TemplateParameterList::iterator NewParm = New->begin();
5722 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005723 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005724 OldParmEnd = Old->end();
5725 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005726 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5727 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005728 if (NewParm == NewParmEnd) {
5729 if (Complain)
5730 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5731 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005732
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005733 return false;
5734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005735
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005736 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5737 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005738 return false;
5739
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005740 ++NewParm;
5741 continue;
5742 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005743
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005744 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005745 // [...] When P's template- parameter-list contains a template parameter
5746 // pack (14.5.3), the template parameter pack will match zero or more
5747 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005748 // template-parameter-list of A with the same type and form as the
5749 // template parameter pack in P (ignoring whether those template
5750 // parameters are template parameter packs).
5751 for (; NewParm != NewParmEnd; ++NewParm) {
5752 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5753 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005754 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005755 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005756 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005757
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005758 // Make sure we exhausted all of the arguments.
5759 if (NewParm != NewParmEnd) {
5760 if (Complain)
5761 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5762 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005763
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005764 return false;
5765 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005766
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005767 return true;
5768}
5769
5770/// \brief Check whether a template can be declared within this scope.
5771///
5772/// If the template declaration is valid in this scope, returns
5773/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005774bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005775Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005776 if (!S)
5777 return false;
5778
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005779 // Find the nearest enclosing declaration scope.
5780 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5781 (S->getFlags() & Scope::TemplateParamScope) != 0)
5782 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005783
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005784 // C++ [temp]p4:
5785 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005786 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005787 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005788 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005789 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005790
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005791 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005792 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005793
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005794 // C++ [temp]p2:
5795 // A template-declaration can appear only as a namespace scope or
5796 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005797 if (Ctx) {
5798 if (Ctx->isFileContext())
5799 return false;
5800 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5801 // C++ [temp.mem]p2:
5802 // A local class shall not have member templates.
5803 if (RD->isLocalClass())
5804 return Diag(TemplateParams->getTemplateLoc(),
5805 diag::err_template_inside_local_class)
5806 << TemplateParams->getSourceRange();
5807 else
5808 return false;
5809 }
5810 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005811
Mike Stump11289f42009-09-09 15:08:12 +00005812 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005813 diag::err_template_outside_namespace_or_class_scope)
5814 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005815}
Douglas Gregor67a65642009-02-17 23:15:12 +00005816
Douglas Gregor54888652009-10-07 00:13:32 +00005817/// \brief Determine what kind of template specialization the given declaration
5818/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005819static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005820 if (!D)
5821 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005822
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005823 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5824 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005825 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5826 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005827 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5828 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005829
Douglas Gregor54888652009-10-07 00:13:32 +00005830 return TSK_Undeclared;
5831}
5832
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005833/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005834/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005835///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005836/// This routine determines whether a template specialization can be declared
5837/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005838///
5839/// \param S the semantic analysis object for which this check is being
5840/// performed.
5841///
5842/// \param Specialized the entity being specialized or instantiated, which
5843/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005844/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005845/// member class).
5846///
5847/// \param PrevDecl the previous declaration of this entity, if any.
5848///
5849/// \param Loc the location of the explicit specialization or instantiation of
5850/// this entity.
5851///
5852/// \param IsPartialSpecialization whether this is a partial specialization of
5853/// a class template.
5854///
Douglas Gregor54888652009-10-07 00:13:32 +00005855/// \returns true if there was an error that we cannot recover from, false
5856/// otherwise.
5857static bool CheckTemplateSpecializationScope(Sema &S,
5858 NamedDecl *Specialized,
5859 NamedDecl *PrevDecl,
5860 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005861 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005862 // Keep these "kind" numbers in sync with the %select statements in the
5863 // various diagnostics emitted by this routine.
5864 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005865 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005866 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005867 else if (isa<VarTemplateDecl>(Specialized))
5868 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005869 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005870 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005871 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005872 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005873 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005874 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005875 else if (isa<RecordDecl>(Specialized))
5876 EntityKind = 7;
5877 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5878 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005879 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005880 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005881 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005882 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005883 return true;
5884 }
5885
Douglas Gregorf47b9112009-02-25 22:02:03 +00005886 // C++ [temp.expl.spec]p2:
5887 // An explicit specialization shall be declared in the namespace
5888 // of which the template is a member, or, for member templates, in
5889 // the namespace of which the enclosing class or enclosing class
5890 // template is a member. An explicit specialization of a member
5891 // function, member class or static data member of a class
5892 // template shall be declared in the namespace of which the class
5893 // template is a member. Such a declaration may also be a
5894 // definition. If the declaration is not a definition, the
5895 // specialization may be defined later in the name- space in which
5896 // the explicit specialization was declared, or in a namespace
5897 // that encloses the one in which the explicit specialization was
5898 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005899 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005900 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005901 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005902 return true;
5903 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005904
Douglas Gregor40fb7442009-10-07 17:30:37 +00005905 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005906 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005907 // Do not warn for class scope explicit specialization during
5908 // instantiation, warning was already emitted during pattern
5909 // semantic analysis.
5910 if (!S.ActiveTemplateInstantiations.size())
5911 S.Diag(Loc, diag::ext_function_specialization_in_class)
5912 << Specialized;
5913 } else {
5914 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5915 << Specialized;
5916 return true;
5917 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005918 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005919
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005920 if (S.CurContext->isRecord() &&
5921 !S.CurContext->Equals(Specialized->getDeclContext())) {
5922 // Make sure that we're specializing in the right record context.
5923 // Otherwise, things can go horribly wrong.
5924 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5925 << Specialized;
5926 return true;
5927 }
5928
Douglas Gregore4b05162009-10-07 17:21:34 +00005929 // C++ [temp.class.spec]p6:
5930 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005931 // in any namespace scope in which its definition may be defined (14.5.1
5932 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005933 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005934 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005935 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005936
5937 // Make sure that this redeclaration (or definition) occurs in an enclosing
5938 // namespace.
5939 // Note that HandleDeclarator() performs this check for explicit
5940 // specializations of function templates, static data members, and member
5941 // functions, so we skip the check here for those kinds of entities.
5942 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5943 // Should we refactor that check, so that it occurs later?
5944 if (!DC->Encloses(SpecializedContext) &&
5945 !(isa<FunctionTemplateDecl>(Specialized) ||
5946 isa<FunctionDecl>(Specialized) ||
5947 isa<VarTemplateDecl>(Specialized) ||
5948 isa<VarDecl>(Specialized))) {
5949 if (isa<TranslationUnitDecl>(SpecializedContext))
5950 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5951 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00005952 else if (isa<NamespaceDecl>(SpecializedContext)) {
5953 int Diag = diag::err_template_spec_redecl_out_of_scope;
5954 if (S.getLangOpts().MicrosoftExt)
5955 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5956 S.Diag(Loc, Diag) << EntityKind << Specialized
5957 << cast<NamedDecl>(SpecializedContext);
5958 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00005959 llvm_unreachable("unexpected namespace context for specialization");
5960
5961 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5962 } else if ((!PrevDecl ||
5963 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5964 getTemplateSpecializationKind(PrevDecl) ==
5965 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005966 // C++ [temp.exp.spec]p2:
5967 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005968 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005969 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005970 // An explicit specialization of a member function, member class or
5971 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005972 // namespace of which the class template is a member.
5973 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005974 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005975 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005976 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005977 // C++11 [temp.explicit]p3:
5978 // An explicit instantiation shall appear in an enclosing namespace of its
5979 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005980 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005981 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005982 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005983 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005984 "DC encloses TU but isn't in enclosing namespace set");
5985 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005986 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005987 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5988 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005989 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005990 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005991 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005992 Diag = diag::ext_template_spec_decl_out_of_scope;
5993 else
5994 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5995 S.Diag(Loc, Diag)
5996 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5997 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005998
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005999 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006000 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006002
Douglas Gregorf47b9112009-02-25 22:02:03 +00006003 return false;
6004}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006005
Richard Smith6056d5e2014-02-09 00:54:43 +00006006static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
6007 if (!E->isInstantiationDependent())
6008 return SourceLocation();
6009 DependencyChecker Checker(Depth);
6010 Checker.TraverseStmt(E);
6011 if (Checker.Match && Checker.MatchLoc.isInvalid())
6012 return E->getSourceRange();
6013 return Checker.MatchLoc;
6014}
6015
6016static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6017 if (!TL.getType()->isDependentType())
6018 return SourceLocation();
6019 DependencyChecker Checker(Depth);
6020 Checker.TraverseTypeLoc(TL);
6021 if (Checker.Match && Checker.MatchLoc.isInvalid())
6022 return TL.getSourceRange();
6023 return Checker.MatchLoc;
6024}
6025
Larisse Voufo39a1e502013-08-06 01:03:05 +00006026/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006027/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006028static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006029 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6030 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006031 for (unsigned I = 0; I != NumArgs; ++I) {
6032 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006033 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006034 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6035 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006036 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006037
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006038 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006039 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006040
Eli Friedmanb826a002012-09-26 02:36:12 +00006041 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006042 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006043
6044 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006045
Douglas Gregor98318c22011-01-03 21:37:45 +00006046 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006047 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6048 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006049
6050 // Strip off any implicit casts we added as part of type checking.
6051 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6052 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006053
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006054 // C++ [temp.class.spec]p8:
6055 // A non-type argument is non-specialized if it is the name of a
6056 // non-type parameter. All other non-type arguments are
6057 // specialized.
6058 //
6059 // Below, we check the two conditions that only apply to
6060 // specialized non-type arguments, so skip any non-specialized
6061 // arguments.
6062 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006063 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006064 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006065
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006066 // C++ [temp.class.spec]p9:
6067 // Within the argument list of a class template partial
6068 // specialization, the following restrictions apply:
6069 // -- A partially specialized non-type argument expression
6070 // shall not involve a template parameter of the partial
6071 // specialization except when the argument expression is a
6072 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006073 SourceRange ParamUseRange =
6074 findTemplateParameter(Param->getDepth(), ArgExpr);
6075 if (ParamUseRange.isValid()) {
6076 if (IsDefaultArgument) {
6077 S.Diag(TemplateNameLoc,
6078 diag::err_dependent_non_type_arg_in_partial_spec);
6079 S.Diag(ParamUseRange.getBegin(),
6080 diag::note_dependent_non_type_default_arg_in_partial_spec)
6081 << ParamUseRange;
6082 } else {
6083 S.Diag(ParamUseRange.getBegin(),
6084 diag::err_dependent_non_type_arg_in_partial_spec)
6085 << ParamUseRange;
6086 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006087 return true;
6088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006089
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006090 // -- The type of a template parameter corresponding to a
6091 // specialized non-type argument shall not be dependent on a
6092 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006093 //
6094 // FIXME: We need to delay this check until instantiation in some cases:
6095 //
6096 // template<template<typename> class X> struct A {
6097 // template<typename T, X<T> N> struct B;
6098 // template<typename T> struct B<T, 0>;
6099 // };
6100 // template<typename> using X = int;
6101 // A<X>::B<int, 0> b;
6102 ParamUseRange = findTemplateParameter(
6103 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6104 if (ParamUseRange.isValid()) {
6105 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6106 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6107 << Param->getType() << ParamUseRange;
6108 S.Diag(Param->getLocation(), diag::note_template_param_here)
6109 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006110 return true;
6111 }
6112 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006113
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006114 return false;
6115}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006116
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006117/// \brief Check the non-type template arguments of a class template
6118/// partial specialization according to C++ [temp.class.spec]p9.
6119///
Richard Smith6056d5e2014-02-09 00:54:43 +00006120/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006121/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006122/// template.
6123/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006124/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006125/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006126///
Richard Smith6056d5e2014-02-09 00:54:43 +00006127/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006128static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006129 Sema &S, SourceLocation TemplateNameLoc,
6130 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006131 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006132 const TemplateArgument *ArgList = TemplateArgs.data();
6133
6134 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6135 NonTypeTemplateParmDecl *Param
6136 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6137 if (!Param)
6138 continue;
6139
Richard Smith6056d5e2014-02-09 00:54:43 +00006140 if (CheckNonTypeTemplatePartialSpecializationArgs(
6141 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006142 return true;
6143 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006144
6145 return false;
6146}
6147
John McCall48871652010-08-21 09:40:31 +00006148DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006149Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6150 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006151 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006152 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006153 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006154 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006155 MultiTemplateParamsArg
6156 TemplateParameterLists,
6157 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006158 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006159
Richard Smith4b55a9c2014-04-17 03:29:33 +00006160 CXXScopeSpec &SS = TemplateId.SS;
6161
Abramo Bagnara60804e12011-03-18 15:16:37 +00006162 // NOTE: KWLoc is the location of the tag keyword. This will instead
6163 // store the location of the outermost template keyword in the declaration.
6164 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006165 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6166 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6167 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6168 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006169
Douglas Gregor67a65642009-02-17 23:15:12 +00006170 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006171 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006172 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006173 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6174
6175 if (!ClassTemplate) {
6176 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006177 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006178 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6179 return true;
6180 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006181
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006182 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006183 bool isPartialSpecialization = false;
6184
Douglas Gregorf47b9112009-02-25 22:02:03 +00006185 // Check the validity of the template headers that introduce this
6186 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006187 // FIXME: We probably shouldn't complain about these headers for
6188 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006189 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006190 TemplateParameterList *TemplateParams =
6191 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006192 KWLoc, TemplateNameLoc, SS, &TemplateId,
6193 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6194 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006195 if (Invalid)
6196 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006197
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006198 if (TemplateParams && TemplateParams->size() > 0) {
6199 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006200
Douglas Gregorec9518b2010-12-21 08:14:57 +00006201 if (TUK == TUK_Friend) {
6202 Diag(KWLoc, diag::err_partial_specialization_friend)
6203 << SourceRange(LAngleLoc, RAngleLoc);
6204 return true;
6205 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006206
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006207 // C++ [temp.class.spec]p10:
6208 // The template parameter list of a specialization shall not
6209 // contain default template argument values.
6210 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6211 Decl *Param = TemplateParams->getParam(I);
6212 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6213 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006214 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006215 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006216 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006217 }
6218 } else if (NonTypeTemplateParmDecl *NTTP
6219 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6220 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006221 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006222 diag::err_default_arg_in_partial_spec)
6223 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006224 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006225 }
6226 } else {
6227 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006228 if (TTP->hasDefaultArgument()) {
6229 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006230 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006231 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006232 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006233 }
6234 }
6235 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006236 } else if (TemplateParams) {
6237 if (TUK == TUK_Friend)
6238 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006239 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006240 SourceRange(TemplateParams->getTemplateLoc(),
6241 TemplateParams->getRAngleLoc()))
6242 << SourceRange(LAngleLoc, RAngleLoc);
6243 else
6244 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006245 } else {
6246 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006247 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006248
Douglas Gregor67a65642009-02-17 23:15:12 +00006249 // Check that the specialization uses the same tag kind as the
6250 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006251 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6252 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006253 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006254 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006255 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006256 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006257 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006258 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006259 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006260 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006261 diag::note_previous_use);
6262 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6263 }
6264
Douglas Gregorc40290e2009-03-09 23:48:35 +00006265 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006266 TemplateArgumentListInfo TemplateArgs =
6267 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006268
Douglas Gregor14406932011-01-03 20:35:03 +00006269 // Check for unexpanded parameter packs in any of the template arguments.
6270 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006271 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006272 UPPC_PartialSpecialization))
6273 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006274
Douglas Gregor67a65642009-02-17 23:15:12 +00006275 // Check that the template argument list is well-formed for this
6276 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006277 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006278 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6279 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006280 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006281
Douglas Gregor2373c592009-05-31 09:31:02 +00006282 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006283 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006284 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006285 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006286 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6287 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006288 return true;
6289
Douglas Gregor678d76c2011-07-01 01:22:09 +00006290 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006291 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006292 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006293 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006294 TemplateArgs.size(),
6295 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006296 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6297 << ClassTemplate->getDeclName();
6298 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006299 }
6300 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006301
Craig Topperc3ec1492014-05-26 06:22:03 +00006302 void *InsertPos = nullptr;
6303 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006304
6305 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006306 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006307 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006308 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006309 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006310
Craig Topperc3ec1492014-05-26 06:22:03 +00006311 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006312
Douglas Gregorf47b9112009-02-25 22:02:03 +00006313 // Check whether we can declare a class template specialization in
6314 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006315 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006316 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6317 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006318 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006319 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006320
Douglas Gregor15301382009-07-30 17:40:51 +00006321 // The canonical type
6322 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006323 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006324 // Build the canonical type that describes the converted template
6325 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006326 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6327 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006328 Converted.data(),
6329 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006330
6331 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006332 ClassTemplate->getInjectedClassNameSpecialization())) {
6333 // C++ [temp.class.spec]p9b3:
6334 //
6335 // -- The argument list of the specialization shall not be identical
6336 // to the implicit argument list of the primary template.
6337 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006338 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006339 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006340 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6341 ClassTemplate->getIdentifier(),
6342 TemplateNameLoc,
6343 Attr,
6344 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006345 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006346 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006347 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006348 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006349 }
Douglas Gregor15301382009-07-30 17:40:51 +00006350
Douglas Gregor2373c592009-05-31 09:31:02 +00006351 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006352 ClassTemplatePartialSpecializationDecl *PrevPartial
6353 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006354 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006355 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006356 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006357 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006358 TemplateParams,
6359 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006360 Converted.data(),
6361 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006362 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006363 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006364 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006365 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006366 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006367 Partial->setTemplateParameterListsInfo(
6368 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006369 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006370
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006371 if (!PrevPartial)
6372 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006373 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006374
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006375 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006376 // template specialization, make a note of that.
6377 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6378 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006379
Douglas Gregor91772d12009-06-13 00:26:55 +00006380 // Check that all of the template parameters of the class template
6381 // partial specialization are deducible from the template
6382 // arguments. If not, this class template partial specialization
6383 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006384 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006385 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006386 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006387 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006388
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006389 if (!DeducibleParams.all()) {
6390 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006391 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006392 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006393 << SourceRange(TemplateNameLoc, RAngleLoc);
6394 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6395 if (!DeducibleParams[I]) {
6396 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6397 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006398 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006399 diag::note_partial_spec_unused_parameter)
6400 << Param->getDeclName();
6401 else
Mike Stump11289f42009-09-09 15:08:12 +00006402 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006403 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006404 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006405 }
6406 }
6407 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006408 } else {
6409 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006410 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006411 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006412 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006413 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006414 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006415 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006416 Converted.data(),
6417 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006418 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006419 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006420 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006421 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006422 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006423 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006424
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006425 if (!PrevDecl)
6426 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006427
David Majnemer678f50b2015-11-18 19:49:19 +00006428 if (CurContext->isDependentContext()) {
6429 // -fms-extensions permits specialization of nested classes without
6430 // fully specializing the outer class(es).
6431 assert(getLangOpts().MicrosoftExt &&
6432 "Only possible with -fms-extensions!");
6433 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6434 CanonType = Context.getTemplateSpecializationType(
6435 CanonTemplate, Converted.data(), Converted.size());
6436 } else {
6437 CanonType = Context.getTypeDeclType(Specialization);
6438 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006439 }
6440
Douglas Gregor06db9f52009-10-12 20:18:28 +00006441 // C++ [temp.expl.spec]p6:
6442 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006443 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006444 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006445 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006446 // use occurs; no diagnostic is required.
6447 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006448 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006449 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006450 // Is there any previous explicit specialization declaration?
6451 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6452 Okay = true;
6453 break;
6454 }
6455 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006456
Douglas Gregorc854c662010-02-26 06:03:23 +00006457 if (!Okay) {
6458 SourceRange Range(TemplateNameLoc, RAngleLoc);
6459 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6460 << Context.getTypeDeclType(Specialization) << Range;
6461
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006462 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006463 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006464 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006465 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006466 return true;
6467 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006468 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006469
Douglas Gregor2208a292009-09-26 20:57:03 +00006470 // If this is not a friend, note that this is an explicit specialization.
6471 if (TUK != TUK_Friend)
6472 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006473
6474 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006475 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006476 RecordDecl *Def = Specialization->getDefinition();
6477 NamedDecl *Hidden = nullptr;
6478 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6479 SkipBody->ShouldSkip = true;
6480 makeMergedDefinitionVisible(Hidden, KWLoc);
6481 // From here on out, treat this as just a redeclaration.
6482 TUK = TUK_Declaration;
6483 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006484 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006485 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006486 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006487 Diag(Def->getLocation(), diag::note_previous_definition);
6488 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006489 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006490 }
6491 }
6492
John McCall659a3372010-12-18 03:30:47 +00006493 if (Attr)
6494 ProcessDeclAttributeList(S, Specialization, Attr);
6495
Richard Smith034b94a2012-08-17 03:20:55 +00006496 // Add alignment attributes if necessary; these attributes are checked when
6497 // the ASTContext lays out the structure.
6498 if (TUK == TUK_Definition) {
6499 AddAlignmentAttributesForRecord(Specialization);
6500 AddMsStructLayoutForRecord(Specialization);
6501 }
6502
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006503 if (ModulePrivateLoc.isValid())
6504 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6505 << (isPartialSpecialization? 1 : 0)
6506 << FixItHint::CreateRemoval(ModulePrivateLoc);
6507
Douglas Gregord56a91e2009-02-26 22:19:44 +00006508 // Build the fully-sugared type for this class template
6509 // specialization as the user wrote in the specialization
6510 // itself. This means that we'll pretty-print the type retrieved
6511 // from the specialization's declaration the way that the user
6512 // actually wrote the specialization, rather than formatting the
6513 // name based on the "canonical" representation used to store the
6514 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006515 TypeSourceInfo *WrittenTy
6516 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6517 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006518 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006519 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006520 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006521 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006522
Douglas Gregor1e249f82009-02-25 22:18:32 +00006523 // C++ [temp.expl.spec]p9:
6524 // A template explicit specialization is in the scope of the
6525 // namespace in which the template was defined.
6526 //
6527 // We actually implement this paragraph where we set the semantic
6528 // context (in the creation of the ClassTemplateSpecializationDecl),
6529 // but we also maintain the lexical context where the actual
6530 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006531 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006532
Douglas Gregor67a65642009-02-17 23:15:12 +00006533 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006534 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006535 Specialization->startDefinition();
6536
Douglas Gregor2208a292009-09-26 20:57:03 +00006537 if (TUK == TUK_Friend) {
6538 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6539 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006540 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006541 /*FIXME:*/KWLoc);
6542 Friend->setAccess(AS_public);
6543 CurContext->addDecl(Friend);
6544 } else {
6545 // Add the specialization into its lexical context, so that it can
6546 // be seen when iterating through the list of declarations in that
6547 // context. However, specializations are not found by name lookup.
6548 CurContext->addDecl(Specialization);
6549 }
John McCall48871652010-08-21 09:40:31 +00006550 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006551}
Douglas Gregor333489b2009-03-27 23:10:48 +00006552
John McCall48871652010-08-21 09:40:31 +00006553Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006554 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006555 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006556 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006557 ActOnDocumentableDecl(NewDecl);
6558 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006559}
6560
John McCall4f7ced62010-02-11 01:33:53 +00006561/// \brief Strips various properties off an implicit instantiation
6562/// that has just been explicitly specialized.
6563static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006564 D->dropAttr<DLLImportAttr>();
6565 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006566
Nico Webere4974382014-12-19 23:52:45 +00006567 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006568 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006569}
6570
Nico Webera8f80b32012-01-09 19:52:25 +00006571/// \brief Compute the diagnostic location for an explicit instantiation
6572// declaration or definition.
6573static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006574 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006575 // Explicit instantiations following a specialization have no effect and
6576 // hence no PointOfInstantiation. In that case, walk decl backwards
6577 // until a valid name loc is found.
6578 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006579 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6580 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006581 PrevDiagLoc = Prev->getLocation();
6582 }
6583 assert(PrevDiagLoc.isValid() &&
6584 "Explicit instantiation without point of instantiation?");
6585 return PrevDiagLoc;
6586}
6587
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006588/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006589/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006590/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006591/// new specialization/instantiation will have any effect.
6592///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006593/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006594/// instantiation.
6595///
6596/// \param NewTSK the kind of the new explicit specialization or instantiation.
6597///
6598/// \param PrevDecl the previous declaration of the entity.
6599///
6600/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6601///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006602/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006603/// declaration was instantiated (either implicitly or explicitly).
6604///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006605/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006606/// specialization or instantiation has no effect and should be ignored.
6607///
6608/// \returns true if there was an error that should prevent the introduction of
6609/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006610bool
6611Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6612 TemplateSpecializationKind NewTSK,
6613 NamedDecl *PrevDecl,
6614 TemplateSpecializationKind PrevTSK,
6615 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006616 bool &HasNoEffect) {
6617 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006618
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006619 switch (NewTSK) {
6620 case TSK_Undeclared:
6621 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006622 assert(
6623 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6624 "previous declaration must be implicit!");
6625 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006626
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006627 case TSK_ExplicitSpecialization:
6628 switch (PrevTSK) {
6629 case TSK_Undeclared:
6630 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006631 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006632 // explicitly specialized or has merely been mentioned without any
6633 // instantiation.
6634 return false;
6635
6636 case TSK_ImplicitInstantiation:
6637 if (PrevPointOfInstantiation.isInvalid()) {
6638 // The declaration itself has not actually been instantiated, so it is
6639 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006640 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006641 return false;
6642 }
6643 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006644
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006645 case TSK_ExplicitInstantiationDeclaration:
6646 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006647 assert((PrevTSK == TSK_ImplicitInstantiation ||
6648 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006649 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006650
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006651 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006652 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006653 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006654 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006655 // implicit instantiation to take place, in every translation unit in
6656 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006657 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006658 // Is there any previous explicit specialization declaration?
6659 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6660 return false;
6661 }
6662
Douglas Gregor1d957a32009-10-27 18:42:08 +00006663 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006664 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006665 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006666 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006667
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006668 return true;
6669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006670
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006671 case TSK_ExplicitInstantiationDeclaration:
6672 switch (PrevTSK) {
6673 case TSK_ExplicitInstantiationDeclaration:
6674 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006675 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006676 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006677
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006678 case TSK_Undeclared:
6679 case TSK_ImplicitInstantiation:
6680 // We're explicitly instantiating something that may have already been
6681 // implicitly instantiated; that's fine.
6682 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006683
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006684 case TSK_ExplicitSpecialization:
6685 // C++0x [temp.explicit]p4:
6686 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006687 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006688 // specialization for that template, the explicit instantiation has no
6689 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006690 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006691 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006692
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006693 case TSK_ExplicitInstantiationDefinition:
6694 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006695 // If an entity is the subject of both an explicit instantiation
6696 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006697 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006698 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006699 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006700
6701 // Explicit instantiations following a specialization have no effect and
6702 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6703 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006704 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6705 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006706 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006707 return false;
6708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006709
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006710 case TSK_ExplicitInstantiationDefinition:
6711 switch (PrevTSK) {
6712 case TSK_Undeclared:
6713 case TSK_ImplicitInstantiation:
6714 // We're explicitly instantiating something that may have already been
6715 // implicitly instantiated; that's fine.
6716 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006717
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006718 case TSK_ExplicitSpecialization:
6719 // C++ DR 259, C++0x [temp.explicit]p4:
6720 // For a given set of template parameters, if an explicit
6721 // instantiation of a template appears after a declaration of
6722 // an explicit specialization for that template, the explicit
6723 // instantiation has no effect.
6724 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006725 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006726 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006727 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006728 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006729 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6730 diag::ext_explicit_instantiation_after_specialization)
6731 << PrevDecl;
6732 Diag(PrevDecl->getLocation(),
6733 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006734 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006735 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006736
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006737 case TSK_ExplicitInstantiationDeclaration:
6738 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006739 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006740
6741 // C++0x [temp.explicit]p4:
6742 // For a given set of template parameters, if an explicit instantiation
6743 // of a template appears after a declaration of an explicit
6744 // specialization for that template, the explicit instantiation has no
6745 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006746 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006747 // Is there any previous explicit specialization declaration?
6748 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6749 HasNoEffect = true;
6750 break;
6751 }
6752 }
6753
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006754 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006755
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006756 case TSK_ExplicitInstantiationDefinition:
6757 // C++0x [temp.spec]p5:
6758 // For a given template and a given set of template-arguments,
6759 // - an explicit instantiation definition shall appear at most once
6760 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006761
6762 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6763 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006764 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006765 : diag::err_explicit_instantiation_duplicate)
6766 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006767 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006768 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006769 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006771 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006773
David Blaikie83d382b2011-09-23 05:06:16 +00006774 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006775}
6776
John McCallb9c78482010-04-08 09:05:18 +00006777/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006778/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006779///
James Dennettf14a6e52012-06-15 22:23:43 +00006780/// The only possible way to get a dependent function template specialization
6781/// is with a friend declaration, like so:
6782///
6783/// \code
6784/// template \<class T> void foo(T);
6785/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006786/// friend void foo<>(T);
6787/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006788/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006789///
6790/// There really isn't any useful analysis we can do here, so we
6791/// just store the information.
6792bool
6793Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6794 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6795 LookupResult &Previous) {
6796 // Remove anything from Previous that isn't a function template in
6797 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006798 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006799 LookupResult::Filter F = Previous.makeFilter();
6800 while (F.hasNext()) {
6801 NamedDecl *D = F.next()->getUnderlyingDecl();
6802 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006803 !FDLookupContext->InEnclosingNamespaceSetOf(
6804 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006805 F.erase();
6806 }
6807 F.done();
6808
6809 // Should this be diagnosed here?
6810 if (Previous.empty()) return true;
6811
6812 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6813 ExplicitTemplateArgs);
6814 return false;
6815}
6816
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006817/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006818/// specialization.
6819///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006820/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006821/// explicit function template specialization. On successful completion,
6822/// the function declaration \p FD will become a function template
6823/// specialization.
6824///
6825/// \param FD the function declaration, which will be updated to become a
6826/// function template specialization.
6827///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006828/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6829/// if any. Note that this may be valid info even when 0 arguments are
6830/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6831/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006832///
Francois Pichet3a44e432011-07-08 06:21:47 +00006833/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006834/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006835bool Sema::CheckFunctionTemplateSpecialization(
6836 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6837 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006838 // The set of function template specializations that could match this
6839 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006840 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006841 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6842 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006843
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006844 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6845 ConvertedTemplateArgs;
6846
Sebastian Redl50c68252010-08-31 00:36:30 +00006847 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006848 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6849 I != E; ++I) {
6850 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6851 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006852 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006853 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006854 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6855 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006856 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006857
Richard Smith574f4f62013-01-14 05:37:29 +00006858 // When matching a constexpr member function template specialization
6859 // against the primary template, we don't yet know whether the
6860 // specialization has an implicit 'const' (because we don't know whether
6861 // it will be a static member function until we know which template it
6862 // specializes), so adjust it now assuming it specializes this template.
6863 QualType FT = FD->getType();
6864 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006865 CXXMethodDecl *OldMD =
6866 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006867 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006868 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006869 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6870 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006871 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006872 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006873 }
6874 }
6875
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006876 TemplateArgumentListInfo Args;
6877 if (ExplicitTemplateArgs)
6878 Args = *ExplicitTemplateArgs;
6879
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006880 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006881 // A trailing template-argument can be left unspecified in the
6882 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006883 // provided it can be deduced from the function argument type.
6884 // Perform template argument deduction to determine whether we may be
6885 // specializing this template.
6886 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006887 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006888 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006889 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6890 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006891 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006892 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006893 // that we can provide nifty diagnostics.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006894 FailedCandidates.addCandidate()
6895 .set(FunTmpl->getTemplatedDecl(),
6896 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006897 (void)TDK;
6898 continue;
6899 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006900
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006901 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006902 if (ExplicitTemplateArgs)
6903 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00006904 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006905 }
6906 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006907
Douglas Gregor5de279c2009-09-26 03:41:46 +00006908 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006909 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006910 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006911 FD->getLocation(),
6912 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6913 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006914 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006915 PDiag(diag::note_function_template_spec_matched));
6916
John McCall58cc69d2010-01-27 01:50:18 +00006917 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006918 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006919
6920 // Ignore access information; it doesn't figure into redeclaration checking.
6921 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006922
6923 FunctionTemplateSpecializationInfo *SpecInfo
6924 = Specialization->getTemplateSpecializationInfo();
6925 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006926
6927 // Note: do not overwrite location info if previous template
6928 // specialization kind was explicit.
6929 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006930 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006931 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006932 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6933 // function can differ from the template declaration with respect to
6934 // the constexpr specifier.
6935 Specialization->setConstexpr(FD->isConstexpr());
6936 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006937
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006938 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006939 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006940
6941 // If this is a friend declaration, then we're not really declaring
6942 // an explicit specialization.
6943 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006944
Douglas Gregor54888652009-10-07 00:13:32 +00006945 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006946 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006947 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006948 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006949 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006950 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006951 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006952
6953 // C++ [temp.expl.spec]p6:
6954 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006955 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006956 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006957 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006958 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006959 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006960 if (!isFriend &&
6961 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006962 TSK_ExplicitSpecialization,
6963 Specialization,
6964 SpecInfo->getTemplateSpecializationKind(),
6965 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006966 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006967 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006968
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006969 // Mark the prior declaration as an explicit specialization, so that later
6970 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006971 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00006972 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006973 MarkUnusedFileScopedDecl(Specialization);
6974 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006975
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006976 // Turn the given function declaration into a function template
6977 // specialization, with the template arguments from the previous
6978 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006979 // Take copies of (semantic and syntactic) template argument lists.
6980 const TemplateArgumentList* TemplArgs = new (Context)
6981 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006982 FD->setFunctionTemplateSpecialization(
6983 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
6984 SpecInfo->getTemplateSpecializationKind(),
6985 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006986
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006987 // The "previous declaration" for this function template specialization is
6988 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00006989 Previous.clear();
6990 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006991 return false;
6992}
6993
Douglas Gregor86d142a2009-10-08 07:24:58 +00006994/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006995/// specialization.
6996///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006997/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006998/// explicit member function specialization. On successful completion,
6999/// the function declaration \p FD will become a member function
7000/// specialization.
7001///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007002/// \param Member the member declaration, which will be updated to become a
7003/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007004///
John McCall1f82f242009-11-18 22:49:29 +00007005/// \param Previous the set of declarations, one of which may be specialized
7006/// by this function specialization; the set will be modified to contain the
7007/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007008bool
John McCall1f82f242009-11-18 22:49:29 +00007009Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007010 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007011
Douglas Gregor86d142a2009-10-08 07:24:58 +00007012 // Try to find the member we are instantiating.
Craig Topperc3ec1492014-05-26 06:22:03 +00007013 NamedDecl *Instantiation = nullptr;
7014 NamedDecl *InstantiatedFrom = nullptr;
7015 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007016
John McCall1f82f242009-11-18 22:49:29 +00007017 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007018 // Nowhere to look anyway.
7019 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007020 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7021 I != E; ++I) {
7022 NamedDecl *D = (*I)->getUnderlyingDecl();
7023 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007024 QualType Adjusted = Function->getType();
7025 if (!hasExplicitCallingConv(Adjusted))
7026 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7027 if (Context.hasSameType(Adjusted, Method->getType())) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007028 Instantiation = Method;
7029 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007030 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007031 break;
7032 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007033 }
7034 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007035 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007036 VarDecl *PrevVar;
7037 if (Previous.isSingleResult() &&
7038 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007039 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00007040 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007041 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007042 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007043 }
7044 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007045 CXXRecordDecl *PrevRecord;
7046 if (Previous.isSingleResult() &&
7047 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
7048 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007049 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007050 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007051 }
Richard Smith7d137e32012-03-23 03:33:32 +00007052 } else if (isa<EnumDecl>(Member)) {
7053 EnumDecl *PrevEnum;
7054 if (Previous.isSingleResult() &&
7055 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
7056 Instantiation = PrevEnum;
7057 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7058 MSInfo = PrevEnum->getMemberSpecializationInfo();
7059 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007061
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007062 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007063 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007064 // specializations are always out-of-line, the caller will complain about
7065 // this mismatch later.
7066 return false;
7067 }
John McCalle820e5e2010-04-13 20:37:33 +00007068
7069 // If this is a friend, just bail out here before we start turning
7070 // things into explicit specializations.
7071 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7072 // Preserve instantiation information.
7073 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7074 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7075 cast<CXXMethodDecl>(InstantiatedFrom),
7076 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7077 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7078 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7079 cast<CXXRecordDecl>(InstantiatedFrom),
7080 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7081 }
7082
7083 Previous.clear();
7084 Previous.addDecl(Instantiation);
7085 return false;
7086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007087
Douglas Gregor86d142a2009-10-08 07:24:58 +00007088 // Make sure that this is a specialization of a member.
7089 if (!InstantiatedFrom) {
7090 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7091 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007092 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7093 return true;
7094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007095
Douglas Gregor06db9f52009-10-12 20:18:28 +00007096 // C++ [temp.expl.spec]p6:
7097 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007098 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007099 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007100 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007101 // use occurs; no diagnostic is required.
7102 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007103
Abramo Bagnara8075c852010-06-12 07:44:57 +00007104 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007105 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7106 TSK_ExplicitSpecialization,
7107 Instantiation,
7108 MSInfo->getTemplateSpecializationKind(),
7109 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007110 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007111 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007112
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007113 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007114 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007115 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007116 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007117 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007118 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007119
Douglas Gregor86d142a2009-10-08 07:24:58 +00007120 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007121 // the original declaration to note that it is an explicit specialization
7122 // (if it was previously an implicit instantiation). This latter step
7123 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007124 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007125 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7126 if (InstantiationFunction->getTemplateSpecializationKind() ==
7127 TSK_ImplicitInstantiation) {
7128 InstantiationFunction->setTemplateSpecializationKind(
7129 TSK_ExplicitSpecialization);
7130 InstantiationFunction->setLocation(Member->getLocation());
7131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007132
Douglas Gregor86d142a2009-10-08 07:24:58 +00007133 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7134 cast<CXXMethodDecl>(InstantiatedFrom),
7135 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007136 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007137 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007138 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7139 if (InstantiationVar->getTemplateSpecializationKind() ==
7140 TSK_ImplicitInstantiation) {
7141 InstantiationVar->setTemplateSpecializationKind(
7142 TSK_ExplicitSpecialization);
7143 InstantiationVar->setLocation(Member->getLocation());
7144 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007145
Larisse Voufo39a1e502013-08-06 01:03:05 +00007146 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7147 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007148 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007149 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007150 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7151 if (InstantiationClass->getTemplateSpecializationKind() ==
7152 TSK_ImplicitInstantiation) {
7153 InstantiationClass->setTemplateSpecializationKind(
7154 TSK_ExplicitSpecialization);
7155 InstantiationClass->setLocation(Member->getLocation());
7156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007157
Douglas Gregor86d142a2009-10-08 07:24:58 +00007158 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007159 cast<CXXRecordDecl>(InstantiatedFrom),
7160 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007161 } else {
7162 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7163 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7164 if (InstantiationEnum->getTemplateSpecializationKind() ==
7165 TSK_ImplicitInstantiation) {
7166 InstantiationEnum->setTemplateSpecializationKind(
7167 TSK_ExplicitSpecialization);
7168 InstantiationEnum->setLocation(Member->getLocation());
7169 }
7170
7171 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7172 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007174
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007175 // Save the caller the trouble of having to figure out which declaration
7176 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007177 Previous.clear();
7178 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007179 return false;
7180}
7181
Douglas Gregore47f5a72009-10-14 23:41:34 +00007182/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007183///
7184/// \returns true if a serious error occurs, false otherwise.
7185static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007186 SourceLocation InstLoc,
7187 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007188 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7189 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007190
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007191 if (CurContext->isRecord()) {
7192 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7193 << D;
7194 return true;
7195 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007196
Richard Smith050d2612011-10-18 02:28:33 +00007197 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007198 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007199 // template. If the name declared in the explicit instantiation is an
7200 // unqualified name, the explicit instantiation shall appear in the
7201 // namespace where its template is declared or, if that namespace is inline
7202 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007203 //
7204 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007205 if (WasQualifiedName) {
7206 if (CurContext->Encloses(OrigContext))
7207 return false;
7208 } else {
7209 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7210 return false;
7211 }
7212
7213 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7214 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007215 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007216 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007217 diag::err_explicit_instantiation_out_of_scope :
7218 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007219 << D << NS;
7220 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007221 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007222 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007223 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7224 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7225 << D << NS;
7226 } else
7227 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007228 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007229 diag::err_explicit_instantiation_must_be_global :
7230 diag::warn_explicit_instantiation_must_be_global_0x)
7231 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007232 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007233 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007234}
7235
7236/// \brief Determine whether the given scope specifier has a template-id in it.
7237static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7238 if (!SS.isSet())
7239 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007240
Richard Smith050d2612011-10-18 02:28:33 +00007241 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007242 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007243 // or a static data member of a class template specialization, the name of
7244 // the class template specialization in the qualified-id for the member
7245 // name shall be a simple-template-id.
7246 //
7247 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007248 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7249 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007250 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007251 if (isa<TemplateSpecializationType>(T))
7252 return true;
7253
7254 return false;
7255}
7256
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007257// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007258DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007259Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007260 SourceLocation ExternLoc,
7261 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007262 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007263 SourceLocation KWLoc,
7264 const CXXScopeSpec &SS,
7265 TemplateTy TemplateD,
7266 SourceLocation TemplateNameLoc,
7267 SourceLocation LAngleLoc,
7268 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007269 SourceLocation RAngleLoc,
7270 AttributeList *Attr) {
7271 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007272 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007273 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007274 // Check that the specialization uses the same tag kind as the
7275 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007276 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7277 assert(Kind != TTK_Enum &&
7278 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007279
7280 if (isa<TypeAliasTemplateDecl>(TD)) {
7281 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7282 Diag(TD->getTemplatedDecl()->getLocation(),
7283 diag::note_previous_use);
7284 return true;
7285 }
7286
7287 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7288
Douglas Gregord9034f02009-05-14 16:41:31 +00007289 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007290 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007291 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007292 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007293 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007294 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007295 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007296 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007297 diag::note_previous_use);
7298 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7299 }
7300
Douglas Gregore47f5a72009-10-14 23:41:34 +00007301 // C++0x [temp.explicit]p2:
7302 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007303 // definition and an explicit instantiation declaration. An explicit
7304 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007305 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7306 ? TSK_ExplicitInstantiationDefinition
7307 : TSK_ExplicitInstantiationDeclaration;
7308
7309 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7310 // Check for dllexport class template instantiation declarations.
7311 for (AttributeList *A = Attr; A; A = A->getNext()) {
7312 if (A->getKind() == AttributeList::AT_DLLExport) {
7313 Diag(ExternLoc,
7314 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7315 Diag(A->getLoc(), diag::note_attribute);
7316 break;
7317 }
7318 }
7319
7320 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7321 Diag(ExternLoc,
7322 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7323 Diag(A->getLocation(), diag::note_attribute);
7324 }
7325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007326
Douglas Gregora1f49972009-05-13 00:25:59 +00007327 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007328 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007329 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007330
7331 // Check that the template argument list is well-formed for this
7332 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007333 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007334 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7335 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007336 return true;
7337
Douglas Gregora1f49972009-05-13 00:25:59 +00007338 // Find the class template specialization declaration that
7339 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007340 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007341 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007342 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007343
Abramo Bagnara8075c852010-06-12 07:44:57 +00007344 TemplateSpecializationKind PrevDecl_TSK
7345 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7346
Douglas Gregor54888652009-10-07 00:13:32 +00007347 // C++0x [temp.explicit]p2:
7348 // [...] An explicit instantiation shall appear in an enclosing
7349 // namespace of its template. [...]
7350 //
7351 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007352 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7353 SS.isSet()))
7354 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007355
Craig Topperc3ec1492014-05-26 06:22:03 +00007356 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007357
Abramo Bagnara8075c852010-06-12 07:44:57 +00007358 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007359 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007360 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007361 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007362 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007363 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007364 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007365
Abramo Bagnara8075c852010-06-12 07:44:57 +00007366 // Even though HasNoEffect == true means that this explicit instantiation
7367 // has no effect on semantics, we go on to put its syntax in the AST.
7368
7369 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7370 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007371 // Since the only prior class template specialization with these
7372 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007373 // declaration node as our own, updating the source location
7374 // for the template name to reflect our new declaration.
7375 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007376 Specialization = PrevDecl;
7377 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007378 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007379 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007380 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007381
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007382 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007383 // Create a new class template specialization declaration node for
7384 // this explicit specialization.
7385 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007386 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007387 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007388 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007389 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007390 Converted.data(),
7391 Converted.size(),
7392 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007393 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007394
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007395 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007396 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007397 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007398 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007399 }
7400
7401 // Build the fully-sugared type for this explicit instantiation as
7402 // the user wrote in the explicit instantiation itself. This means
7403 // that we'll pretty-print the type retrieved from the
7404 // specialization's declaration the way that the user actually wrote
7405 // the explicit instantiation, rather than formatting the name based
7406 // on the "canonical" representation used to store the template
7407 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007408 TypeSourceInfo *WrittenTy
7409 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7410 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007411 Context.getTypeDeclType(Specialization));
7412 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007413
Abramo Bagnara8075c852010-06-12 07:44:57 +00007414 // Set source locations for keywords.
7415 Specialization->setExternLoc(ExternLoc);
7416 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007417 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007418
Rafael Espindola0b062072012-01-03 06:04:21 +00007419 if (Attr)
7420 ProcessDeclAttributeList(S, Specialization, Attr);
7421
Abramo Bagnara8075c852010-06-12 07:44:57 +00007422 // Add the explicit instantiation into its lexical context. However,
7423 // since explicit instantiations are never found by name lookup, we
7424 // just put it into the declaration context directly.
7425 Specialization->setLexicalDeclContext(CurContext);
7426 CurContext->addDecl(Specialization);
7427
7428 // Syntax is now OK, so return if it has no other effect on semantics.
7429 if (HasNoEffect) {
7430 // Set the template specialization kind.
7431 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007432 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007433 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007434
7435 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007436 // A definition of a class template or class member template
7437 // shall be in scope at the point of the explicit instantiation of
7438 // the class template or class member template.
7439 //
7440 // This check comes when we actually try to perform the
7441 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007442 ClassTemplateSpecializationDecl *Def
7443 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007444 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007445 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007446 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007447 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007448 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007449 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7450 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007451
Douglas Gregor1d957a32009-10-27 18:42:08 +00007452 // Instantiate the members of this class template specialization.
7453 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007454 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007455 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007456 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7457
7458 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7459 // TSK_ExplicitInstantiationDefinition
7460 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00007461 TSK == TSK_ExplicitInstantiationDefinition) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007462 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007463 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007464
Hans Wennborgc0875502015-06-09 00:39:05 +00007465 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7466 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7467 // In the MS ABI, an explicit instantiation definition can add a dll
7468 // attribute to a template with a previous instantiation declaration.
7469 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007470 auto *A = cast<InheritableAttr>(
7471 getDLLAttr(Specialization)->clone(getASTContext()));
7472 A->setInherited(true);
7473 Def->addAttr(A);
Reid Kleckner5b640342016-02-26 19:51:02 +00007474
7475 // We reject explicit instantiations in class scope, so there should
7476 // never be any delayed exported classes to worry about.
7477 assert(DelayedDllExportClasses.empty() &&
7478 "delayed exports present at explicit instantiation");
Hans Wennborg17f9b442015-05-27 00:06:45 +00007479 checkClassLevelDLLAttribute(Def);
Reid Kleckner5b640342016-02-26 19:51:02 +00007480 referenceDLLExportedClassMethods();
Hans Wennborgfce87ca2015-06-09 00:39:09 +00007481
7482 // Propagate attribute to base class templates.
7483 for (auto &B : Def->bases()) {
7484 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7485 B.getType()->getAsCXXRecordDecl()))
7486 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7487 }
Hans Wennborg17f9b442015-05-27 00:06:45 +00007488 }
7489 }
7490
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007491 // Set the template specialization kind. Make sure it is set before
7492 // instantiating the members which will trigger ASTConsumer callbacks.
7493 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007494 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007495 } else {
7496
7497 // Set the template specialization kind.
7498 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007499 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007500
John McCall48871652010-08-21 09:40:31 +00007501 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007502}
7503
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007504// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007505DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007506Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007507 SourceLocation ExternLoc,
7508 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007509 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007510 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007511 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007512 IdentifierInfo *Name,
7513 SourceLocation NameLoc,
7514 AttributeList *Attr) {
7515
Douglas Gregord6ab8742009-05-28 23:31:59 +00007516 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007517 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007518 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007519 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007520 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007521 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007522 SourceLocation(), false, TypeResult(),
7523 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007524 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7525
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007526 if (!TagD)
7527 return true;
7528
John McCall48871652010-08-21 09:40:31 +00007529 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007530 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007531
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007532 if (Tag->isInvalidDecl())
7533 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007534
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007535 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7536 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7537 if (!Pattern) {
7538 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7539 << Context.getTypeDeclType(Record);
7540 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7541 return true;
7542 }
7543
Douglas Gregore47f5a72009-10-14 23:41:34 +00007544 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007545 // If the explicit instantiation is for a class or member class, the
7546 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007547 // simple-template-id.
7548 //
7549 // C++98 has the same restriction, just worded differently.
7550 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007551 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007552 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007553
Douglas Gregore47f5a72009-10-14 23:41:34 +00007554 // C++0x [temp.explicit]p2:
7555 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007556 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007557 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007558 TemplateSpecializationKind TSK
7559 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7560 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007561
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007562 // C++0x [temp.explicit]p2:
7563 // [...] An explicit instantiation shall appear in an enclosing
7564 // namespace of its template. [...]
7565 //
7566 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007567 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007568
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007569 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007570 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007571 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007572 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007573 PrevDecl = Record;
7574 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007575 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007576 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007577 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007578 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007579 PrevDecl,
7580 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007581 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007582 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007583 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007584 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007585 return TagD;
7586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007587
Douglas Gregor12e49d32009-10-15 22:53:21 +00007588 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007589 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007590 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007591 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007592 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007593 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007594 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007595 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007596 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007597 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7598 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007599 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7600 << Pattern;
7601 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007602 } else {
7603 if (InstantiateClass(NameLoc, Record, Def,
7604 getTemplateInstantiationArgs(Record),
7605 TSK))
7606 return true;
7607
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007608 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007609 if (!RecordDef)
7610 return true;
7611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007612 }
7613
Douglas Gregor1d957a32009-10-27 18:42:08 +00007614 // Instantiate all of the members of the class.
7615 InstantiateClassMembers(NameLoc, RecordDef,
7616 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007617
Douglas Gregor88d292c2010-05-13 16:44:06 +00007618 if (TSK == TSK_ExplicitInstantiationDefinition)
7619 MarkVTableUsed(NameLoc, RecordDef, true);
7620
Mike Stump87c57ac2009-05-16 07:39:55 +00007621 // FIXME: We don't have any representation for explicit instantiations of
7622 // member classes. Such a representation is not needed for compilation, but it
7623 // should be available for clients that want to see all of the declarations in
7624 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007625 return TagD;
7626}
7627
John McCallfaf5fb42010-08-26 23:41:50 +00007628DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7629 SourceLocation ExternLoc,
7630 SourceLocation TemplateLoc,
7631 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007632 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007633 // TODO: check if/when DNInfo should replace Name.
7634 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7635 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007636 if (!Name) {
7637 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007638 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007639 diag::err_explicit_instantiation_requires_name)
7640 << D.getDeclSpec().getSourceRange()
7641 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007642
Douglas Gregor450f00842009-09-25 18:43:00 +00007643 return true;
7644 }
7645
7646 // The scope passed in may not be a decl scope. Zip up the scope tree until
7647 // we find one that is.
7648 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7649 (S->getFlags() & Scope::TemplateParamScope) != 0)
7650 S = S->getParent();
7651
7652 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007653 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7654 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007655 if (R.isNull())
7656 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007657
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007658 // C++ [dcl.stc]p1:
7659 // A storage-class-specifier shall not be specified in [...] an explicit
7660 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007661 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007662 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7663 << Name;
7664 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007665 } else if (D.getDeclSpec().getStorageClassSpec()
7666 != DeclSpec::SCS_unspecified) {
7667 // Complain about then remove the storage class specifier.
7668 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7669 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7670
7671 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007672 }
7673
Douglas Gregor3c74d412009-10-14 20:14:33 +00007674 // C++0x [temp.explicit]p1:
7675 // [...] An explicit instantiation of a function template shall not use the
7676 // inline or constexpr specifiers.
7677 // Presumably, this also applies to member functions of class templates as
7678 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007679 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007680 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007681 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007682 diag::err_explicit_instantiation_inline :
7683 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007684 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007685 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007686 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7687 // not already specified.
7688 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7689 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007690
Nathan Wilsonde498452016-02-08 05:34:00 +00007691 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7692 // applied only to the definition of a function template or variable template,
7693 // declared in namespace scope.
7694 if (D.getDeclSpec().isConceptSpecified()) {
7695 Diag(D.getDeclSpec().getConceptSpecLoc(),
7696 diag::err_concept_specified_specialization) << 0;
7697 return true;
7698 }
7699
Douglas Gregore47f5a72009-10-14 23:41:34 +00007700 // C++0x [temp.explicit]p2:
7701 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007702 // definition and an explicit instantiation declaration. An explicit
7703 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007704 TemplateSpecializationKind TSK
7705 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7706 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007707
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007708 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007709 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007710
7711 if (!R->isFunctionType()) {
7712 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007713 // A [...] static data member of a class template can be explicitly
7714 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007715 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007716 // C++1y [temp.explicit]p1:
7717 // A [...] variable [...] template specialization can be explicitly
7718 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007719 if (Previous.isAmbiguous())
7720 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007721
John McCall67c00872009-12-02 08:25:40 +00007722 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007723 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007724
Larisse Voufo39a1e502013-08-06 01:03:05 +00007725 if (!PrevTemplate) {
7726 if (!Prev || !Prev->isStaticDataMember()) {
7727 // We expect to see a data data member here.
7728 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7729 << Name;
7730 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7731 P != PEnd; ++P)
7732 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7733 return true;
7734 }
7735
7736 if (!Prev->getInstantiatedFromStaticDataMember()) {
7737 // FIXME: Check for explicit specialization?
7738 Diag(D.getIdentifierLoc(),
7739 diag::err_explicit_instantiation_data_member_not_instantiated)
7740 << Prev;
7741 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7742 // FIXME: Can we provide a note showing where this was declared?
7743 return true;
7744 }
7745 } else {
7746 // Explicitly instantiate a variable template.
7747
7748 // C++1y [dcl.spec.auto]p6:
7749 // ... A program that uses auto or decltype(auto) in a context not
7750 // explicitly allowed in this section is ill-formed.
7751 //
7752 // This includes auto-typed variable template instantiations.
7753 if (R->isUndeducedType()) {
7754 Diag(T->getTypeLoc().getLocStart(),
7755 diag::err_auto_not_allowed_var_inst);
7756 return true;
7757 }
7758
Richard Smithef985ac2013-09-18 02:10:12 +00007759 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7760 // C++1y [temp.explicit]p3:
7761 // If the explicit instantiation is for a variable, the unqualified-id
7762 // in the declaration shall be a template-id.
7763 Diag(D.getIdentifierLoc(),
7764 diag::err_explicit_instantiation_without_template_id)
7765 << PrevTemplate;
7766 Diag(PrevTemplate->getLocation(),
7767 diag::note_explicit_instantiation_here);
7768 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007769 }
7770
Richard Smithef985ac2013-09-18 02:10:12 +00007771 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007772 TemplateArgumentListInfo TemplateArgs =
7773 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007774
Larisse Voufo39a1e502013-08-06 01:03:05 +00007775 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7776 D.getIdentifierLoc(), TemplateArgs);
7777 if (Res.isInvalid())
7778 return true;
7779
7780 // Ignore access control bits, we don't need them for redeclaration
7781 // checking.
7782 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007783 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007784
Douglas Gregore47f5a72009-10-14 23:41:34 +00007785 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007786 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007787 // or a static data member of a class template specialization, the name of
7788 // the class template specialization in the qualified-id for the member
7789 // name shall be a simple-template-id.
7790 //
7791 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007792 //
Richard Smith5977d872013-09-18 21:55:14 +00007793 // This does not apply to variable template specializations, where the
7794 // template-id is in the unqualified-id instead.
7795 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007796 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007797 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007798 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007799
Douglas Gregore47f5a72009-10-14 23:41:34 +00007800 // Check the scope of this explicit instantiation.
7801 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007802
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007803 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007804 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7805 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007806 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007807 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007808 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007809 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007810
Larisse Voufo39a1e502013-08-06 01:03:05 +00007811 if (!HasNoEffect) {
7812 // Instantiate static data member or variable template.
7813
7814 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7815 if (PrevTemplate) {
7816 // Merge attributes.
7817 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7818 ProcessDeclAttributeList(S, Prev, Attr);
7819 }
7820 if (TSK == TSK_ExplicitInstantiationDefinition)
7821 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7822 }
7823
7824 // Check the new variable specialization against the parsed input.
7825 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7826 Diag(T->getTypeLoc().getLocStart(),
7827 diag::err_invalid_var_template_spec_type)
7828 << 0 << PrevTemplate << R << Prev->getType();
7829 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7830 << 2 << PrevTemplate->getDeclName();
7831 return true;
7832 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007833
Douglas Gregor450f00842009-09-25 18:43:00 +00007834 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007835 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007837
7838 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007839 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007840 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007841 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007842 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007843 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007844 HasExplicitTemplateArgs = true;
7845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007846
Douglas Gregor450f00842009-09-25 18:43:00 +00007847 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007848 // A [...] function [...] can be explicitly instantiated from its template.
7849 // A member function [...] of a class template can be explicitly
7850 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007851 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007852 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007853 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007854 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7855 P != PEnd; ++P) {
7856 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007857 if (!HasExplicitTemplateArgs) {
7858 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007859 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7860 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007861 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007862
John McCall58cc69d2010-01-27 01:50:18 +00007863 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007864 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7865 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007866 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007867 }
7868 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007869
Douglas Gregor450f00842009-09-25 18:43:00 +00007870 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7871 if (!FunTmpl)
7872 continue;
7873
Larisse Voufo98b20f12013-07-19 23:00:19 +00007874 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007875 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007876 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007877 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007878 (HasExplicitTemplateArgs ? &TemplateArgs
7879 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007880 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007881 // Keep track of almost-matches.
7882 FailedCandidates.addCandidate()
7883 .set(FunTmpl->getTemplatedDecl(),
7884 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007885 (void)TDK;
7886 continue;
7887 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007888
John McCall58cc69d2010-01-27 01:50:18 +00007889 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007891
Douglas Gregor450f00842009-09-25 18:43:00 +00007892 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007893 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007894 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007895 D.getIdentifierLoc(),
7896 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7897 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7898 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007899
John McCall58cc69d2010-01-27 01:50:18 +00007900 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007901 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007902
7903 // Ignore access control bits, we don't need them for redeclaration checking.
7904 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007905
Alexey Bataev73983912014-11-06 10:10:50 +00007906 // C++11 [except.spec]p4
7907 // In an explicit instantiation an exception-specification may be specified,
7908 // but is not required.
7909 // If an exception-specification is specified in an explicit instantiation
7910 // directive, it shall be compatible with the exception-specifications of
7911 // other declarations of that function.
7912 if (auto *FPT = R->getAs<FunctionProtoType>())
7913 if (FPT->hasExceptionSpec()) {
7914 unsigned DiagID =
7915 diag::err_mismatched_exception_spec_explicit_instantiation;
7916 if (getLangOpts().MicrosoftExt)
7917 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7918 bool Result = CheckEquivalentExceptionSpec(
7919 PDiag(DiagID) << Specialization->getType(),
7920 PDiag(diag::note_explicit_instantiation_here),
7921 Specialization->getType()->getAs<FunctionProtoType>(),
7922 Specialization->getLocation(), FPT, D.getLocStart());
7923 // In Microsoft mode, mismatching exception specifications just cause a
7924 // warning.
7925 if (!getLangOpts().MicrosoftExt && Result)
7926 return true;
7927 }
7928
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007929 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007930 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007931 diag::err_explicit_instantiation_member_function_not_instantiated)
7932 << Specialization
7933 << (Specialization->getTemplateSpecializationKind() ==
7934 TSK_ExplicitSpecialization);
7935 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7936 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007937 }
7938
Douglas Gregorec9fd132012-01-14 16:38:05 +00007939 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00007940 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7941 PrevDecl = Specialization;
7942
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007943 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007944 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007945 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007946 PrevDecl,
7947 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007948 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007949 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007950 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007951
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007952 // FIXME: We may still want to build some representation of this
7953 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007954 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00007955 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007956 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00007957
7958 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00007959 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7960 if (Attr)
7961 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007962
Richard Smitheb36ddf2014-04-24 22:45:46 +00007963 if (Specialization->isDefined()) {
7964 // Let the ASTConsumer know that this function has been explicitly
7965 // instantiated now, and its linkage might have changed.
7966 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7967 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00007968 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007969
Douglas Gregore47f5a72009-10-14 23:41:34 +00007970 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007971 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007972 // or a static data member of a class template specialization, the name of
7973 // the class template specialization in the qualified-id for the member
7974 // name shall be a simple-template-id.
7975 //
7976 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007977 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00007978 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007979 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00007980 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007981 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007982 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007983 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007984
Douglas Gregore47f5a72009-10-14 23:41:34 +00007985 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007986 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00007987 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007988 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00007989 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007990
Douglas Gregor450f00842009-09-25 18:43:00 +00007991 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00007992 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007993}
7994
John McCallfaf5fb42010-08-26 23:41:50 +00007995TypeResult
John McCall7f41d982009-09-11 04:59:25 +00007996Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7997 const CXXScopeSpec &SS, IdentifierInfo *Name,
7998 SourceLocation TagLoc, SourceLocation NameLoc) {
7999 // This has to hold, because SS is expected to be defined.
8000 assert(Name && "Expected a name in a dependent tag");
8001
Aaron Ballman4a979672014-01-03 13:56:08 +00008002 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008003 if (!NNS)
8004 return true;
8005
Abramo Bagnara6150c882010-05-11 21:36:43 +00008006 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008007
Douglas Gregorba41d012010-04-24 16:38:41 +00008008 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8009 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008010 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008011 return true;
8012 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008013
Douglas Gregore7c20652011-03-02 00:47:37 +00008014 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008015 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008016 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8017
8018 // Create type-source location information for this type.
8019 TypeLocBuilder TLB;
8020 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008021 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008022 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8023 TL.setNameLoc(NameLoc);
8024 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008025}
8026
John McCallfaf5fb42010-08-26 23:41:50 +00008027TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008028Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8029 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008030 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008031 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008032 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008033
Richard Smith0bf8a4922011-10-18 20:49:44 +00008034 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8035 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008036 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008037 diag::warn_cxx98_compat_typename_outside_of_template :
8038 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008039 << FixItHint::CreateRemoval(TypenameLoc);
8040
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008041 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008042 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8043 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008044 if (T.isNull())
8045 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008046
8047 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8048 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008049 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008050 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008051 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008052 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008053 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008054 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008055 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008056 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008057 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008059
John McCallba7bf592010-08-24 05:47:05 +00008060 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008061}
8062
John McCallfaf5fb42010-08-26 23:41:50 +00008063TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008064Sema::ActOnTypenameType(Scope *S,
8065 SourceLocation TypenameLoc,
8066 const CXXScopeSpec &SS,
8067 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008068 TemplateTy TemplateIn,
8069 SourceLocation TemplateNameLoc,
8070 SourceLocation LAngleLoc,
8071 ASTTemplateArgsPtr TemplateArgsIn,
8072 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008073 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8074 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008075 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008076 diag::warn_cxx98_compat_typename_outside_of_template :
8077 diag::ext_typename_outside_of_template)
8078 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008079
8080 // Translate the parser's template argument list in our AST format.
8081 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8082 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8083
8084 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008085 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8086 // Construct a dependent template specialization type.
8087 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008088 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008089 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8090 DTN->getQualifier(),
8091 DTN->getIdentifier(),
8092 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008093
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008094 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008095 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008096 DependentTemplateSpecializationTypeLoc SpecTL
8097 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008098 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8099 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008100 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008101 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008102 SpecTL.setLAngleLoc(LAngleLoc);
8103 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008104 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8105 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008106 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008107 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008108
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008109 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8110 if (T.isNull())
8111 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008112
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008113 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008114 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008115 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008116 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008117 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8118 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008119 SpecTL.setLAngleLoc(LAngleLoc);
8120 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008121 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8122 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8123
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008124 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8125 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008126 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008127 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8128
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008129 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8130 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008131}
8132
Douglas Gregorb09518c2011-02-27 22:46:49 +00008133
Richard Smith6f8d2c62012-05-09 05:17:00 +00008134/// Determine whether this failed name lookup should be treated as being
8135/// disabled by a usage of std::enable_if.
8136static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8137 SourceRange &CondRange) {
8138 // We must be looking for a ::type...
8139 if (!II.isStr("type"))
8140 return false;
8141
8142 // ... within an explicitly-written template specialization...
8143 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8144 return false;
8145 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008146 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8147 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8148 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008149 return false;
8150 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008151 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008152
8153 // ... which names a complete class template declaration...
8154 const TemplateDecl *EnableIfDecl =
8155 EnableIfTST->getTemplateName().getAsTemplateDecl();
8156 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8157 return false;
8158
8159 // ... called "enable_if".
8160 const IdentifierInfo *EnableIfII =
8161 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8162 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8163 return false;
8164
8165 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008166 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008167 return true;
8168}
8169
Douglas Gregor333489b2009-03-27 23:10:48 +00008170/// \brief Build the type that describes a C++ typename specifier,
8171/// e.g., "typename T::type".
8172QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008173Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8174 SourceLocation KeywordLoc,
8175 NestedNameSpecifierLoc QualifierLoc,
8176 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008177 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008178 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008179 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008180
John McCall0b66eb32010-05-01 00:40:08 +00008181 DeclContext *Ctx = computeDeclContext(SS);
8182 if (!Ctx) {
8183 // If the nested-name-specifier is dependent and couldn't be
8184 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008185 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8186 return Context.getDependentNameType(Keyword,
8187 QualifierLoc.getNestedNameSpecifier(),
8188 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008189 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008190
John McCall0b66eb32010-05-01 00:40:08 +00008191 // If the nested-name-specifier refers to the current instantiation,
8192 // the "typename" keyword itself is superfluous. In C++03, the
8193 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8194 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008195 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008196
John McCall0b66eb32010-05-01 00:40:08 +00008197 if (RequireCompleteDeclContext(SS, Ctx))
8198 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008199
8200 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008201 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008202 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008203 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008204 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008205 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008206 case LookupResult::NotFound: {
8207 // If we're looking up 'type' within a template named 'enable_if', produce
8208 // a more specific diagnostic.
8209 SourceRange CondRange;
8210 if (isEnableIf(QualifierLoc, II, CondRange)) {
8211 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8212 << Ctx << CondRange;
8213 return QualType();
8214 }
8215
Douglas Gregore40876a2009-10-13 21:16:44 +00008216 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008217 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008218 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008219
8220 case LookupResult::FoundUnresolvedValue: {
8221 // We found a using declaration that is a value. Most likely, the using
8222 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008223 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008224 IILoc);
8225 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8226 << Name << Ctx << FullRange;
8227 if (UnresolvedUsingValueDecl *Using
8228 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008229 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008230 Diag(Loc, diag::note_using_value_decl_missing_typename)
8231 << FixItHint::CreateInsertion(Loc, "typename ");
8232 }
8233 }
8234 // Fall through to create a dependent typename type, from which we can recover
8235 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008236
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008237 case LookupResult::NotFoundInCurrentInstantiation:
8238 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008239 return Context.getDependentNameType(Keyword,
8240 QualifierLoc.getNestedNameSpecifier(),
8241 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008242
8243 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008244 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008245 // We found a type. Build an ElaboratedType, since the
8246 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008247 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008248 return Context.getElaboratedType(ETK_Typename,
8249 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008250 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008251 }
8252
8253 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008254 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008255 break;
8256
8257 case LookupResult::FoundOverloaded:
8258 DiagID = diag::err_typename_nested_not_type;
8259 Referenced = *Result.begin();
8260 break;
8261
John McCall6538c932009-10-10 05:48:19 +00008262 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008263 return QualType();
8264 }
8265
8266 // If we get here, it's because name lookup did not find a
8267 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008268 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008269 IILoc);
8270 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008271 if (Referenced)
8272 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8273 << Name;
8274 return QualType();
8275}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008276
8277namespace {
8278 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008279 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008280 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008281 SourceLocation Loc;
8282 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008283
Douglas Gregor15acfb92009-08-06 16:20:37 +00008284 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008285 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008286
Mike Stump11289f42009-09-09 15:08:12 +00008287 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008288 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008289 DeclarationName Entity)
8290 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008291 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008292
8293 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008294 /// transformed.
8295 ///
8296 /// For the purposes of type reconstruction, a type has already been
8297 /// transformed if it is NULL or if it is not dependent.
8298 bool AlreadyTransformed(QualType T) {
8299 return T.isNull() || !T->isDependentType();
8300 }
Mike Stump11289f42009-09-09 15:08:12 +00008301
8302 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008303 /// rebuilt.
8304 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008305
Douglas Gregor15acfb92009-08-06 16:20:37 +00008306 /// \brief Returns the name of the entity whose type is being rebuilt.
8307 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008308
Douglas Gregoref6ab412009-10-27 06:26:26 +00008309 /// \brief Sets the "base" location and entity when that
8310 /// information is known based on another transformation.
8311 void setBase(SourceLocation Loc, DeclarationName Entity) {
8312 this->Loc = Loc;
8313 this->Entity = Entity;
8314 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008315
8316 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8317 // Lambdas never need to be transformed.
8318 return E;
8319 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008320 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008321} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008322
Douglas Gregor15acfb92009-08-06 16:20:37 +00008323/// \brief Rebuilds a type within the context of the current instantiation.
8324///
Mike Stump11289f42009-09-09 15:08:12 +00008325/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008326/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008327/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008328/// partial specialization thereof). This routine will rebuild that type now
8329/// that we have entered the declarator's scope, which may produce different
8330/// canonical types, e.g.,
8331///
8332/// \code
8333/// template<typename T>
8334/// struct X {
8335/// typedef T* pointer;
8336/// pointer data();
8337/// };
8338///
8339/// template<typename T>
8340/// typename X<T>::pointer X<T>::data() { ... }
8341/// \endcode
8342///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008343/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008344/// since we do not know that we can look into X<T> when we parsed the type.
8345/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008346/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008347/// as the canonical type of T*, allowing the return types of the out-of-line
8348/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008349TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8350 SourceLocation Loc,
8351 DeclarationName Name) {
8352 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008353 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008354
Douglas Gregor15acfb92009-08-06 16:20:37 +00008355 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8356 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008357}
Douglas Gregorbe999392009-09-15 16:23:51 +00008358
John McCalldadc5752010-08-24 06:29:42 +00008359ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008360 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8361 DeclarationName());
8362 return Rebuilder.TransformExpr(E);
8363}
8364
John McCall99b2fe52010-04-29 23:50:39 +00008365bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008366 if (SS.isInvalid())
8367 return true;
John McCall2408e322010-04-27 00:57:59 +00008368
Douglas Gregor10176412011-02-25 16:07:42 +00008369 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008370 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8371 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008372 NestedNameSpecifierLoc Rebuilt
8373 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8374 if (!Rebuilt)
8375 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008376
Douglas Gregor10176412011-02-25 16:07:42 +00008377 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008378 return false;
John McCall2408e322010-04-27 00:57:59 +00008379}
8380
Douglas Gregor041b0842011-10-14 15:31:12 +00008381/// \brief Rebuild the template parameters now that we know we're in a current
8382/// instantiation.
8383bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8384 TemplateParameterList *Params) {
8385 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8386 Decl *Param = Params->getParam(I);
8387
8388 // There is nothing to rebuild in a type parameter.
8389 if (isa<TemplateTypeParmDecl>(Param))
8390 continue;
8391
8392 // Rebuild the template parameter list of a template template parameter.
8393 if (TemplateTemplateParmDecl *TTP
8394 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8395 if (RebuildTemplateParamsInCurrentInstantiation(
8396 TTP->getTemplateParameters()))
8397 return true;
8398
8399 continue;
8400 }
8401
8402 // Rebuild the type of a non-type template parameter.
8403 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8404 TypeSourceInfo *NewTSI
8405 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8406 NTTP->getLocation(),
8407 NTTP->getDeclName());
8408 if (!NewTSI)
8409 return true;
8410
8411 if (NewTSI != NTTP->getTypeSourceInfo()) {
8412 NTTP->setTypeSourceInfo(NewTSI);
8413 NTTP->setType(NewTSI->getType());
8414 }
8415 }
8416
8417 return false;
8418}
8419
Douglas Gregorbe999392009-09-15 16:23:51 +00008420/// \brief Produces a formatted string that describes the binding of
8421/// template parameters to template arguments.
8422std::string
8423Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8424 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008425 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008426}
8427
8428std::string
8429Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8430 const TemplateArgument *Args,
8431 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008432 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008433 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008434
Douglas Gregore62e6a02009-11-11 19:13:48 +00008435 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008436 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008437
Douglas Gregorbe999392009-09-15 16:23:51 +00008438 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008439 if (I >= NumArgs)
8440 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008441
Douglas Gregorbe999392009-09-15 16:23:51 +00008442 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008443 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008444 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008445 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008446
Douglas Gregorbe999392009-09-15 16:23:51 +00008447 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008448 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008449 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008450 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008451 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008452
Douglas Gregor0192c232010-12-20 16:52:59 +00008453 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008454 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008455 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008456
8457 Out << ']';
8458 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008459}
Francois Pichet1c229c02011-04-22 22:18:13 +00008460
Richard Smithe40f2ba2013-08-07 21:41:30 +00008461void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8462 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008463 if (!FD)
8464 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008465
8466 LateParsedTemplate *LPT = new LateParsedTemplate;
8467
8468 // Take tokens to avoid allocations
8469 LPT->Toks.swap(Toks);
8470 LPT->D = FnD;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00008471 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008472
8473 FD->setLateTemplateParsed(true);
8474}
8475
8476void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8477 if (!FD)
8478 return;
8479 FD->setLateTemplateParsed(false);
8480}
Francois Pichet1c229c02011-04-22 22:18:13 +00008481
8482bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8483 DeclContext *DC = CurContext;
8484
8485 while (DC) {
8486 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8487 const FunctionDecl *FD = RD->isLocalClass();
8488 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8489 } else if (DC->isTranslationUnit() || DC->isNamespace())
8490 return false;
8491
8492 DC = DC->getParent();
8493 }
8494 return false;
8495}