blob: 7d573293f4e4ff8f98c0deb08460e9ab2a26d8cf [file] [log] [blame]
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +000011
Douglas Gregor15acfb92009-08-06 16:20:37 +000012#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000013#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000015#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000019#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000020#include "clang/AST/TypeVisitor.h"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000021#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedTemplate.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000032#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000034#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000035
Eric Fiselier6ad68552016-07-01 01:24:09 +000036#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000037using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000039
John McCall9b72f892010-11-10 02:40:36 +000040// Exported for use by Parser.
41SourceRange
42clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 unsigned N) {
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46}
47
Douglas Gregorb7bfe792009-09-02 22:59:36 +000048/// \brief Determine whether the declaration found is acceptable as the name
49/// of a template and, if so, return that template declaration. Otherwise,
50/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000051static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000052 NamedDecl *Orig,
53 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000054 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000055
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000056 if (isa<TemplateDecl>(D)) {
57 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000058 return nullptr;
59
John McCalle9cccd82010-06-16 08:42:20 +000060 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000061 }
Mike Stump11289f42009-09-09 15:08:12 +000062
Douglas Gregorb7bfe792009-09-02 22:59:36 +000063 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
64 // C++ [temp.local]p1:
65 // Like normal (non-template) classes, class templates have an
66 // injected-class-name (Clause 9). The injected-class-name
67 // can be used with or without a template-argument-list. When
68 // it is used without a template-argument-list, it is
69 // equivalent to the injected-class-name followed by the
70 // template-parameters of the class template enclosed in
71 // <>. When it is used with a template-argument-list, it
72 // refers to the specified class template specialization,
73 // which could be the current specialization or another
74 // specialization.
75 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000076 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000077 if (Record->getDescribedClassTemplate())
78 return Record->getDescribedClassTemplate();
79
80 if (ClassTemplateSpecializationDecl *Spec
81 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
82 return Spec->getSpecializedTemplate();
83 }
Mike Stump11289f42009-09-09 15:08:12 +000084
Craig Topperc3ec1492014-05-26 06:22:03 +000085 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000086 }
Mike Stump11289f42009-09-09 15:08:12 +000087
Craig Topperc3ec1492014-05-26 06:22:03 +000088 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000089}
90
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000091void Sema::FilterAcceptableTemplateNames(LookupResult &R,
92 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +000093 // The set of class templates we've already seen.
94 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000095 LookupResult::Filter filter = R.makeFilter();
96 while (filter.hasNext()) {
97 NamedDecl *Orig = filter.next();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000098 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
99 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +0000100 if (!Repl)
101 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000102 else if (Repl != Orig) {
103
104 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000105 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000106 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000107 // one base class). If all of the injected-class-names that are found
108 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000109 // is used as a template-name, the reference refers to the class
110 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000111 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000112 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000113 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000114 filter.erase();
115 continue;
116 }
John McCallbd8062d2010-08-13 07:02:08 +0000117
118 // FIXME: we promote access to public here as a workaround to
119 // the fact that LookupResult doesn't let us remember that we
120 // found this template through a particular injected class name,
121 // which means we end up doing nasty things to the invariants.
122 // Pretending that access is public is *much* safer.
123 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000124 }
John McCalle66edc12009-11-24 19:00:30 +0000125 }
126 filter.done();
127}
128
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000129bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
130 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000131 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000132 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000133 return true;
134
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000135 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000136}
137
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000138TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000139 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000140 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000141 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000142 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000143 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000144 TemplateTy &TemplateResult,
145 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000146 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000147
Douglas Gregor3cf81312009-11-03 23:16:33 +0000148 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000149 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000150
Douglas Gregor3cf81312009-11-03 23:16:33 +0000151 switch (Name.getKind()) {
152 case UnqualifiedId::IK_Identifier:
153 TName = DeclarationName(Name.Identifier);
154 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000155
Douglas Gregor3cf81312009-11-03 23:16:33 +0000156 case UnqualifiedId::IK_OperatorFunctionId:
157 TName = Context.DeclarationNames.getCXXOperatorName(
158 Name.OperatorFunctionId.Operator);
159 break;
160
Alexis Hunted0530f2009-11-28 08:58:14 +0000161 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000162 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
163 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000164
Douglas Gregor3cf81312009-11-03 23:16:33 +0000165 default:
166 return TNK_Non_template;
167 }
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCallba7bf592010-08-24 05:47:05 +0000169 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000170
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000171 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000172 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
173 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000174 if (R.empty()) return TNK_Non_template;
175 if (R.isAmbiguous()) {
176 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000177 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000178
179 // FIXME: we might have ambiguous templates, in which case we
180 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000181 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000182 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000183
John McCalld28ae272009-12-02 08:04:21 +0000184 TemplateName Template;
185 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000186
John McCalld28ae272009-12-02 08:04:21 +0000187 unsigned ResultCount = R.end() - R.begin();
188 if (ResultCount > 1) {
189 // We assume that we'll preserve the qualifier from a function
190 // template name in other ways.
191 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
192 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000193
194 // We'll do this lookup again later.
195 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000196 } else {
John McCalld28ae272009-12-02 08:04:21 +0000197 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
198
199 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000200 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000201 Template = Context.getQualifiedTemplateName(Qualifier,
202 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000203 } else {
204 Template = TemplateName(TD);
205 }
206
John McCalldcc71402010-08-13 02:23:42 +0000207 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000208 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000209
210 // We'll do this lookup again later.
211 R.suppressDiagnostics();
212 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000213 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000214 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
215 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000216 TemplateKind =
217 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000218 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000219 }
Mike Stump11289f42009-09-09 15:08:12 +0000220
John McCalld28ae272009-12-02 08:04:21 +0000221 TemplateResult = TemplateTy::make(Template);
222 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000223}
224
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000225bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000226 SourceLocation IILoc,
227 Scope *S,
228 const CXXScopeSpec *SS,
229 TemplateTy &SuggestedTemplate,
230 TemplateNameKind &SuggestedKind) {
231 // We can't recover unless there's a dependent scope specifier preceding the
232 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000233 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000234 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
235 computeDeclContext(*SS))
236 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000237
Douglas Gregor18473f32010-01-12 21:28:44 +0000238 // The code is missing a 'template' keyword prior to the dependent template
239 // name.
240 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
241 Diag(IILoc, diag::err_template_kw_missing)
242 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000243 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000244 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000245 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
246 SuggestedKind = TNK_Dependent_template_name;
247 return true;
248}
249
John McCalle66edc12009-11-24 19:00:30 +0000250void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000251 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000252 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000253 bool EnteringContext,
254 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000255 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000256 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000257 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000258 bool isDependent = false;
259 if (!ObjectType.isNull()) {
260 // This nested-name-specifier occurs in a member access expression, e.g.,
261 // x->B::f, and we are looking into the type of the object.
262 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
263 LookupCtx = computeDeclContext(ObjectType);
264 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000265 assert((isDependent || !ObjectType->isIncompleteType() ||
266 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000267 "Caller should have completed object type");
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000268
269 // Template names cannot appear inside an Objective-C class or object type.
270 if (ObjectType->isObjCObjectOrInterfaceType()) {
271 Found.clear();
272 return;
273 }
John McCalle66edc12009-11-24 19:00:30 +0000274 } else if (SS.isSet()) {
275 // This nested-name-specifier occurs after another nested-name-specifier,
276 // so long into the context associated with the prior nested-name-specifier.
277 LookupCtx = computeDeclContext(SS, EnteringContext);
278 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279
John McCalle66edc12009-11-24 19:00:30 +0000280 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000281 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000282 return;
283 }
284
285 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000286 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000287 if (LookupCtx) {
288 // Perform "qualified" name lookup into the declaration context we
289 // computed, which is either the type of the base of a member access
290 // expression or the declaration context associated with a prior
291 // nested-name-specifier.
292 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000293 if (!ObjectType.isNull() && Found.empty()) {
294 // C++ [basic.lookup.classref]p1:
295 // In a class member access expression (5.2.5), if the . or -> token is
296 // immediately followed by an identifier followed by a <, the
297 // identifier must be looked up to determine whether the < is the
298 // beginning of a template argument list (14.2) or a less-than operator.
299 // The identifier is first looked up in the class of the object
300 // expression. If the identifier is not found, it is then looked up in
301 // the context of the entire postfix-expression and shall name a class
302 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000303 if (S) LookupName(Found, S);
304 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000305 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000306 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000307 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000308 // We cannot look into a dependent object type or nested nme
309 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000310 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000311 return;
312 } else {
313 // Perform unqualified name lookup in the current scope.
314 LookupName(Found, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000315
316 if (!ObjectType.isNull())
317 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000318 }
319
Douglas Gregorc119dd52010-01-12 17:06:20 +0000320 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000321 // If we did not find any names, attempt to correct any typos.
322 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000323 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000324 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000325 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
326 FilterCCC->WantTypeSpecifiers = false;
327 FilterCCC->WantExpressionKeywords = false;
328 FilterCCC->WantRemainingKeywords = false;
329 FilterCCC->WantCXXNamedCasts = true;
330 if (TypoCorrection Corrected = CorrectTypo(
331 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
332 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000333 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000334 if (auto *ND = Corrected.getFoundDecl())
335 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000336 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000337 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000338 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000339 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
340 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000341 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000342 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
343 << Name << LookupCtx << DroppedSpecifier
344 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000345 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000346 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000347 }
John McCalle9cccd82010-06-16 08:42:20 +0000348 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000349 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000350 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000351 }
352 }
353
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000354 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000355 if (Found.empty()) {
356 if (isDependent)
357 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000358 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000359 }
John McCalle66edc12009-11-24 19:00:30 +0000360
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000361 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000362 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000363 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000364 // [...] If the lookup in the class of the object expression finds a
365 // template, the name is also looked up in the context of the entire
366 // postfix-expression and [...]
367 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000368 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000369 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
370 LookupOrdinaryName);
371 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000372 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000373
John McCalle66edc12009-11-24 19:00:30 +0000374 if (FoundOuter.empty()) {
375 // - if the name is not found, the name found in the class of the
376 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000377 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
378 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000379 // - if the name is found in the context of the entire
380 // postfix-expression and does not name a class template, the name
381 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000382 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000383 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000384 // - if the name found is a class template, it must refer to the same
385 // entity as the one found in the class of the object expression,
386 // otherwise the program is ill-formed.
387 if (!Found.isSingleResult() ||
388 Found.getFoundDecl()->getCanonicalDecl()
389 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000390 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000391 diag::ext_nested_name_member_ref_lookup_ambiguous)
392 << Found.getLookupName()
393 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000394 Diag(Found.getRepresentativeDecl()->getLocation(),
395 diag::note_ambig_member_ref_object_type)
396 << ObjectType;
397 Diag(FoundOuter.getFoundDecl()->getLocation(),
398 diag::note_ambig_member_ref_scope);
399
400 // Recover by taking the template that we found in the object
401 // expression's type.
402 }
403 }
404 }
405}
406
John McCallcd4b4772009-12-02 03:53:29 +0000407/// ActOnDependentIdExpression - Handle a dependent id-expression that
408/// was just parsed. This is only possible with an explicit scope
409/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000410ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000411Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000412 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000413 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000414 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000415 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000416 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417
Reid Kleckner1af391df2016-03-11 18:59:12 +0000418 // C++11 [expr.prim.general]p12:
419 // An id-expression that denotes a non-static data member or non-static
420 // member function of a class can only be used:
421 // (...)
422 // - if that id-expression denotes a non-static data member and it
423 // appears in an unevaluated operand.
424 //
425 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
426 // CXXDependentScopeMemberExpr. The former can instantiate to either
427 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
428 // always a MemberExpr.
429 bool MightBeCxx11UnevalField =
430 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
431
432 if (!MightBeCxx11UnevalField && !isAddressOfOperand &&
433 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000434 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000435
John McCalle66edc12009-11-24 19:00:30 +0000436 // Since the 'this' expression is synthesized, we don't need to
437 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000438 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000439
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000440 return CXXDependentScopeMemberExpr::Create(
441 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
442 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
443 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000444 }
445
Abramo Bagnara7945c982012-01-27 09:46:47 +0000446 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000447}
448
John McCalldadc5752010-08-24 06:29:42 +0000449ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000450Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000451 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000452 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000453 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000454 return DependentScopeDeclRefExpr::Create(
455 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
456 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000457}
458
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000459
460/// Determine whether we would be unable to instantiate this template (because
461/// it either has no definition, or is in the process of being instantiated).
462bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
463 NamedDecl *Instantiation,
464 bool InstantiatedFromMember,
465 const NamedDecl *Pattern,
466 const NamedDecl *PatternDef,
467 TemplateSpecializationKind TSK,
468 bool Complain /*= true*/) {
469 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation));
470
471 if (PatternDef && (isa<FunctionDecl>(PatternDef)
472 || !cast<TagDecl>(PatternDef)->isBeingDefined())) {
473 NamedDecl *SuggestedDef = nullptr;
474 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
475 /*OnlyNeedComplete*/false)) {
476 // If we're allowed to diagnose this and recover, do so.
477 bool Recover = Complain && !isSFINAEContext();
478 if (Complain)
479 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
480 Sema::MissingImportKind::Definition, Recover);
481 return !Recover;
482 }
483 return false;
484 }
485
Richard Smith6f4e2e02016-08-23 19:41:39 +0000486 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
487 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000488
489 QualType InstantiationTy;
490 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
491 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000492 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000493 Diag(PointOfInstantiation,
494 diag::err_template_instantiate_within_definition)
495 << (TSK != TSK_ImplicitInstantiation)
496 << InstantiationTy;
497 // Not much point in noting the template declaration here, since
498 // we're lexically inside it.
499 Instantiation->setInvalidDecl();
500 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000501 if (isa<FunctionDecl>(Instantiation)) {
502 Diag(PointOfInstantiation,
503 diag::err_explicit_instantiation_undefined_member)
504 << 1 << Instantiation->getDeclName() << Instantiation->getDeclContext();
505 } else {
506 Diag(PointOfInstantiation,
507 diag::err_implicit_instantiate_member_undefined)
508 << InstantiationTy;
509 }
510 Diag(Pattern->getLocation(), isa<FunctionDecl>(Instantiation)
511 ? diag::note_explicit_instantiation_here
512 : diag::note_member_declared_at);
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000513 } else {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000514 if (isa<FunctionDecl>(Instantiation))
515 Diag(PointOfInstantiation,
516 diag::err_explicit_instantiation_undefined_func_template)
517 << Pattern;
518 else
519 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
520 << (TSK != TSK_ImplicitInstantiation)
521 << InstantiationTy;
522 Diag(Pattern->getLocation(), isa<FunctionDecl>(Instantiation)
523 ? diag::note_explicit_instantiation_here
524 : diag::note_template_decl_here);
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000525 }
526
527 // In general, Instantiation isn't marked invalid to get more than one
528 // error for multiple undefined instantiations. But the code that does
529 // explicit declaration -> explicit definition conversion can't handle
530 // invalid declarations, so mark as invalid in that case.
531 if (TSK == TSK_ExplicitInstantiationDeclaration)
532 Instantiation->setInvalidDecl();
533 return true;
534}
535
Douglas Gregor5101c242008-12-05 18:15:24 +0000536/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
537/// that the template parameter 'PrevDecl' is being shadowed by a new
538/// declaration at location Loc. Returns true to indicate that this is
539/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000540void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000541 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000542
543 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000544 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000545 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000546
547 // C++ [temp.local]p4:
548 // A template-parameter shall not be redeclared within its
549 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000550 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000551 << cast<NamedDecl>(PrevDecl)->getDeclName();
552 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000553}
554
Douglas Gregor463421d2009-03-03 04:44:36 +0000555/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000556/// the parameter D to reference the templated declaration and return a pointer
557/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000558TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
559 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
560 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000561 return Temp;
562 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000563 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000564}
565
Douglas Gregoreb29d182011-01-05 17:40:24 +0000566ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
567 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000568 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000569 "Only template template arguments can be pack expansions here");
570 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
571 "Template template argument pack expansion without packs");
572 ParsedTemplateArgument Result(*this);
573 Result.EllipsisLoc = EllipsisLoc;
574 return Result;
575}
576
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000577static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
578 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000579
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000580 switch (Arg.getKind()) {
581 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000582 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000583 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000585 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000586 return TemplateArgumentLoc(TemplateArgument(T), DI);
587 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000588
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000589 case ParsedTemplateArgument::NonType: {
590 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
591 return TemplateArgumentLoc(TemplateArgument(E), E);
592 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000594 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000595 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000596 TemplateArgument TArg;
597 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000598 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000599 else
600 TArg = Template;
601 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000602 Arg.getScopeSpec().getWithLocInContext(
603 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000604 Arg.getLocation(),
605 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000606 }
607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000609 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000610}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000611
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000612/// \brief Translates template arguments as provided by the parser
613/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000614void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
615 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000616 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000617 TemplateArgs.addArgument(translateTemplateArgument(*this,
618 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000619}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000620
Richard Smithb80d5402013-06-25 22:21:36 +0000621static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
622 SourceLocation Loc,
623 IdentifierInfo *Name) {
624 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
625 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
626 if (PrevDecl && PrevDecl->isTemplateParameter())
627 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
628}
629
Douglas Gregor5101c242008-12-05 18:15:24 +0000630/// ActOnTypeParameter - Called when a C++ template type parameter
631/// (e.g., "typename T") has been parsed. Typename specifies whether
632/// the keyword "typename" was used to declare the type parameter
633/// (otherwise, "class" was used), and KeyLoc is the location of the
634/// "class" or "typename" keyword. ParamName is the name of the
635/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000636/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000637/// If the type parameter has a default argument, it will be added
638/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000639Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000640 SourceLocation EllipsisLoc,
641 SourceLocation KeyLoc,
642 IdentifierInfo *ParamName,
643 SourceLocation ParamNameLoc,
644 unsigned Depth, unsigned Position,
645 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000646 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000647 assert(S->isTemplateParamScope() &&
648 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000649
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000650 SourceLocation Loc = ParamNameLoc;
651 if (!ParamName)
652 Loc = KeyLoc;
653
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000654 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000655 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000656 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000657 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000658 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000659 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000660
661 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000662 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
663
Douglas Gregor5101c242008-12-05 18:15:24 +0000664 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000665 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000666 IdResolver.AddDecl(Param);
667 }
668
Douglas Gregorf5500772011-01-05 15:48:55 +0000669 // C++0x [temp.param]p9:
670 // A default template-argument may be specified for any kind of
671 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000672 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000673 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000674 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000675 }
676
Douglas Gregordc13ded2010-07-01 00:00:45 +0000677 // Handle the default argument, if provided.
678 if (DefaultArg) {
679 TypeSourceInfo *DefaultTInfo;
680 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000681
Douglas Gregordc13ded2010-07-01 00:00:45 +0000682 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000684 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000686 UPPC_DefaultArgument))
687 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Douglas Gregordc13ded2010-07-01 00:00:45 +0000689 // Check the template argument itself.
690 if (CheckTemplateArgument(Param, DefaultTInfo)) {
691 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000692 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000694
Richard Smith1469b912015-06-10 00:29:03 +0000695 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
John McCall48871652010-08-21 09:40:31 +0000698 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000699}
700
Douglas Gregor463421d2009-03-03 04:44:36 +0000701/// \brief Check that the type of a non-type template parameter is
702/// well-formed.
703///
704/// \returns the (possibly-promoted) parameter type if valid;
705/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000706QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000707Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000708 // We don't allow variably-modified types as the type of non-type template
709 // parameters.
710 if (T->isVariablyModifiedType()) {
711 Diag(Loc, diag::err_variably_modified_nontype_template_param)
712 << T;
713 return QualType();
714 }
715
Douglas Gregor463421d2009-03-03 04:44:36 +0000716 // C++ [temp.param]p4:
717 //
718 // A non-type template-parameter shall have one of the following
719 // (optionally cv-qualified) types:
720 //
721 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000722 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000723 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000724 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000725 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000726 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000727 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000728 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000729 // -- std::nullptr_t.
730 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000731 // If T is a dependent type, we can't do the check now, so we
732 // assume that it is well-formed.
Richard Smithd0e1c952012-03-13 07:21:50 +0000733 T->isDependentType()) {
734 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
735 // are ignored when determining its type.
736 return T.getUnqualifiedType();
737 }
738
Douglas Gregor463421d2009-03-03 04:44:36 +0000739 // C++ [temp.param]p8:
740 //
741 // A non-type template-parameter of type "array of T" or
742 // "function returning T" is adjusted to be of type "pointer to
743 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000744 else if (T->isArrayType() || T->isFunctionType())
745 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000746
Douglas Gregor463421d2009-03-03 04:44:36 +0000747 Diag(Loc, diag::err_template_nontype_parm_bad_type)
748 << T;
749
750 return QualType();
751}
752
John McCall48871652010-08-21 09:40:31 +0000753Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
754 unsigned Depth,
755 unsigned Position,
756 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000757 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000758 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
759 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000760
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000761 assert(S->isTemplateParamScope() &&
762 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000763 bool Invalid = false;
764
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000765 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
766 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000767 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000768 Invalid = true;
769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000770
Richard Smithb80d5402013-06-25 22:21:36 +0000771 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000772 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000773 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000774 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000775 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000776 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000777 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000778 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000779 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000780
Douglas Gregor5101c242008-12-05 18:15:24 +0000781 if (Invalid)
782 Param->setInvalidDecl();
783
Richard Smithb80d5402013-06-25 22:21:36 +0000784 if (ParamName) {
785 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
786 ParamName);
787
Douglas Gregor5101c242008-12-05 18:15:24 +0000788 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000789 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000790 IdResolver.AddDecl(Param);
791 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000792
Douglas Gregorf5500772011-01-05 15:48:55 +0000793 // C++0x [temp.param]p9:
794 // A default template-argument may be specified for any kind of
795 // template-parameter that is not a template parameter pack.
796 if (Default && IsParameterPack) {
797 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000798 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000799 }
800
Douglas Gregordc13ded2010-07-01 00:00:45 +0000801 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000802 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000803 // Check for unexpanded parameter packs.
804 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
805 return Param;
806
Douglas Gregordc13ded2010-07-01 00:00:45 +0000807 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000808 ExprResult DefaultRes =
809 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000810 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000811 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000812 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000813 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000814 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000815
Richard Smith1469b912015-06-10 00:29:03 +0000816 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000818
John McCall48871652010-08-21 09:40:31 +0000819 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000820}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000821
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000822/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000823/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000824/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000825Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
826 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000827 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000828 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000829 IdentifierInfo *Name,
830 SourceLocation NameLoc,
831 unsigned Depth,
832 unsigned Position,
833 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000834 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000835 assert(S->isTemplateParamScope() &&
836 "Template template parameter not in template parameter scope!");
837
838 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000839 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000840 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000841 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842 NameLoc.isInvalid()? TmpLoc : NameLoc,
843 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000844 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000845 Param->setAccess(AS_public);
846
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000847 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000848 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000849 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000850 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
851
John McCall48871652010-08-21 09:40:31 +0000852 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000853 IdResolver.AddDecl(Param);
854 }
855
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000856 if (Params->size() == 0) {
857 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
858 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
859 Param->setInvalidDecl();
860 }
861
Douglas Gregorf5500772011-01-05 15:48:55 +0000862 // C++0x [temp.param]p9:
863 // A default template-argument may be specified for any kind of
864 // template-parameter that is not a template parameter pack.
865 if (IsParameterPack && !Default.isInvalid()) {
866 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
867 Default = ParsedTemplateArgument();
868 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000869
Douglas Gregordc13ded2010-07-01 00:00:45 +0000870 if (!Default.isInvalid()) {
871 // Check only that we have a template template argument. We don't want to
872 // try to check well-formedness now, because our template template parameter
873 // might have dependent types in its template parameters, which we wouldn't
874 // be able to match now.
875 //
876 // If none of the template template parameter's template arguments mention
877 // other template parameters, we could actually perform more checking here.
878 // However, it isn't worth doing.
879 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
880 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000881 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000882 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000883 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000884 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000885
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000886 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000887 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000888 DefaultArg.getArgument().getAsTemplate(),
889 UPPC_DefaultArgument))
890 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000891
Richard Smith1469b912015-06-10 00:29:03 +0000892 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000893 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000894
John McCall48871652010-08-21 09:40:31 +0000895 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000896}
897
Hubert Tongf608c052016-04-29 18:05:37 +0000898/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
899/// constrained by RequiresClause, that contains the template parameters in
900/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000901TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000902Sema::ActOnTemplateParameterList(unsigned Depth,
903 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000904 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000905 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000906 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +0000907 SourceLocation RAngleLoc,
908 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000909 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000910 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000911
David Majnemer902f8c62015-12-27 07:16:27 +0000912 return TemplateParameterList::Create(
913 Context, TemplateLoc, LAngleLoc,
914 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000915 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000916}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000917
John McCall3e11ebe2010-03-15 10:12:16 +0000918static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
919 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000920 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000921}
922
John McCallfaf5fb42010-08-26 23:41:50 +0000923DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000924Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000925 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000926 IdentifierInfo *Name, SourceLocation NameLoc,
927 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000928 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000929 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000930 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000931 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000932 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000933 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000934 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000935 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000936 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000937 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000938
939 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000940 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000941 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000942
Abramo Bagnara6150c882010-05-11 21:36:43 +0000943 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
944 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000945
946 // There is no such thing as an unnamed class template.
947 if (!Name) {
948 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000949 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000950 }
951
Richard Smith6483d222012-04-21 01:27:54 +0000952 // Find any previous declaration with this name. For a friend with no
953 // scope explicitly specified, we only look for tag declarations (per
954 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000955 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000956 LookupResult Previous(*this, Name, NameLoc,
957 (SS.isEmpty() && TUK == TUK_Friend)
958 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000959 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000960 if (SS.isNotEmpty() && !SS.isInvalid()) {
961 SemanticContext = computeDeclContext(SS, true);
962 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000963 // FIXME: Horrible, horrible hack! We can't currently represent this
964 // in the AST, and historically we have just ignored such friend
965 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000966 Diag(NameLoc, TUK == TUK_Friend
967 ? diag::warn_template_qualified_friend_ignored
968 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000969 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000970 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000971 }
Mike Stump11289f42009-09-09 15:08:12 +0000972
John McCall0b66eb32010-05-01 00:40:08 +0000973 if (RequireCompleteDeclContext(SS, SemanticContext))
974 return true;
975
Douglas Gregor041b0842011-10-14 15:31:12 +0000976 // If we're adding a template to a dependent context, we may need to
977 // rebuilding some of the types used within the template parameter list,
978 // now that we know what the current instantiation is.
979 if (SemanticContext->isDependentContext()) {
980 ContextRAII SavedContext(*this, SemanticContext);
981 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
982 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000983 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
984 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000985
John McCall27b18f82009-11-17 02:14:36 +0000986 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000987 } else {
988 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +0000989
990 // C++14 [class.mem]p14:
991 // If T is the name of a class, then each of the following shall have a
992 // name different from T:
993 // -- every member template of class T
994 if (TUK != TUK_Friend &&
995 DiagnoseClassNameShadow(SemanticContext,
996 DeclarationNameInfo(Name, NameLoc)))
997 return true;
998
John McCall27b18f82009-11-17 02:14:36 +0000999 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001000 }
Mike Stump11289f42009-09-09 15:08:12 +00001001
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001002 if (Previous.isAmbiguous())
1003 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001004
Craig Topperc3ec1492014-05-26 06:22:03 +00001005 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001006 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001007 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001008
Serge Pavlove50bf752016-06-10 04:39:07 +00001009 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1010 // Maybe we will complain about the shadowed template parameter.
1011 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1012 // Just pretend that we didn't see the previous declaration.
1013 PrevDecl = nullptr;
1014 }
1015
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001016 // If there is a previous declaration with the same name, check
1017 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +00001018 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001019 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001020
1021 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001022 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001023 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001024 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001025 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1026 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001027 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001028 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1029 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1030 PrevClassTemplate
1031 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1032 ->getSpecializedTemplate();
1033 }
1034 }
1035
John McCalld43784f2009-12-18 11:25:59 +00001036 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001037 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001038 // [...] When looking for a prior declaration of a class or a function
1039 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001040 // function is neither a qualified name nor a template-id, scopes outside
1041 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001042 if (!SS.isSet()) {
1043 DeclContext *OutermostContext = CurContext;
1044 while (!OutermostContext->isFileContext())
1045 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001046
Richard Smith61e582f2012-04-20 07:12:26 +00001047 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001048 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1049 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1050 SemanticContext = PrevDecl->getDeclContext();
1051 } else {
1052 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001053 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001054 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001055 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001056 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001057
1058 // Check that the chosen semantic context doesn't already contain a
1059 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001060 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001061 DeclContext *LookupContext = SemanticContext;
1062 while (LookupContext->isTransparentContext())
1063 LookupContext = LookupContext->getLookupParent();
1064 LookupQualifiedName(Previous, LookupContext);
1065
1066 if (Previous.isAmbiguous())
1067 return true;
1068
1069 if (Previous.begin() != Previous.end())
1070 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001071 }
John McCall90d3bb92009-12-17 23:21:11 +00001072 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001073 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001074 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1075 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001076 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001077
Richard Smithfc805ca2015-07-06 04:43:58 +00001078 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1079 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1080 if (SS.isEmpty() &&
1081 !(PrevClassTemplate &&
1082 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1083 SemanticContext->getRedeclContext()))) {
1084 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1085 Diag(Shadow->getTargetDecl()->getLocation(),
1086 diag::note_using_decl_target);
1087 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1088 // Recover by ignoring the old declaration.
1089 PrevDecl = PrevClassTemplate = nullptr;
1090 }
1091 }
1092
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001093 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001094 // Ensure that the template parameter lists are compatible. Skip this check
1095 // for a friend in a dependent context: the template parameter list itself
1096 // could be dependent.
1097 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1098 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001099 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001100 /*Complain=*/true,
1101 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001102 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001103
1104 // C++ [temp.class]p4:
1105 // In a redeclaration, partial specialization, explicit
1106 // specialization or explicit instantiation of a class template,
1107 // the class-key shall agree in kind with the original class
1108 // template declaration (7.1.5.3).
1109 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001110 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001111 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001112 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001113 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001114 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001115 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001116 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001117 }
1118
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001119 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001120 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001121 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001122 // If we have a prior definition that is not visible, treat this as
1123 // simply making that previous definition visible.
1124 NamedDecl *Hidden = nullptr;
1125 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001126 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001127 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1128 assert(Tmpl && "original definition of a class template is not a "
1129 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001130 makeMergedDefinitionVisible(Hidden, KWLoc);
1131 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001132 return Def;
1133 }
1134
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001135 Diag(NameLoc, diag::err_redefinition) << Name;
1136 Diag(Def->getLocation(), diag::note_previous_definition);
1137 // FIXME: Would it make sense to try to "forget" the previous
1138 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001139 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001140 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001141 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001142 } else if (PrevDecl) {
1143 // C++ [temp]p5:
1144 // A class template shall not have the same name as any other
1145 // template, class, function, object, enumeration, enumerator,
1146 // namespace, or type in the same scope (3.3), except as specified
1147 // in (14.5.4).
1148 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1149 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001150 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001151 }
1152
Douglas Gregordba32632009-02-10 19:49:53 +00001153 // Check the template parameter list of this declaration, possibly
1154 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001155 // template declaration. Skip this check for a friend in a dependent
1156 // context, because the template parameter list might be dependent.
1157 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001158 CheckTemplateParameterList(
1159 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001160 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1161 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001162 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1163 SemanticContext->isDependentContext())
1164 ? TPC_ClassTemplateMember
1165 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1166 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001167 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001168
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001169 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001170 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001171 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001172 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1173 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001174 : diag::err_member_decl_does_not_match)
1175 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001176 Invalid = true;
1177 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001178 }
1179
Mike Stump11289f42009-09-09 15:08:12 +00001180 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001181 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001182 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001183 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001184 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001185 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001186 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001187 NewClass->setTemplateParameterListsInfo(
1188 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1189 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001190
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001191 // Add alignment attributes if necessary; these attributes are checked when
1192 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001193 if (TUK == TUK_Definition) {
1194 AddAlignmentAttributesForRecord(NewClass);
1195 AddMsStructLayoutForRecord(NewClass);
1196 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001197
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001198 ClassTemplateDecl *NewTemplate
1199 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1200 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001201 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001202 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001203
Douglas Gregor21823bf2011-12-20 18:11:52 +00001204 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001205 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001206
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001207 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001208 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001209 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001210 assert(T->isDependentType() && "Class template type is not dependent?");
1211 (void)T;
1212
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001213 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001214 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001215 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001216 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1217 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001218
Anders Carlsson137108d2009-03-26 01:24:28 +00001219 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001220 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001221 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001222
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001223 // Set the lexical context of these templates
1224 NewClass->setLexicalDeclContext(CurContext);
1225 NewTemplate->setLexicalDeclContext(CurContext);
1226
John McCall9bb74a52009-07-31 02:45:11 +00001227 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001228 NewClass->startDefinition();
1229
1230 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001231 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001232
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001233 if (PrevClassTemplate)
1234 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1235
Rafael Espindola385c0422012-07-13 18:04:45 +00001236 AddPushedVisibilityAttribute(NewClass);
1237
Richard Smith234ff472014-08-23 00:49:01 +00001238 if (TUK != TUK_Friend) {
1239 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1240 Scope *Outer = S;
1241 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1242 Outer = Outer->getParent();
1243 PushOnScopeChains(NewTemplate, Outer);
1244 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001245 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001246 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001247 NewClass->setAccess(PrevClassTemplate->getAccess());
1248 }
John McCall27b5c252009-09-14 21:59:20 +00001249
Richard Smith64017682013-07-17 23:53:16 +00001250 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001251
John McCall27b5c252009-09-14 21:59:20 +00001252 // Friend templates are visible in fairly strange ways.
1253 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001254 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001255 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001256 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1257 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001258 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001259 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001260
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001261 FriendDecl *Friend = FriendDecl::Create(
1262 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001263 Friend->setAccess(AS_public);
1264 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001265 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001266
Douglas Gregordba32632009-02-10 19:49:53 +00001267 if (Invalid) {
1268 NewTemplate->setInvalidDecl();
1269 NewClass->setInvalidDecl();
1270 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001271
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001272 ActOnDocumentableDecl(NewTemplate);
1273
John McCall48871652010-08-21 09:40:31 +00001274 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001275}
1276
Douglas Gregored5731f2009-11-25 17:50:39 +00001277/// \brief Diagnose the presence of a default template argument on a
1278/// template parameter, which is ill-formed in certain contexts.
1279///
1280/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001281static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001282 Sema::TemplateParamListContext TPC,
1283 SourceLocation ParamLoc,
1284 SourceRange DefArgRange) {
1285 switch (TPC) {
1286 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001287 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001288 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001289 return false;
1290
1291 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001292 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001293 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001294 // A default template-argument shall not be specified in a
1295 // function template declaration or a function template
1296 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001297 // If a friend function template declaration specifies a default
1298 // template-argument, that declaration shall be a definition and shall be
1299 // the only declaration of the function template in the translation unit.
1300 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001301 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001302 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1303 : diag::ext_template_parameter_default_in_function_template)
1304 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001305 return false;
1306
1307 case Sema::TPC_ClassTemplateMember:
1308 // C++0x [temp.param]p9:
1309 // A default template-argument shall not be specified in the
1310 // template-parameter-lists of the definition of a member of a
1311 // class template that appears outside of the member's class.
1312 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1313 << DefArgRange;
1314 return true;
1315
David Majnemerba8f17a2013-06-25 22:08:55 +00001316 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001317 case Sema::TPC_FriendFunctionTemplate:
1318 // C++ [temp.param]p9:
1319 // A default template-argument shall not be specified in a
1320 // friend template declaration.
1321 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1322 << DefArgRange;
1323 return true;
1324
1325 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1326 // for friend function templates if there is only a single
1327 // declaration (and it is a definition). Strange!
1328 }
1329
David Blaikie8a40f702012-01-17 06:56:22 +00001330 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001331}
1332
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001333/// \brief Check for unexpanded parameter packs within the template parameters
1334/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001335static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1336 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001337 // A template template parameter which is a parameter pack is also a pack
1338 // expansion.
1339 if (TTP->isParameterPack())
1340 return false;
1341
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001342 TemplateParameterList *Params = TTP->getTemplateParameters();
1343 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1344 NamedDecl *P = Params->getParam(I);
1345 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001346 if (!NTTP->isParameterPack() &&
1347 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001348 NTTP->getTypeSourceInfo(),
1349 Sema::UPPC_NonTypeTemplateParameterType))
1350 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001352 continue;
1353 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001354
1355 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001356 = dyn_cast<TemplateTemplateParmDecl>(P))
1357 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1358 return true;
1359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001360
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001361 return false;
1362}
1363
Douglas Gregordba32632009-02-10 19:49:53 +00001364/// \brief Checks the validity of a template parameter list, possibly
1365/// considering the template parameter list from a previous
1366/// declaration.
1367///
1368/// If an "old" template parameter list is provided, it must be
1369/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1370/// template parameter list.
1371///
1372/// \param NewParams Template parameter list for a new template
1373/// declaration. This template parameter list will be updated with any
1374/// default arguments that are carried through from the previous
1375/// template parameter list.
1376///
1377/// \param OldParams If provided, template parameter list from a
1378/// previous declaration of the same template. Default template
1379/// arguments will be merged from the old template parameter list to
1380/// the new template parameter list.
1381///
Douglas Gregored5731f2009-11-25 17:50:39 +00001382/// \param TPC Describes the context in which we are checking the given
1383/// template parameter list.
1384///
Douglas Gregordba32632009-02-10 19:49:53 +00001385/// \returns true if an error occurred, false otherwise.
1386bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001387 TemplateParameterList *OldParams,
1388 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001389 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001390
Douglas Gregordba32632009-02-10 19:49:53 +00001391 // C++ [temp.param]p10:
1392 // The set of default template-arguments available for use with a
1393 // template declaration or definition is obtained by merging the
1394 // default arguments from the definition (if in scope) and all
1395 // declarations in scope in the same way default function
1396 // arguments are (8.3.6).
1397 bool SawDefaultArgument = false;
1398 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001399
Mike Stumpc89c8e32009-02-11 23:03:27 +00001400 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001401 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001402 if (OldParams)
1403 OldParam = OldParams->begin();
1404
Douglas Gregor0693def2011-01-27 01:40:17 +00001405 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001406 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1407 NewParamEnd = NewParams->end();
1408 NewParam != NewParamEnd; ++NewParam) {
1409 // Variables used to diagnose redundant default arguments
1410 bool RedundantDefaultArg = false;
1411 SourceLocation OldDefaultLoc;
1412 SourceLocation NewDefaultLoc;
1413
David Blaikie651c73c2011-10-19 05:19:50 +00001414 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001415 bool MissingDefaultArg = false;
1416
David Blaikie651c73c2011-10-19 05:19:50 +00001417 // Variable used to diagnose non-final parameter packs
1418 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001419
Douglas Gregordba32632009-02-10 19:49:53 +00001420 if (TemplateTypeParmDecl *NewTypeParm
1421 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001422 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001423 if (NewTypeParm->hasDefaultArgument() &&
1424 DiagnoseDefaultTemplateArgument(*this, TPC,
1425 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001426 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001427 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001428 NewTypeParm->removeDefaultArgument();
1429
1430 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001431 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001432 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001433 if (NewTypeParm->isParameterPack()) {
1434 assert(!NewTypeParm->hasDefaultArgument() &&
1435 "Parameter packs can't have a default argument!");
1436 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001437 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001438 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001439 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1440 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1441 SawDefaultArgument = true;
1442 RedundantDefaultArg = true;
1443 PreviousDefaultArgLoc = NewDefaultLoc;
1444 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1445 // Merge the default argument from the old declaration to the
1446 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001447 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001448 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1449 } else if (NewTypeParm->hasDefaultArgument()) {
1450 SawDefaultArgument = true;
1451 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1452 } else if (SawDefaultArgument)
1453 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001454 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001455 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001456 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001457 if (!NewNonTypeParm->isParameterPack() &&
1458 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001459 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001460 UPPC_NonTypeTemplateParameterType)) {
1461 Invalid = true;
1462 continue;
1463 }
1464
Douglas Gregored5731f2009-11-25 17:50:39 +00001465 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001466 if (NewNonTypeParm->hasDefaultArgument() &&
1467 DiagnoseDefaultTemplateArgument(*this, TPC,
1468 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001469 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001470 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001471 }
1472
Mike Stump12b8ce12009-08-04 21:02:39 +00001473 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001474 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001475 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001476 if (NewNonTypeParm->isParameterPack()) {
1477 assert(!NewNonTypeParm->hasDefaultArgument() &&
1478 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001479 if (!NewNonTypeParm->isPackExpansion())
1480 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001481 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001482 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001483 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1484 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1485 SawDefaultArgument = true;
1486 RedundantDefaultArg = true;
1487 PreviousDefaultArgLoc = NewDefaultLoc;
1488 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1489 // Merge the default argument from the old declaration to the
1490 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001491 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001492 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1493 } else if (NewNonTypeParm->hasDefaultArgument()) {
1494 SawDefaultArgument = true;
1495 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1496 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001497 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001498 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001499 TemplateTemplateParmDecl *NewTemplateParm
1500 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001501
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001502 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001503 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001504 Invalid = true;
1505 continue;
1506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001507
David Blaikie651c73c2011-10-19 05:19:50 +00001508 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001509 if (NewTemplateParm->hasDefaultArgument() &&
1510 DiagnoseDefaultTemplateArgument(*this, TPC,
1511 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001512 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001513 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001514
1515 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001516 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001517 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001518 if (NewTemplateParm->isParameterPack()) {
1519 assert(!NewTemplateParm->hasDefaultArgument() &&
1520 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001521 if (!NewTemplateParm->isPackExpansion())
1522 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001523 } else if (OldTemplateParm &&
1524 hasVisibleDefaultArgument(OldTemplateParm) &&
1525 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001526 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1527 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001528 SawDefaultArgument = true;
1529 RedundantDefaultArg = true;
1530 PreviousDefaultArgLoc = NewDefaultLoc;
1531 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1532 // Merge the default argument from the old declaration to the
1533 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001534 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001535 PreviousDefaultArgLoc
1536 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001537 } else if (NewTemplateParm->hasDefaultArgument()) {
1538 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001539 PreviousDefaultArgLoc
1540 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001541 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001542 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001543 }
1544
Richard Smith1fde8ec2012-09-07 02:06:42 +00001545 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001546 // If a template parameter of a primary class template or alias template
1547 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001548 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001549 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1550 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001551 Diag((*NewParam)->getLocation(),
1552 diag::err_template_param_pack_must_be_last_template_parameter);
1553 Invalid = true;
1554 }
1555
Douglas Gregordba32632009-02-10 19:49:53 +00001556 if (RedundantDefaultArg) {
1557 // C++ [temp.param]p12:
1558 // A template-parameter shall not be given default arguments
1559 // by two different declarations in the same scope.
1560 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1561 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1562 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001563 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001564 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001565 // If a template-parameter of a class template has a default
1566 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001567 // have a default template-argument supplied or be a template parameter
1568 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001569 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001570 diag::err_template_param_default_arg_missing);
1571 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1572 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001573 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001574 }
1575
1576 // If we have an old template parameter list that we're merging
1577 // in, move on to the next parameter.
1578 if (OldParams)
1579 ++OldParam;
1580 }
1581
Douglas Gregor0693def2011-01-27 01:40:17 +00001582 // We were missing some default arguments at the end of the list, so remove
1583 // all of the default arguments.
1584 if (RemoveDefaultArguments) {
1585 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1586 NewParamEnd = NewParams->end();
1587 NewParam != NewParamEnd; ++NewParam) {
1588 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1589 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001590 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001591 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1592 NTTP->removeDefaultArgument();
1593 else
1594 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1595 }
1596 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001597
Douglas Gregordba32632009-02-10 19:49:53 +00001598 return Invalid;
1599}
Douglas Gregord32e0282009-02-09 23:23:08 +00001600
John McCalla020a012010-10-20 05:44:58 +00001601namespace {
1602
1603/// A class which looks for a use of a certain level of template
1604/// parameter.
1605struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1606 typedef RecursiveASTVisitor<DependencyChecker> super;
1607
1608 unsigned Depth;
1609 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001610 SourceLocation MatchLoc;
1611
1612 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001613
1614 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1615 NamedDecl *ND = Params->getParam(0);
1616 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1617 Depth = PD->getDepth();
1618 } else if (NonTypeTemplateParmDecl *PD =
1619 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1620 Depth = PD->getDepth();
1621 } else {
1622 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1623 }
1624 }
1625
Richard Smith6056d5e2014-02-09 00:54:43 +00001626 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001627 if (ParmDepth >= Depth) {
1628 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001629 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001630 return true;
1631 }
1632 return false;
1633 }
1634
Richard Smith6056d5e2014-02-09 00:54:43 +00001635 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1636 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1637 }
1638
John McCalla020a012010-10-20 05:44:58 +00001639 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1640 return !Matches(T->getDepth());
1641 }
1642
1643 bool TraverseTemplateName(TemplateName N) {
1644 if (TemplateTemplateParmDecl *PD =
1645 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001646 if (Matches(PD->getDepth()))
1647 return false;
John McCalla020a012010-10-20 05:44:58 +00001648 return super::TraverseTemplateName(N);
1649 }
1650
1651 bool VisitDeclRefExpr(DeclRefExpr *E) {
1652 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001653 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1654 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001655 return false;
John McCalla020a012010-10-20 05:44:58 +00001656 return super::VisitDeclRefExpr(E);
1657 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001658
1659 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1660 return TraverseType(T->getReplacementType());
1661 }
1662
1663 bool
1664 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1665 return TraverseTemplateArgument(T->getArgumentPack());
1666 }
1667
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001668 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1669 return TraverseType(T->getInjectedSpecializationType());
1670 }
John McCalla020a012010-10-20 05:44:58 +00001671};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001672} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001673
Douglas Gregor972fe532011-05-10 18:27:06 +00001674/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001675/// list.
1676static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001677DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001678 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001679 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001680 return Checker.Match;
1681}
1682
Douglas Gregor972fe532011-05-10 18:27:06 +00001683// Find the source range corresponding to the named type in the given
1684// nested-name-specifier, if any.
1685static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1686 QualType T,
1687 const CXXScopeSpec &SS) {
1688 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1689 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1690 if (const Type *CurType = NNS->getAsType()) {
1691 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1692 return NNSLoc.getTypeLoc().getSourceRange();
1693 } else
1694 break;
1695
1696 NNSLoc = NNSLoc.getPrefix();
1697 }
1698
1699 return SourceRange();
1700}
1701
Mike Stump11289f42009-09-09 15:08:12 +00001702/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001703/// specifier, returning the template parameter list that applies to the
1704/// name.
1705///
1706/// \param DeclStartLoc the start of the declaration that has a scope
1707/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001708///
Douglas Gregor972fe532011-05-10 18:27:06 +00001709/// \param DeclLoc The location of the declaration itself.
1710///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001711/// \param SS the scope specifier that will be matched to the given template
1712/// parameter lists. This scope specifier precedes a qualified name that is
1713/// being declared.
1714///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001715/// \param TemplateId The template-id following the scope specifier, if there
1716/// is one. Used to check for a missing 'template<>'.
1717///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001718/// \param ParamLists the template parameter lists, from the outermost to the
1719/// innermost template parameter lists.
1720///
John McCalle820e5e2010-04-13 20:37:33 +00001721/// \param IsFriend Whether to apply the slightly different rules for
1722/// matching template parameters to scope specifiers in friend
1723/// declarations.
1724///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001725/// \param IsExplicitSpecialization will be set true if the entity being
1726/// declared is an explicit specialization, false otherwise.
1727///
Mike Stump11289f42009-09-09 15:08:12 +00001728/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001729/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001730/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001731/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001732/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001733/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001734TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1735 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001736 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001737 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1738 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001739 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001740 Invalid = false;
1741
1742 // The sequence of nested types to which we will match up the template
1743 // parameter lists. We first build this list by starting with the type named
1744 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001745 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001746 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001747 if (SS.getScopeRep()) {
1748 if (CXXRecordDecl *Record
1749 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1750 T = Context.getTypeDeclType(Record);
1751 else
1752 T = QualType(SS.getScopeRep()->getAsType(), 0);
1753 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001754
1755 // If we found an explicit specialization that prevents us from needing
1756 // 'template<>' headers, this will be set to the location of that
1757 // explicit specialization.
1758 SourceLocation ExplicitSpecLoc;
1759
1760 while (!T.isNull()) {
1761 NestedTypes.push_back(T);
1762
1763 // Retrieve the parent of a record type.
1764 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1765 // If this type is an explicit specialization, we're done.
1766 if (ClassTemplateSpecializationDecl *Spec
1767 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1768 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1769 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1770 ExplicitSpecLoc = Spec->getLocation();
1771 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001772 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001773 } else if (Record->getTemplateSpecializationKind()
1774 == TSK_ExplicitSpecialization) {
1775 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001776 break;
1777 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001778
1779 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1780 T = Context.getTypeDeclType(Parent);
1781 else
1782 T = QualType();
1783 continue;
1784 }
1785
1786 if (const TemplateSpecializationType *TST
1787 = T->getAs<TemplateSpecializationType>()) {
1788 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1789 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1790 T = Context.getTypeDeclType(Parent);
1791 else
1792 T = QualType();
1793 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001794 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001795 }
1796
1797 // Look one step prior in a dependent template specialization type.
1798 if (const DependentTemplateSpecializationType *DependentTST
1799 = T->getAs<DependentTemplateSpecializationType>()) {
1800 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1801 T = QualType(NNS->getAsType(), 0);
1802 else
1803 T = QualType();
1804 continue;
1805 }
1806
1807 // Look one step prior in a dependent name type.
1808 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1809 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1810 T = QualType(NNS->getAsType(), 0);
1811 else
1812 T = QualType();
1813 continue;
1814 }
1815
1816 // Retrieve the parent of an enumeration type.
1817 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1818 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1819 // check here.
1820 EnumDecl *Enum = EnumT->getDecl();
1821
1822 // Get to the parent type.
1823 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1824 T = Context.getTypeDeclType(Parent);
1825 else
1826 T = QualType();
1827 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001828 }
Mike Stump11289f42009-09-09 15:08:12 +00001829
Douglas Gregor972fe532011-05-10 18:27:06 +00001830 T = QualType();
1831 }
1832 // Reverse the nested types list, since we want to traverse from the outermost
1833 // to the innermost while checking template-parameter-lists.
1834 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001835
Douglas Gregor972fe532011-05-10 18:27:06 +00001836 // C++0x [temp.expl.spec]p17:
1837 // A member or a member template may be nested within many
1838 // enclosing class templates. In an explicit specialization for
1839 // such a member, the member declaration shall be preceded by a
1840 // template<> for each enclosing class template that is
1841 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001842 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001843
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001844 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001845 if (SawNonEmptyTemplateParameterList) {
1846 Diag(DeclLoc, diag::err_specialize_member_of_template)
1847 << !Recovery << Range;
1848 Invalid = true;
1849 IsExplicitSpecialization = false;
1850 return true;
1851 }
1852
1853 return false;
1854 };
1855
1856 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1857 // Check that we can have an explicit specialization here.
1858 if (CheckExplicitSpecialization(Range, true))
1859 return true;
1860
1861 // We don't have a template header, but we should.
1862 SourceLocation ExpectedTemplateLoc;
1863 if (!ParamLists.empty())
1864 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1865 else
1866 ExpectedTemplateLoc = DeclStartLoc;
1867
1868 Diag(DeclLoc, diag::err_template_spec_needs_header)
1869 << Range
1870 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1871 return false;
1872 };
1873
Douglas Gregor972fe532011-05-10 18:27:06 +00001874 unsigned ParamIdx = 0;
1875 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1876 ++TypeIdx) {
1877 T = NestedTypes[TypeIdx];
1878
1879 // Whether we expect a 'template<>' header.
1880 bool NeedEmptyTemplateHeader = false;
1881
1882 // Whether we expect a template header with parameters.
1883 bool NeedNonemptyTemplateHeader = false;
1884
1885 // For a dependent type, the set of template parameters that we
1886 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001887 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001888
Douglas Gregor373af9b2011-05-11 23:26:17 +00001889 // C++0x [temp.expl.spec]p15:
1890 // A member or a member template may be nested within many enclosing
1891 // class templates. In an explicit specialization for such a member, the
1892 // member declaration shall be preceded by a template<> for each
1893 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001894 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1895 if (ClassTemplatePartialSpecializationDecl *Partial
1896 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1897 ExpectedTemplateParams = Partial->getTemplateParameters();
1898 NeedNonemptyTemplateHeader = true;
1899 } else if (Record->isDependentType()) {
1900 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001901 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001902 ->getTemplateParameters();
1903 NeedNonemptyTemplateHeader = true;
1904 }
1905 } else if (ClassTemplateSpecializationDecl *Spec
1906 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1907 // C++0x [temp.expl.spec]p4:
1908 // Members of an explicitly specialized class template are defined
1909 // in the same manner as members of normal classes, and not using
1910 // the template<> syntax.
1911 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1912 NeedEmptyTemplateHeader = true;
1913 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001914 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001915 } else if (Record->getTemplateSpecializationKind()) {
1916 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001917 != TSK_ExplicitSpecialization &&
1918 TypeIdx == NumTypes - 1)
1919 IsExplicitSpecialization = true;
1920
1921 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001922 }
1923 } else if (const TemplateSpecializationType *TST
1924 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001925 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001926 ExpectedTemplateParams = Template->getTemplateParameters();
1927 NeedNonemptyTemplateHeader = true;
1928 }
1929 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1930 // FIXME: We actually could/should check the template arguments here
1931 // against the corresponding template parameter list.
1932 NeedNonemptyTemplateHeader = false;
1933 }
1934
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001935 // C++ [temp.expl.spec]p16:
1936 // In an explicit specialization declaration for a member of a class
1937 // template or a member template that ap- pears in namespace scope, the
1938 // member template and some of its enclosing class templates may remain
1939 // unspecialized, except that the declaration shall not explicitly
1940 // specialize a class member template if its en- closing class templates
1941 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001942 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001943 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001944 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1945 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001946 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001947 } else
1948 SawNonEmptyTemplateParameterList = true;
1949 }
1950
Douglas Gregor972fe532011-05-10 18:27:06 +00001951 if (NeedEmptyTemplateHeader) {
1952 // If we're on the last of the types, and we need a 'template<>' header
1953 // here, then it's an explicit specialization.
1954 if (TypeIdx == NumTypes - 1)
1955 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001956
1957 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001958 if (ParamLists[ParamIdx]->size() > 0) {
1959 // The header has template parameters when it shouldn't. Complain.
1960 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1961 diag::err_template_param_list_matches_nontemplate)
1962 << T
1963 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1964 ParamLists[ParamIdx]->getRAngleLoc())
1965 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1966 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001967 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001968 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001969
Douglas Gregor972fe532011-05-10 18:27:06 +00001970 // Consume this template header.
1971 ++ParamIdx;
1972 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001973 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001974
1975 if (!IsFriend)
1976 if (DiagnoseMissingExplicitSpecialization(
1977 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001978 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001979
Douglas Gregor972fe532011-05-10 18:27:06 +00001980 continue;
1981 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001982
Douglas Gregor972fe532011-05-10 18:27:06 +00001983 if (NeedNonemptyTemplateHeader) {
1984 // In friend declarations we can have template-ids which don't
1985 // depend on the corresponding template parameter lists. But
1986 // assume that empty parameter lists are supposed to match this
1987 // template-id.
1988 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001989 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001990 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001991 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001992 else
1993 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001994 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001995
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001996 if (ParamIdx < ParamLists.size()) {
1997 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001998 if (ExpectedTemplateParams &&
1999 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2000 ExpectedTemplateParams,
2001 true, TPL_TemplateMatch))
2002 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002003
Douglas Gregor972fe532011-05-10 18:27:06 +00002004 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002005 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002006 TPC_ClassTemplateMember))
2007 Invalid = true;
2008
2009 ++ParamIdx;
2010 continue;
2011 }
2012
2013 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2014 << T
2015 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2016 Invalid = true;
2017 continue;
2018 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002019 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002020
Douglas Gregord8d297c2009-07-21 23:53:31 +00002021 // If there were at least as many template-ids as there were template
2022 // parameter lists, then there are no template parameter lists remaining for
2023 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002024 if (ParamIdx >= ParamLists.size()) {
2025 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002026 // We don't have a template header for the declaration itself, but we
2027 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002028 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00002029 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2030 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002031
2032 // Fabricate an empty template parameter list for the invented header.
2033 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002034 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002035 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002036 }
2037
Craig Topperc3ec1492014-05-26 06:22:03 +00002038 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002039 }
Mike Stump11289f42009-09-09 15:08:12 +00002040
Douglas Gregord8d297c2009-07-21 23:53:31 +00002041 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002042 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002043 bool HasAnyExplicitSpecHeader = false;
2044 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002045 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002046 if (ParamLists[I]->size() == 0)
2047 HasAnyExplicitSpecHeader = true;
2048 else
2049 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002050 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002051
Douglas Gregor972fe532011-05-10 18:27:06 +00002052 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002053 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2054 : diag::err_template_spec_extra_headers)
2055 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2056 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002057
2058 // If there was a specialization somewhere, such that 'template<>' is
2059 // not required, and there were any 'template<>' headers, note where the
2060 // specialization occurred.
2061 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2062 Diag(ExplicitSpecLoc,
2063 diag::note_explicit_template_spec_does_not_need_header)
2064 << NestedTypes.back();
2065
2066 // We have a template parameter list with no corresponding scope, which
2067 // means that the resulting template declaration can't be instantiated
2068 // properly (we'll end up with dependent nodes when we shouldn't).
2069 if (!AllExplicitSpecHeaders)
2070 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002071 }
Mike Stump11289f42009-09-09 15:08:12 +00002072
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002073 // C++ [temp.expl.spec]p16:
2074 // In an explicit specialization declaration for a member of a class
2075 // template or a member template that ap- pears in namespace scope, the
2076 // member template and some of its enclosing class templates may remain
2077 // unspecialized, except that the declaration shall not explicitly
2078 // specialize a class member template if its en- closing class templates
2079 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002080 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002081 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2082 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002083 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002084
Douglas Gregord8d297c2009-07-21 23:53:31 +00002085 // Return the last template parameter list, which corresponds to the
2086 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002087 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002088}
2089
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002090void Sema::NoteAllFoundTemplates(TemplateName Name) {
2091 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2092 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002093 << (isa<FunctionTemplateDecl>(Template)
2094 ? 0
2095 : isa<ClassTemplateDecl>(Template)
2096 ? 1
2097 : isa<VarTemplateDecl>(Template)
2098 ? 2
2099 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2100 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002101 return;
2102 }
2103
2104 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2105 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2106 IEnd = OST->end();
2107 I != IEnd; ++I)
2108 Diag((*I)->getLocation(), diag::note_template_declared_here)
2109 << 0 << (*I)->getDeclName();
2110
2111 return;
2112 }
2113}
2114
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002115static QualType
2116checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2117 const SmallVectorImpl<TemplateArgument> &Converted,
2118 SourceLocation TemplateLoc,
2119 TemplateArgumentListInfo &TemplateArgs) {
2120 ASTContext &Context = SemaRef.getASTContext();
2121 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002122 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002123 // Specializations of __make_integer_seq<S, T, N> are treated like
2124 // S<T, 0, ..., N-1>.
2125
2126 // C++14 [inteseq.intseq]p1:
2127 // T shall be an integer type.
2128 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2129 SemaRef.Diag(TemplateArgs[1].getLocation(),
2130 diag::err_integer_sequence_integral_element_type);
2131 return QualType();
2132 }
2133
2134 // C++14 [inteseq.make]p1:
2135 // If N is negative the program is ill-formed.
2136 TemplateArgument NumArgsArg = Converted[2];
2137 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2138 if (NumArgs < 0) {
2139 SemaRef.Diag(TemplateArgs[2].getLocation(),
2140 diag::err_integer_sequence_negative_length);
2141 return QualType();
2142 }
2143
2144 QualType ArgTy = NumArgsArg.getIntegralType();
2145 TemplateArgumentListInfo SyntheticTemplateArgs;
2146 // The type argument gets reused as the first template argument in the
2147 // synthetic template argument list.
2148 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2149 // Expand N into 0 ... N-1.
2150 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2151 I < NumArgs; ++I) {
2152 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002153 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2154 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002155 }
2156 // The first template argument will be reused as the template decl that
2157 // our synthetic template arguments will be applied to.
2158 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2159 TemplateLoc, SyntheticTemplateArgs);
2160 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002161
2162 case BTK__type_pack_element:
2163 // Specializations of
2164 // __type_pack_element<Index, T_1, ..., T_N>
2165 // are treated like T_Index.
2166 assert(Converted.size() == 2 &&
2167 "__type_pack_element should be given an index and a parameter pack");
2168
2169 // If the Index is out of bounds, the program is ill-formed.
2170 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2171 llvm::APSInt Index = IndexArg.getAsIntegral();
2172 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2173 "type std::size_t, and hence be non-negative");
2174 if (Index >= Ts.pack_size()) {
2175 SemaRef.Diag(TemplateArgs[0].getLocation(),
2176 diag::err_type_pack_element_out_of_bounds);
2177 return QualType();
2178 }
2179
2180 // We simply return the type at index `Index`.
2181 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2182 return Nth->getAsType();
2183 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002184 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2185}
2186
Douglas Gregordc572a32009-03-30 22:58:21 +00002187QualType Sema::CheckTemplateIdType(TemplateName Name,
2188 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002189 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002190 DependentTemplateName *DTN
2191 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002192 if (DTN && DTN->isIdentifier())
2193 // When building a template-id where the template-name is dependent,
2194 // assume the template is a type template. Either our assumption is
2195 // correct, or the code is ill-formed and will be diagnosed when the
2196 // dependent name is substituted.
2197 return Context.getDependentTemplateSpecializationType(ETK_None,
2198 DTN->getQualifier(),
2199 DTN->getIdentifier(),
2200 TemplateArgs);
2201
Douglas Gregordc572a32009-03-30 22:58:21 +00002202 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002203 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2204 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002205 // We might have a substituted template template parameter pack. If so,
2206 // build a template specialization type for it.
2207 if (Name.getAsSubstTemplateTemplateParmPack())
2208 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002209
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002210 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2211 << Name;
2212 NoteAllFoundTemplates(Name);
2213 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002214 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002215
Douglas Gregorc40290e2009-03-09 23:48:35 +00002216 // Check that the template argument list is well-formed for this
2217 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002218 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002219 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002220 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002221 return QualType();
2222
Douglas Gregorc40290e2009-03-09 23:48:35 +00002223 QualType CanonType;
2224
Douglas Gregor678d76c2011-07-01 01:22:09 +00002225 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002226 if (TypeAliasTemplateDecl *AliasTemplate =
2227 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002228 // Find the canonical type for this type alias template specialization.
2229 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2230 if (Pattern->isInvalidDecl())
2231 return QualType();
2232
2233 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002234 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002235
2236 // Only substitute for the innermost template argument list.
2237 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002238 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002239 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2240 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002241 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002242
Richard Smith802c4b72012-08-23 06:16:52 +00002243 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002244 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002245 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002246 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002247
Richard Smith3f1b5d02011-05-05 21:57:07 +00002248 CanonType = SubstType(Pattern->getUnderlyingType(),
2249 TemplateArgLists, AliasTemplate->getLocation(),
2250 AliasTemplate->getDeclName());
2251 if (CanonType.isNull())
2252 return QualType();
2253 } else if (Name.isDependent() ||
2254 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002255 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002256 // This class template specialization is a dependent
2257 // type. Therefore, its canonical type is another class template
2258 // specialization type that contains all of the converted
2259 // arguments in canonical form. This ensures that, e.g., A<T> and
2260 // A<T, T> have identical types when A is declared as:
2261 //
2262 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002263 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002264 CanonType = Context.getTemplateSpecializationType(CanonName,
David Majnemer6fbeee32016-07-07 04:43:07 +00002265 Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002266
Douglas Gregora8e02e72009-07-28 23:00:59 +00002267 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002268 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002269 // In the future, we need to teach getTemplateSpecializationType to only
2270 // build the canonical type and return that to us.
2271 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002272
2273 // This might work out to be a current instantiation, in which
2274 // case the canonical type needs to be the InjectedClassNameType.
2275 //
2276 // TODO: in theory this could be a simple hashtable lookup; most
2277 // changes to CurContext don't change the set of current
2278 // instantiations.
2279 if (isa<ClassTemplateDecl>(Template)) {
2280 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2281 // If we get out to a namespace, we're done.
2282 if (Ctx->isFileContext()) break;
2283
2284 // If this isn't a record, keep looking.
2285 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2286 if (!Record) continue;
2287
2288 // Look for one of the two cases with InjectedClassNameTypes
2289 // and check whether it's the same template.
2290 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2291 !Record->getDescribedClassTemplate())
2292 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002293
John McCall2408e322010-04-27 00:57:59 +00002294 // Fetch the injected class name type and check whether its
2295 // injected type is equal to the type we just built.
2296 QualType ICNT = Context.getTypeDeclType(Record);
2297 QualType Injected = cast<InjectedClassNameType>(ICNT)
2298 ->getInjectedSpecializationType();
2299
2300 if (CanonType != Injected->getCanonicalTypeInternal())
2301 continue;
2302
2303 // If so, the canonical type of this TST is the injected
2304 // class name type of the record we just found.
2305 assert(ICNT.isCanonical());
2306 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002307 break;
2308 }
2309 }
Mike Stump11289f42009-09-09 15:08:12 +00002310 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002311 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002312 // Find the class template specialization declaration that
2313 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002314 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002315 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002316 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002317 if (!Decl) {
2318 // This is the first time we have referenced this class template
2319 // specialization. Create the canonical declaration and add it to
2320 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002321 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002322 ClassTemplate->getTemplatedDecl()->getTagKind(),
2323 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002324 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002325 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002326 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00002327 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002328 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002329 if (ClassTemplate->isOutOfLine())
2330 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002331 }
2332
Chandler Carruth2acfb222013-09-27 22:14:40 +00002333 // Diagnose uses of this specialization.
2334 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2335
Douglas Gregorc40290e2009-03-09 23:48:35 +00002336 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002337 assert(isa<RecordType>(CanonType) &&
2338 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002339 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2340 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2341 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002342 }
Mike Stump11289f42009-09-09 15:08:12 +00002343
Douglas Gregorc40290e2009-03-09 23:48:35 +00002344 // Build the fully-sugared type for this class template
2345 // specialization, which refers back to the class template
2346 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002347 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002348}
2349
John McCallfaf5fb42010-08-26 23:41:50 +00002350TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002351Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002352 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002353 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002354 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002355 SourceLocation RAngleLoc,
2356 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002357 if (SS.isInvalid())
2358 return true;
2359
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002360 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002361
Douglas Gregorc40290e2009-03-09 23:48:35 +00002362 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002363 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002364 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002365
Douglas Gregor5a064722011-02-28 17:23:35 +00002366 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002367 QualType T
2368 = Context.getDependentTemplateSpecializationType(ETK_None,
2369 DTN->getQualifier(),
2370 DTN->getIdentifier(),
2371 TemplateArgs);
2372 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002373 TypeLocBuilder TLB;
2374 DependentTemplateSpecializationTypeLoc SpecTL
2375 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002376 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2377 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002378 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002379 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002380 SpecTL.setLAngleLoc(LAngleLoc);
2381 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002382 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2383 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2384 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2385 }
2386
John McCall6b51f282009-11-23 01:53:49 +00002387 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002388
2389 if (Result.isNull())
2390 return true;
2391
Douglas Gregore7c20652011-03-02 00:47:37 +00002392 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002393 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002394 TemplateSpecializationTypeLoc SpecTL
2395 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002396 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002397 SpecTL.setTemplateNameLoc(TemplateLoc);
2398 SpecTL.setLAngleLoc(LAngleLoc);
2399 SpecTL.setRAngleLoc(RAngleLoc);
2400 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2401 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002402
Abramo Bagnara4244b432012-01-27 08:46:19 +00002403 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2404 // constructor or destructor name (in such a case, the scope specifier
2405 // will be attached to the enclosing Decl or Expr node).
2406 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002407 // Create an elaborated-type-specifier containing the nested-name-specifier.
2408 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2409 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002410 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002411 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2412 }
2413
2414 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002415}
John McCall06f6fe8d2009-09-04 01:14:41 +00002416
Douglas Gregore7c20652011-03-02 00:47:37 +00002417TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002418 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002419 SourceLocation TagLoc,
2420 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002421 SourceLocation TemplateKWLoc,
2422 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002423 SourceLocation TemplateLoc,
2424 SourceLocation LAngleLoc,
2425 ASTTemplateArgsPtr TemplateArgsIn,
2426 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002427 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002428
2429 // Translate the parser's template argument list in our AST format.
2430 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2431 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2432
2433 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002434 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002435 ElaboratedTypeKeyword Keyword
2436 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002437
Douglas Gregore7c20652011-03-02 00:47:37 +00002438 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2439 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2440 DTN->getQualifier(),
2441 DTN->getIdentifier(),
2442 TemplateArgs);
2443
2444 // Build type-source information.
2445 TypeLocBuilder TLB;
2446 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002447 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2448 SpecTL.setElaboratedKeywordLoc(TagLoc);
2449 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002450 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002451 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002452 SpecTL.setLAngleLoc(LAngleLoc);
2453 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002454 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2455 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2456 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2457 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002458
2459 if (TypeAliasTemplateDecl *TAT =
2460 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2461 // C++0x [dcl.type.elab]p2:
2462 // If the identifier resolves to a typedef-name or the simple-template-id
2463 // resolves to an alias template specialization, the
2464 // elaborated-type-specifier is ill-formed.
2465 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2466 Diag(TAT->getLocation(), diag::note_declared_at);
2467 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002468
2469 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2470 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002471 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002472
2473 // Check the tag kind
2474 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002475 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002476
John McCalld8fe9af2009-09-08 17:47:29 +00002477 IdentifierInfo *Id = D->getIdentifier();
2478 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002479
Richard Trieucaa33d32011-06-10 03:11:26 +00002480 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002481 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002482 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002483 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002484 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002485 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002486 }
2487 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002488
Douglas Gregore7c20652011-03-02 00:47:37 +00002489 // Provide source-location information for the template specialization.
2490 TypeLocBuilder TLB;
2491 TemplateSpecializationTypeLoc SpecTL
2492 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002493 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002494 SpecTL.setTemplateNameLoc(TemplateLoc);
2495 SpecTL.setLAngleLoc(LAngleLoc);
2496 SpecTL.setRAngleLoc(RAngleLoc);
2497 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2498 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002499
Douglas Gregore7c20652011-03-02 00:47:37 +00002500 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002501 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002502 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2503 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002504 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002505 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2506 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002507}
2508
Larisse Voufo39a1e502013-08-06 01:03:05 +00002509static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002510 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2511 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002512
2513static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2514 NamedDecl *PrevDecl,
2515 SourceLocation Loc,
2516 bool IsPartialSpecialization);
2517
2518static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002519
Richard Smith300e0c32013-09-24 04:49:23 +00002520static bool isTemplateArgumentTemplateParameter(
2521 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2522 switch (Arg.getKind()) {
2523 case TemplateArgument::Null:
2524 case TemplateArgument::NullPtr:
2525 case TemplateArgument::Integral:
2526 case TemplateArgument::Declaration:
2527 case TemplateArgument::Pack:
2528 case TemplateArgument::TemplateExpansion:
2529 return false;
2530
2531 case TemplateArgument::Type: {
2532 QualType Type = Arg.getAsType();
2533 const TemplateTypeParmType *TPT =
2534 Arg.getAsType()->getAs<TemplateTypeParmType>();
2535 return TPT && !Type.hasQualifiers() &&
2536 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2537 }
2538
2539 case TemplateArgument::Expression: {
2540 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2541 if (!DRE || !DRE->getDecl())
2542 return false;
2543 const NonTypeTemplateParmDecl *NTTP =
2544 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2545 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2546 }
2547
2548 case TemplateArgument::Template:
2549 const TemplateTemplateParmDecl *TTP =
2550 dyn_cast_or_null<TemplateTemplateParmDecl>(
2551 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2552 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2553 }
2554 llvm_unreachable("unexpected kind of template argument");
2555}
2556
2557static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2558 ArrayRef<TemplateArgument> Args) {
2559 if (Params->size() != Args.size())
2560 return false;
2561
2562 unsigned Depth = Params->getDepth();
2563
2564 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2565 TemplateArgument Arg = Args[I];
2566
2567 // If the parameter is a pack expansion, the argument must be a pack
2568 // whose only element is a pack expansion.
2569 if (Params->getParam(I)->isParameterPack()) {
2570 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2571 !Arg.pack_begin()->isPackExpansion())
2572 return false;
2573 Arg = Arg.pack_begin()->getPackExpansionPattern();
2574 }
2575
2576 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2577 return false;
2578 }
2579
2580 return true;
2581}
2582
Richard Smith4b55a9c2014-04-17 03:29:33 +00002583/// Convert the parser's template argument list representation into our form.
2584static TemplateArgumentListInfo
2585makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2586 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2587 TemplateId.RAngleLoc);
2588 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2589 TemplateId.NumArgs);
2590 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2591 return TemplateArgs;
2592}
2593
Larisse Voufo39a1e502013-08-06 01:03:05 +00002594DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002595 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002596 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002597 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002598 // D must be variable template id.
2599 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2600 "Variable template specialization is declared with a template it.");
2601
2602 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002603 TemplateArgumentListInfo TemplateArgs =
2604 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002605 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2606 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2607 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002608
Richard Smithbeef3452014-01-16 23:39:20 +00002609 TemplateName Name = TemplateId->Template.get();
2610
2611 // The template-id must name a variable template.
2612 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002613 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2614 if (!VarTemplate) {
2615 NamedDecl *FnTemplate;
2616 if (auto *OTS = Name.getAsOverloadedTemplate())
2617 FnTemplate = *OTS->begin();
2618 else
2619 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2620 if (FnTemplate)
2621 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2622 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002623 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2624 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002625 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002626
2627 // Check for unexpanded parameter packs in any of the template arguments.
2628 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2629 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2630 UPPC_PartialSpecialization))
2631 return true;
2632
2633 // Check that the template argument list is well-formed for this
2634 // template.
2635 SmallVector<TemplateArgument, 4> Converted;
2636 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2637 false, Converted))
2638 return true;
2639
Larisse Voufo39a1e502013-08-06 01:03:05 +00002640 // Find the variable template (partial) specialization declaration that
2641 // corresponds to these arguments.
2642 if (IsPartialSpecialization) {
2643 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002644 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2645 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002646 return true;
2647
2648 bool InstantiationDependent;
2649 if (!Name.isDependent() &&
2650 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00002651 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00002652 InstantiationDependent)) {
2653 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2654 << VarTemplate->getDeclName();
2655 IsPartialSpecialization = false;
2656 }
Richard Smith300e0c32013-09-24 04:49:23 +00002657
2658 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2659 Converted)) {
2660 // C++ [temp.class.spec]p9b3:
2661 //
2662 // -- The argument list of the specialization shall not be identical
2663 // to the implicit argument list of the primary template.
2664 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2665 << /*variable template*/ 1
2666 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2667 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2668 // FIXME: Recover from this by treating the declaration as a redeclaration
2669 // of the primary template.
2670 return true;
2671 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002672 }
2673
Craig Topperc3ec1492014-05-26 06:22:03 +00002674 void *InsertPos = nullptr;
2675 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002676
2677 if (IsPartialSpecialization)
2678 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002679 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002680 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002681 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002682
Craig Topperc3ec1492014-05-26 06:22:03 +00002683 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002684
2685 // Check whether we can declare a variable template specialization in
2686 // the current scope.
2687 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2688 TemplateNameLoc,
2689 IsPartialSpecialization))
2690 return true;
2691
2692 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2693 // Since the only prior variable template specialization with these
2694 // arguments was referenced but not declared, reuse that
2695 // declaration node as our own, updating its source location and
2696 // the list of outer template parameters to reflect our new declaration.
2697 Specialization = PrevDecl;
2698 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002699 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002700 } else if (IsPartialSpecialization) {
2701 // Create a new class template partial specialization declaration node.
2702 VarTemplatePartialSpecializationDecl *PrevPartial =
2703 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002704 VarTemplatePartialSpecializationDecl *Partial =
2705 VarTemplatePartialSpecializationDecl::Create(
2706 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2707 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00002708 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002709
2710 if (!PrevPartial)
2711 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2712 Specialization = Partial;
2713
2714 // If we are providing an explicit specialization of a member variable
2715 // template specialization, make a note of that.
2716 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002717 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002718
2719 // Check that all of the template parameters of the variable template
2720 // partial specialization are deducible from the template
2721 // arguments. If not, this variable template partial specialization
2722 // will never be used.
2723 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2724 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2725 TemplateParams->getDepth(), DeducibleParams);
2726
2727 if (!DeducibleParams.all()) {
2728 unsigned NumNonDeducible =
2729 DeducibleParams.size() - DeducibleParams.count();
2730 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002731 << /*variable template*/ 1 << (NumNonDeducible > 1)
2732 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002733 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2734 if (!DeducibleParams[I]) {
2735 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2736 if (Param->getDeclName())
2737 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2738 << Param->getDeclName();
2739 else
2740 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002741 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002742 }
2743 }
2744 }
2745 } else {
2746 // Create a new class template specialization declaration node for
2747 // this explicit specialization or friend declaration.
2748 Specialization = VarTemplateSpecializationDecl::Create(
2749 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00002750 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002751 Specialization->setTemplateArgsInfo(TemplateArgs);
2752
2753 if (!PrevDecl)
2754 VarTemplate->AddSpecialization(Specialization, InsertPos);
2755 }
2756
2757 // C++ [temp.expl.spec]p6:
2758 // If a template, a member template or the member of a class template is
2759 // explicitly specialized then that specialization shall be declared
2760 // before the first use of that specialization that would cause an implicit
2761 // instantiation to take place, in every translation unit in which such a
2762 // use occurs; no diagnostic is required.
2763 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2764 bool Okay = false;
2765 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2766 // Is there any previous explicit specialization declaration?
2767 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2768 Okay = true;
2769 break;
2770 }
2771 }
2772
2773 if (!Okay) {
2774 SourceRange Range(TemplateNameLoc, RAngleLoc);
2775 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2776 << Name << Range;
2777
2778 Diag(PrevDecl->getPointOfInstantiation(),
2779 diag::note_instantiation_required_here)
2780 << (PrevDecl->getTemplateSpecializationKind() !=
2781 TSK_ImplicitInstantiation);
2782 return true;
2783 }
2784 }
2785
2786 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2787 Specialization->setLexicalDeclContext(CurContext);
2788
2789 // Add the specialization into its lexical context, so that it can
2790 // be seen when iterating through the list of declarations in that
2791 // context. However, specializations are not found by name lookup.
2792 CurContext->addDecl(Specialization);
2793
2794 // Note that this is an explicit specialization.
2795 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2796
2797 if (PrevDecl) {
2798 // Check that this isn't a redefinition of this specialization,
2799 // merging with previous declarations.
2800 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2801 ForRedeclaration);
2802 PrevSpec.addDecl(PrevDecl);
2803 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002804 } else if (Specialization->isStaticDataMember() &&
2805 Specialization->isOutOfLine()) {
2806 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002807 }
2808
2809 // Link instantiations of static data members back to the template from
2810 // which they were instantiated.
2811 if (Specialization->isStaticDataMember())
2812 Specialization->setInstantiationOfStaticDataMember(
2813 VarTemplate->getTemplatedDecl(),
2814 Specialization->getSpecializationKind());
2815
2816 return Specialization;
2817}
2818
2819namespace {
2820/// \brief A partial specialization whose template arguments have matched
2821/// a given template-id.
2822struct PartialSpecMatchResult {
2823 VarTemplatePartialSpecializationDecl *Partial;
2824 TemplateArgumentList *Args;
2825};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002826} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00002827
2828DeclResult
2829Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2830 SourceLocation TemplateNameLoc,
2831 const TemplateArgumentListInfo &TemplateArgs) {
2832 assert(Template && "A variable template id without template?");
2833
2834 // Check that the template argument list is well-formed for this template.
2835 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002836 if (CheckTemplateArgumentList(
2837 Template, TemplateNameLoc,
2838 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002839 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002840 return true;
2841
2842 // Find the variable template specialization declaration that
2843 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002844 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002845 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00002846 Converted, InsertPos)) {
2847 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002848 // If we already have a variable template specialization, return it.
2849 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00002850 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002851
2852 // This is the first time we have referenced this variable template
2853 // specialization. Create the canonical declaration and add it to
2854 // the set of specializations, based on the closest partial specialization
2855 // that it represents. That is,
2856 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2857 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002858 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002859 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2860 bool AmbiguousPartialSpec = false;
2861 typedef PartialSpecMatchResult MatchResult;
2862 SmallVector<MatchResult, 4> Matched;
2863 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002864 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2865 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002866
2867 // 1. Attempt to find the closest partial specialization that this
2868 // specializes, if any.
2869 // If any of the template arguments is dependent, then this is probably
2870 // a placeholder for an incomplete declarative context; which must be
2871 // complete by instantiation time. Thus, do not search through the partial
2872 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002873 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2874 // Perhaps better after unification of DeduceTemplateArguments() and
2875 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002876 bool InstantiationDependent = false;
2877 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2878 TemplateArgs, InstantiationDependent)) {
2879
2880 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2881 Template->getPartialSpecializations(PartialSpecs);
2882
2883 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2884 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2885 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2886
2887 if (TemplateDeductionResult Result =
2888 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2889 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002890 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002891 FailedCandidates.addCandidate().set(
2892 DeclAccessPair::make(Template, AS_public), Partial,
2893 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002894 (void)Result;
2895 } else {
2896 Matched.push_back(PartialSpecMatchResult());
2897 Matched.back().Partial = Partial;
2898 Matched.back().Args = Info.take();
2899 }
2900 }
2901
Larisse Voufo39a1e502013-08-06 01:03:05 +00002902 if (Matched.size() >= 1) {
2903 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2904 if (Matched.size() == 1) {
2905 // -- If exactly one matching specialization is found, the
2906 // instantiation is generated from that specialization.
2907 // We don't need to do anything for this.
2908 } else {
2909 // -- If more than one matching specialization is found, the
2910 // partial order rules (14.5.4.2) are used to determine
2911 // whether one of the specializations is more specialized
2912 // than the others. If none of the specializations is more
2913 // specialized than all of the other matching
2914 // specializations, then the use of the variable template is
2915 // ambiguous and the program is ill-formed.
2916 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2917 PEnd = Matched.end();
2918 P != PEnd; ++P) {
2919 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2920 PointOfInstantiation) ==
2921 P->Partial)
2922 Best = P;
2923 }
2924
2925 // Determine if the best partial specialization is more specialized than
2926 // the others.
2927 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2928 PEnd = Matched.end();
2929 P != PEnd; ++P) {
2930 if (P != Best && getMoreSpecializedPartialSpecialization(
2931 P->Partial, Best->Partial,
2932 PointOfInstantiation) != Best->Partial) {
2933 AmbiguousPartialSpec = true;
2934 break;
2935 }
2936 }
2937 }
2938
2939 // Instantiate using the best variable template partial specialization.
2940 InstantiationPattern = Best->Partial;
2941 InstantiationArgs = Best->Args;
2942 } else {
2943 // -- If no match is found, the instantiation is generated
2944 // from the primary template.
2945 // InstantiationPattern = Template->getTemplatedDecl();
2946 }
2947 }
2948
Larisse Voufo39a1e502013-08-06 01:03:05 +00002949 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00002950 // Note that we do not instantiate a definition until we see an odr-use
2951 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002952 // FIXME: LateAttrs et al.?
2953 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2954 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2955 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2956 if (!Decl)
2957 return true;
2958
2959 if (AmbiguousPartialSpec) {
2960 // Partial ordering did not produce a clear winner. Complain.
2961 Decl->setInvalidDecl();
2962 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2963 << Decl;
2964
2965 // Print the matching partial specializations.
2966 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2967 PEnd = Matched.end();
2968 P != PEnd; ++P)
2969 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2970 << getTemplateArgumentBindingsText(
2971 P->Partial->getTemplateParameters(), *P->Args);
2972 return true;
2973 }
2974
2975 if (VarTemplatePartialSpecializationDecl *D =
2976 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2977 Decl->setInstantiationOf(D, InstantiationArgs);
2978
Richard Smith6739a102016-05-05 00:56:12 +00002979 checkSpecializationVisibility(TemplateNameLoc, Decl);
2980
Larisse Voufo39a1e502013-08-06 01:03:05 +00002981 assert(Decl && "No variable template specialization?");
2982 return Decl;
2983}
2984
2985ExprResult
2986Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2987 const DeclarationNameInfo &NameInfo,
2988 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2989 const TemplateArgumentListInfo *TemplateArgs) {
2990
2991 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2992 *TemplateArgs);
2993 if (Decl.isInvalid())
2994 return ExprError();
2995
2996 VarDecl *Var = cast<VarDecl>(Decl.get());
2997 if (!Var->getTemplateSpecializationKind())
2998 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2999 NameInfo.getLoc());
3000
3001 // Build an ordinary singleton decl ref.
3002 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003003 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003004}
3005
John McCalldadc5752010-08-24 06:29:42 +00003006ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003007 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003008 LookupResult &R,
3009 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003010 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003011 // FIXME: Can we do any checking at this point? I guess we could check the
3012 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003013 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003014 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003015 // foo<int> could identify a single function unambiguously
3016 // This approach does NOT work, since f<int>(1);
3017 // gets resolved prior to resorting to overload resolution
3018 // i.e., template<class T> void f(double);
3019 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003020
3021 // These should be filtered out by our callers.
3022 assert(!R.empty() && "empty lookup results when building templateid");
3023 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3024
Larisse Voufo39a1e502013-08-06 01:03:05 +00003025 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003026 bool InstantiationDependent;
3027 if (R.getAsSingle<VarTemplateDecl>() &&
3028 !TemplateSpecializationType::anyDependentTemplateArguments(
3029 *TemplateArgs, InstantiationDependent)) {
3030 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3031 R.getAsSingle<VarTemplateDecl>(),
3032 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003033 }
3034
John McCall58cc69d2010-01-27 01:50:18 +00003035 // We don't want lookup warnings at this point.
3036 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003037
John McCalle66edc12009-11-24 19:00:30 +00003038 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003039 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003040 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003041 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003042 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003043 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003044 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003045
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003046 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003047}
3048
John McCalle66edc12009-11-24 19:00:30 +00003049// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003050ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003051Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003052 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003053 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003054 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003055
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003056 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003057 DeclContext *DC;
3058 if (!(DC = computeDeclContext(SS, false)) ||
3059 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003060 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003061 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003062
Douglas Gregor786123d2010-05-21 23:18:07 +00003063 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003064 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003065 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003066 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003067
John McCalle66edc12009-11-24 19:00:30 +00003068 if (R.isAmbiguous())
3069 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003070
John McCalle66edc12009-11-24 19:00:30 +00003071 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003072 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3073 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003074 return ExprError();
3075 }
3076
3077 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003078 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003079 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003080 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003081 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3082 return ExprError();
3083 }
3084
Abramo Bagnara7945c982012-01-27 09:46:47 +00003085 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003086}
3087
Douglas Gregorb67535d2009-03-31 00:43:58 +00003088/// \brief Form a dependent template name.
3089///
3090/// This action forms a dependent template name given the template
3091/// name and its (presumably dependent) scope specifier. For
3092/// example, given "MetaFun::template apply", the scope specifier \p
3093/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3094/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003096 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003097 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003098 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003099 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003100 bool EnteringContext,
3101 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003102 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3103 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003104 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003105 diag::warn_cxx98_compat_template_outside_of_template :
3106 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003107 << FixItHint::CreateRemoval(TemplateKWLoc);
3108
Craig Topperc3ec1492014-05-26 06:22:03 +00003109 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003110 if (SS.isSet())
3111 LookupCtx = computeDeclContext(SS, EnteringContext);
3112 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003113 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003114 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003115 // C++0x [temp.names]p5:
3116 // If a name prefixed by the keyword template is not the name of
3117 // a template, the program is ill-formed. [Note: the keyword
3118 // template may not be applied to non-template members of class
3119 // templates. -end note ] [ Note: as is the case with the
3120 // typename prefix, the template prefix is allowed in cases
3121 // where it is not strictly necessary; i.e., when the
3122 // nested-name-specifier or the expression on the left of the ->
3123 // or . is not dependent on a template-parameter, or the use
3124 // does not appear in the scope of a template. -end note]
3125 //
3126 // Note: C++03 was more strict here, because it banned the use of
3127 // the "template" keyword prior to a template-name that was not a
3128 // dependent name. C++ DR468 relaxed this requirement (the
3129 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003130 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003131 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003132 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003133 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003134 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003135 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3136 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003137 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3138 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003139 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003140 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003141 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003142 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003143 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003144 << Name.getSourceRange()
3145 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003146 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003147 } else {
3148 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003149 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003150 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003151 }
3152
Aaron Ballman4a979672014-01-03 13:56:08 +00003153 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003154
Douglas Gregor3cf81312009-11-03 23:16:33 +00003155 switch (Name.getKind()) {
3156 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003157 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003158 Name.Identifier));
3159 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003160
Douglas Gregor71395fa2009-11-04 00:56:37 +00003161 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003162 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003163 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003164 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003165
3166 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003167 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003168
Douglas Gregor3cf81312009-11-03 23:16:33 +00003169 default:
3170 break;
3171 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003172
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003173 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003174 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003175 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003176 << Name.getSourceRange()
3177 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003178 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003179}
3180
Mike Stump11289f42009-09-09 15:08:12 +00003181bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003182 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003183 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003184 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003185 QualType ArgType;
3186 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003187
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003188 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003189 switch(Arg.getKind()) {
3190 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003191 // C++ [temp.arg.type]p1:
3192 // A template-argument for a template-parameter which is a
3193 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003194 ArgType = Arg.getAsType();
3195 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003196 break;
3197 case TemplateArgument::Template: {
3198 // We have a template type parameter but the template argument
3199 // is a template without any arguments.
3200 SourceRange SR = AL.getSourceRange();
3201 TemplateName Name = Arg.getAsTemplate();
3202 Diag(SR.getBegin(), diag::err_template_missing_args)
3203 << Name << SR;
3204 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3205 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003206
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003207 return true;
3208 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003209 case TemplateArgument::Expression: {
3210 // We have a template type parameter but the template argument is an
3211 // expression; see if maybe it is missing the "typename" keyword.
3212 CXXScopeSpec SS;
3213 DeclarationNameInfo NameInfo;
3214
3215 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3216 SS.Adopt(ArgExpr->getQualifierLoc());
3217 NameInfo = ArgExpr->getNameInfo();
3218 } else if (DependentScopeDeclRefExpr *ArgExpr =
3219 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3220 SS.Adopt(ArgExpr->getQualifierLoc());
3221 NameInfo = ArgExpr->getNameInfo();
3222 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3223 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003224 if (ArgExpr->isImplicitAccess()) {
3225 SS.Adopt(ArgExpr->getQualifierLoc());
3226 NameInfo = ArgExpr->getMemberNameInfo();
3227 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003228 }
3229
Reid Kleckner377c1592014-06-10 23:29:48 +00003230 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003231 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3232 LookupParsedName(Result, CurScope, &SS);
3233
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003234 if (Result.getAsSingle<TypeDecl>() ||
3235 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003236 LookupResult::NotFoundInCurrentInstantiation) {
3237 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003238 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003239 Diag(Loc, getLangOpts().MSVCCompat
3240 ? diag::ext_ms_template_type_arg_missing_typename
3241 : diag::err_template_arg_must_be_type_suggest)
3242 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003243 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003244
3245 // Recover by synthesizing a type using the location information that we
3246 // already have.
3247 ArgType =
3248 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3249 TypeLocBuilder TLB;
3250 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3251 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3252 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3253 TL.setNameLoc(NameInfo.getLoc());
3254 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3255
3256 // Overwrite our input TemplateArgumentLoc so that we can recover
3257 // properly.
3258 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3259 TemplateArgumentLocInfo(TSI));
3260
3261 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003262 }
3263 }
3264 // fallthrough
3265 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003266 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003267 // We have a template type parameter but the template argument
3268 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003269 SourceRange SR = AL.getSourceRange();
3270 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003271 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003272
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003273 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003274 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003275 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003276
Reid Kleckner377c1592014-06-10 23:29:48 +00003277 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003278 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003279
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003280 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003281 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003282
3283 // Objective-C ARC:
3284 // If an explicitly-specified template argument type is a lifetime type
3285 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003286 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003287 ArgType->isObjCLifetimeType() &&
3288 !ArgType.getObjCLifetime()) {
3289 Qualifiers Qs;
3290 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3291 ArgType = Context.getQualifiedType(ArgType, Qs);
3292 }
3293
3294 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003295 return false;
3296}
3297
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003298/// \brief Substitute template arguments into the default template argument for
3299/// the given template type parameter.
3300///
3301/// \param SemaRef the semantic analysis object for which we are performing
3302/// the substitution.
3303///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003304/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003305/// for.
3306///
3307/// \param TemplateLoc the location of the template name that started the
3308/// template-id we are checking.
3309///
3310/// \param RAngleLoc the location of the right angle bracket ('>') that
3311/// terminates the template-id.
3312///
3313/// \param Param the template template parameter whose default we are
3314/// substituting into.
3315///
3316/// \param Converted the list of template arguments provided for template
3317/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003318/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003319static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003320SubstDefaultTemplateArgument(Sema &SemaRef,
3321 TemplateDecl *Template,
3322 SourceLocation TemplateLoc,
3323 SourceLocation RAngleLoc,
3324 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003325 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003326 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003327
3328 // If the argument type is dependent, instantiate it now based
3329 // on the previously-computed template arguments.
3330 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003331 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003332 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003333 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003334 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003335 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336
David Majnemer8b622692016-07-03 21:17:51 +00003337 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003338
3339 // Only substitute for the innermost template argument list.
3340 MultiLevelTemplateArgumentList TemplateArgLists;
3341 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3342 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3343 TemplateArgLists.addOuterTemplateArguments(None);
3344
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003345 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003346 ArgType =
3347 SemaRef.SubstType(ArgType, TemplateArgLists,
3348 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003349 }
3350
3351 return ArgType;
3352}
3353
3354/// \brief Substitute template arguments into the default template argument for
3355/// the given non-type template parameter.
3356///
3357/// \param SemaRef the semantic analysis object for which we are performing
3358/// the substitution.
3359///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003360/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003361/// for.
3362///
3363/// \param TemplateLoc the location of the template name that started the
3364/// template-id we are checking.
3365///
3366/// \param RAngleLoc the location of the right angle bracket ('>') that
3367/// terminates the template-id.
3368///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003369/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003370/// substituting into.
3371///
3372/// \param Converted the list of template arguments provided for template
3373/// parameters that precede \p Param in the template parameter list.
3374///
3375/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003376static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003377SubstDefaultTemplateArgument(Sema &SemaRef,
3378 TemplateDecl *Template,
3379 SourceLocation TemplateLoc,
3380 SourceLocation RAngleLoc,
3381 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003382 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003383 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003384 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003385 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003386 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003387 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003388
David Majnemer8b622692016-07-03 21:17:51 +00003389 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003390
3391 // Only substitute for the innermost template argument list.
3392 MultiLevelTemplateArgumentList TemplateArgLists;
3393 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3394 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3395 TemplateArgLists.addOuterTemplateArguments(None);
3396
Faisal Vali48401eb2015-11-19 19:20:17 +00003397 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3398 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003399 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003400}
3401
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003402/// \brief Substitute template arguments into the default template argument for
3403/// the given template template parameter.
3404///
3405/// \param SemaRef the semantic analysis object for which we are performing
3406/// the substitution.
3407///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003409/// for.
3410///
3411/// \param TemplateLoc the location of the template name that started the
3412/// template-id we are checking.
3413///
3414/// \param RAngleLoc the location of the right angle bracket ('>') that
3415/// terminates the template-id.
3416///
3417/// \param Param the template template parameter whose default we are
3418/// substituting into.
3419///
3420/// \param Converted the list of template arguments provided for template
3421/// parameters that precede \p Param in the template parameter list.
3422///
Douglas Gregordf846d12011-03-02 18:46:51 +00003423/// \param QualifierLoc Will be set to the nested-name-specifier (with
3424/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003425///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003426/// \returns the substituted template argument, or NULL if an error occurred.
3427static TemplateName
3428SubstDefaultTemplateArgument(Sema &SemaRef,
3429 TemplateDecl *Template,
3430 SourceLocation TemplateLoc,
3431 SourceLocation RAngleLoc,
3432 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003433 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003434 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00003435 Sema::InstantiatingTemplate Inst(
3436 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
3437 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003438 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003439 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003440
David Majnemer8b622692016-07-03 21:17:51 +00003441 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003442
3443 // Only substitute for the innermost template argument list.
3444 MultiLevelTemplateArgumentList TemplateArgLists;
3445 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3446 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3447 TemplateArgLists.addOuterTemplateArguments(None);
3448
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003449 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003450 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003451 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003452 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003453 QualifierLoc =
3454 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003455 if (!QualifierLoc)
3456 return TemplateName();
3457 }
David Majnemer89189202013-08-28 23:48:32 +00003458
3459 return SemaRef.SubstTemplateName(
3460 QualifierLoc,
3461 Param->getDefaultArgument().getArgument().getAsTemplate(),
3462 Param->getDefaultArgument().getTemplateNameLoc(),
3463 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003464}
3465
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003466/// \brief If the given template parameter has a default template
3467/// argument, substitute into that default template argument and
3468/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003469TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003470Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3471 SourceLocation TemplateLoc,
3472 SourceLocation RAngleLoc,
3473 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003474 SmallVectorImpl<TemplateArgument>
3475 &Converted,
3476 bool &HasDefaultArg) {
3477 HasDefaultArg = false;
3478
3479 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003480 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003481 return TemplateArgumentLoc();
3482
Richard Smithc87b9382013-07-04 01:01:24 +00003483 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003484 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003485 TemplateLoc,
3486 RAngleLoc,
3487 TypeParm,
3488 Converted);
3489 if (DI)
3490 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3491
3492 return TemplateArgumentLoc();
3493 }
3494
3495 if (NonTypeTemplateParmDecl *NonTypeParm
3496 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003497 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003498 return TemplateArgumentLoc();
3499
Richard Smithc87b9382013-07-04 01:01:24 +00003500 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003501 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003502 TemplateLoc,
3503 RAngleLoc,
3504 NonTypeParm,
3505 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003506 if (Arg.isInvalid())
3507 return TemplateArgumentLoc();
3508
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003509 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003510 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3511 }
3512
3513 TemplateTemplateParmDecl *TempTempParm
3514 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003515 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003516 return TemplateArgumentLoc();
3517
Richard Smithc87b9382013-07-04 01:01:24 +00003518 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003519 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003520 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003522 RAngleLoc,
3523 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003524 Converted,
3525 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003526 if (TName.isNull())
3527 return TemplateArgumentLoc();
3528
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003530 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003531 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3532}
3533
Douglas Gregorda0fb532009-11-11 19:31:23 +00003534/// \brief Check that the given template argument corresponds to the given
3535/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003536///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003537/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003538/// checked.
3539///
Richard Trieu15b66532015-01-24 02:48:32 +00003540/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003541///
3542/// \param Template The template in which the template argument resides.
3543///
3544/// \param TemplateLoc The location of the template name for the template
3545/// whose argument list we're matching.
3546///
3547/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3548/// the template argument list.
3549///
3550/// \param ArgumentPackIndex The index into the argument pack where this
3551/// argument will be placed. Only valid if the parameter is a parameter pack.
3552///
3553/// \param Converted The checked, converted argument will be added to the
3554/// end of this small vector.
3555///
3556/// \param CTAK Describes how we arrived at this particular template argument:
3557/// explicitly written, deduced, etc.
3558///
3559/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003560bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003561 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003562 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003563 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003564 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003565 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003566 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003567 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003568 // Check template type parameters.
3569 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003570 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571
Douglas Gregoreebed722009-11-11 19:41:09 +00003572 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003573 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003574 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003575 // with the template arguments we've seen thus far. But if the
3576 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003577 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003578 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3579 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003580
Peter Collingbourne01687632010-12-10 17:08:53 +00003581 if (NTTPType->isDependentType() &&
3582 !isa<TemplateTemplateParmDecl>(Template) &&
3583 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003584 // Do substitution on the type of the non-type template parameter.
3585 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003586 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003587 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003588 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003589 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003590
3591 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003592 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003593 NTTPType = SubstType(NTTPType,
3594 MultiLevelTemplateArgumentList(TemplateArgs),
3595 NTTP->getLocation(),
3596 NTTP->getDeclName());
3597 // If that worked, check the non-type template parameter type
3598 // for validity.
3599 if (!NTTPType.isNull())
3600 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3601 NTTP->getLocation());
3602 if (NTTPType.isNull())
3603 return true;
3604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003605
Douglas Gregorda0fb532009-11-11 19:31:23 +00003606 switch (Arg.getArgument().getKind()) {
3607 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003608 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003609
Douglas Gregorda0fb532009-11-11 19:31:23 +00003610 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003611 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003612 ExprResult Res =
3613 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3614 Result, CTAK);
3615 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003616 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003617
Richard Trieu15b66532015-01-24 02:48:32 +00003618 // If the resulting expression is new, then use it in place of the
3619 // old expression in the template argument.
3620 if (Res.get() != Arg.getArgument().getAsExpr()) {
3621 TemplateArgument TA(Res.get());
3622 Arg = TemplateArgumentLoc(TA, Res.get());
3623 }
3624
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003625 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003626 break;
3627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
Douglas Gregorda0fb532009-11-11 19:31:23 +00003629 case TemplateArgument::Declaration:
3630 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003631 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003632 // We've already checked this template argument, so just copy
3633 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003634 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003635 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003636
Douglas Gregorda0fb532009-11-11 19:31:23 +00003637 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003638 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003639 // We were given a template template argument. It may not be ill-formed;
3640 // see below.
3641 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003642 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3643 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003644 // We have a template argument such as \c T::template X, which we
3645 // parsed as a template template argument. However, since we now
3646 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003647 // template name into an expression.
3648
3649 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3650 Arg.getTemplateNameLoc());
3651
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003652 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003653 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003654 // FIXME: the template-template arg was a DependentTemplateName,
3655 // so it was provided with a template keyword. However, its source
3656 // location is not stored in the template argument structure.
3657 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003658 ExprResult E = DependentScopeDeclRefExpr::Create(
3659 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3660 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003661
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003662 // If we parsed the template argument as a pack expansion, create a
3663 // pack expansion expression.
3664 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003665 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003666 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003667 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003669
Douglas Gregorda0fb532009-11-11 19:31:23 +00003670 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003671 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003672 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003673 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003675 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003676 break;
3677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678
Douglas Gregorda0fb532009-11-11 19:31:23 +00003679 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003680 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003681 // therefore cannot be a non-type template argument.
3682 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3683 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003684
Douglas Gregorda0fb532009-11-11 19:31:23 +00003685 Diag(Param->getLocation(), diag::note_template_param_here);
3686 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003687
Douglas Gregorda0fb532009-11-11 19:31:23 +00003688 case TemplateArgument::Type: {
3689 // We have a non-type template parameter but the template
3690 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003691
Douglas Gregorda0fb532009-11-11 19:31:23 +00003692 // C++ [temp.arg]p2:
3693 // In a template-argument, an ambiguity between a type-id and
3694 // an expression is resolved to a type-id, regardless of the
3695 // form of the corresponding template-parameter.
3696 //
3697 // We warn specifically about this case, since it can be rather
3698 // confusing for users.
3699 QualType T = Arg.getArgument().getAsType();
3700 SourceRange SR = Arg.getSourceRange();
3701 if (T->isFunctionType())
3702 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3703 else
3704 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3705 Diag(Param->getLocation(), diag::note_template_param_here);
3706 return true;
3707 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003708
Douglas Gregorda0fb532009-11-11 19:31:23 +00003709 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003710 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003712
Douglas Gregorda0fb532009-11-11 19:31:23 +00003713 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003714 }
3715
3716
Douglas Gregorda0fb532009-11-11 19:31:23 +00003717 // Check template template parameters.
3718 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003719
Douglas Gregorda0fb532009-11-11 19:31:23 +00003720 // Substitute into the template parameter list of the template
3721 // template parameter, since previously-supplied template arguments
3722 // may appear within the template template parameter.
3723 {
3724 // Set up a template instantiation context.
3725 LocalInstantiationScope Scope(*this);
3726 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003727 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003728 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003729 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003730 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003731
David Majnemer8b622692016-07-03 21:17:51 +00003732 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003733 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003734 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003735 MultiLevelTemplateArgumentList(TemplateArgs)));
3736 if (!TempParm)
3737 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003738 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
Douglas Gregorda0fb532009-11-11 19:31:23 +00003740 switch (Arg.getArgument().getKind()) {
3741 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003742 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003743
Douglas Gregorda0fb532009-11-11 19:31:23 +00003744 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003745 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003746 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003747 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003748
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003749 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003750 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003751
Douglas Gregorda0fb532009-11-11 19:31:23 +00003752 case TemplateArgument::Expression:
3753 case TemplateArgument::Type:
3754 // We have a template template parameter but the template
3755 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003756 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003757 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003758 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003759
Douglas Gregorda0fb532009-11-11 19:31:23 +00003760 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003761 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003762 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003763 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003764 case TemplateArgument::NullPtr:
3765 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003766
Douglas Gregorda0fb532009-11-11 19:31:23 +00003767 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003768 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770
Douglas Gregorda0fb532009-11-11 19:31:23 +00003771 return false;
3772}
3773
Douglas Gregor8e072612012-02-03 07:34:46 +00003774/// \brief Diagnose an arity mismatch in the
3775static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3776 SourceLocation TemplateLoc,
3777 TemplateArgumentListInfo &TemplateArgs) {
3778 TemplateParameterList *Params = Template->getTemplateParameters();
3779 unsigned NumParams = Params->size();
3780 unsigned NumArgs = TemplateArgs.size();
3781
3782 SourceRange Range;
3783 if (NumArgs > NumParams)
3784 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3785 TemplateArgs.getRAngleLoc());
3786 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3787 << (NumArgs > NumParams)
3788 << (isa<ClassTemplateDecl>(Template)? 0 :
3789 isa<FunctionTemplateDecl>(Template)? 1 :
3790 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3791 << Template << Range;
3792 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3793 << Params->getSourceRange();
3794 return true;
3795}
3796
Richard Smith1fde8ec2012-09-07 02:06:42 +00003797/// \brief Check whether the template parameter is a pack expansion, and if so,
3798/// determine the number of parameters produced by that expansion. For instance:
3799///
3800/// \code
3801/// template<typename ...Ts> struct A {
3802/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3803/// };
3804/// \endcode
3805///
3806/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3807/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003808static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003809 if (NonTypeTemplateParmDecl *NTTP
3810 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3811 if (NTTP->isExpandedParameterPack())
3812 return NTTP->getNumExpansionTypes();
3813 }
3814
3815 if (TemplateTemplateParmDecl *TTP
3816 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3817 if (TTP->isExpandedParameterPack())
3818 return TTP->getNumExpansionTemplateParameters();
3819 }
3820
David Blaikie7a30dc52013-02-21 01:47:18 +00003821 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003822}
3823
Richard Smith35c1df52015-06-17 20:16:32 +00003824/// Diagnose a missing template argument.
3825template<typename TemplateParmDecl>
3826static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3827 TemplateDecl *TD,
3828 const TemplateParmDecl *D,
3829 TemplateArgumentListInfo &Args) {
3830 // Dig out the most recent declaration of the template parameter; there may be
3831 // declarations of the template that are more recent than TD.
3832 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3833 ->getTemplateParameters()
3834 ->getParam(D->getIndex()));
3835
3836 // If there's a default argument that's not visible, diagnose that we're
3837 // missing a module import.
3838 llvm::SmallVector<Module*, 8> Modules;
3839 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3840 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3841 D->getDefaultArgumentLoc(), Modules,
3842 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00003843 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00003844 return true;
3845 }
3846
3847 // FIXME: If there's a more recent default argument that *is* visible,
3848 // diagnose that it was declared too late.
3849
3850 return diagnoseArityMismatch(S, TD, Loc, Args);
3851}
3852
Douglas Gregord32e0282009-02-09 23:23:08 +00003853/// \brief Check that the given template argument list is well-formed
3854/// for specializing the given template.
3855bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3856 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003857 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003858 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003859 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003860 // Make a copy of the template arguments for processing. Only make the
3861 // changes at the end when successful in matching the arguments to the
3862 // template.
3863 TemplateArgumentListInfo NewArgs = TemplateArgs;
3864
Douglas Gregord32e0282009-02-09 23:23:08 +00003865 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003866
Richard Trieu15b66532015-01-24 02:48:32 +00003867 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003868
Mike Stump11289f42009-09-09 15:08:12 +00003869 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003870 // [...] The type and form of each template-argument specified in
3871 // a template-id shall match the type and form specified for the
3872 // corresponding parameter declared by the template in its
3873 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003874 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003875 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003876 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003877 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003878 for (TemplateParameterList::iterator Param = Params->begin(),
3879 ParamEnd = Params->end();
3880 Param != ParamEnd; /* increment in loop */) {
3881 // If we have an expanded parameter pack, make sure we don't have too
3882 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003883 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003884 if (*Expansions == ArgumentPack.size()) {
3885 // We're done with this parameter pack. Pack up its arguments and add
3886 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003887 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00003888 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003889 ArgumentPack.clear();
3890
Richard Smith1fde8ec2012-09-07 02:06:42 +00003891 // This argument is assigned to the next parameter.
3892 ++Param;
3893 continue;
3894 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3895 // Not enough arguments for this parameter pack.
3896 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3897 << false
3898 << (isa<ClassTemplateDecl>(Template)? 0 :
3899 isa<FunctionTemplateDecl>(Template)? 1 :
3900 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3901 << Template;
3902 Diag(Template->getLocation(), diag::note_template_decl_here)
3903 << Params->getSourceRange();
3904 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003905 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003906 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003907
Richard Smith1fde8ec2012-09-07 02:06:42 +00003908 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003909 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003910 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003911 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003912 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003913 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003914
Richard Smith96d71c32014-11-12 23:38:38 +00003915 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003916 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003917 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3918 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003919 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003920 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003921 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003922 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003923 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003924 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003925 Diag((*Param)->getLocation(), diag::note_template_param_here);
3926 return true;
3927 }
3928
Richard Smith1fde8ec2012-09-07 02:06:42 +00003929 // We're now done with this argument.
3930 ++ArgIdx;
3931
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003932 if ((*Param)->isTemplateParameterPack()) {
3933 // The template parameter was a template parameter pack, so take the
3934 // deduced argument and place it on the argument pack. Note that we
3935 // stay on the same template parameter so that we can deduce more
3936 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003937 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003938 } else {
3939 // Move to the next template parameter.
3940 ++Param;
3941 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003942
Richard Smith96d71c32014-11-12 23:38:38 +00003943 // If we just saw a pack expansion into a non-pack, then directly convert
3944 // the remaining arguments, because we don't know what parameters they'll
3945 // match up with.
3946 if (PackExpansionIntoNonPack) {
3947 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003948 // If we were part way through filling in an expanded parameter pack,
3949 // fall back to just producing individual arguments.
3950 Converted.insert(Converted.end(),
3951 ArgumentPack.begin(), ArgumentPack.end());
3952 ArgumentPack.clear();
3953 }
3954
3955 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003956 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003957 ++ArgIdx;
3958 }
3959
Richard Smith1fde8ec2012-09-07 02:06:42 +00003960 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003961 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003962
Douglas Gregor84d49a22009-11-11 21:54:23 +00003963 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003965
Douglas Gregor2f157c92011-06-03 02:59:40 +00003966 // If we're checking a partial template argument list, we're done.
3967 if (PartialTemplateArgs) {
3968 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00003969 Converted.push_back(
3970 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3971
Richard Smith1fde8ec2012-09-07 02:06:42 +00003972 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003973 }
3974
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003975 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003976 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003977 if ((*Param)->isTemplateParameterPack()) {
3978 assert(!getExpandedPackSize(*Param) &&
3979 "Should have dealt with this already");
3980
3981 // A non-expanded parameter pack before the end of the parameter list
3982 // only occurs for an ill-formed template parameter list, unless we've
3983 // got a partial argument list for a function template, so just bail out.
3984 if (Param + 1 != ParamEnd)
3985 return true;
3986
Benjamin Kramercce63472015-08-05 09:40:22 +00003987 Converted.push_back(
3988 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003989 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003990
3991 ++Param;
3992 continue;
3993 }
3994
Douglas Gregor8e072612012-02-03 07:34:46 +00003995 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003996 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003997
Douglas Gregor84d49a22009-11-11 21:54:23 +00003998 // Retrieve the default template argument from the template
3999 // parameter. For each kind of template parameter, we substitute the
4000 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004001 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004002 // the default argument.
4003 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004004 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004005 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4006 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004007
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004008 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004009 Template,
4010 TemplateLoc,
4011 RAngleLoc,
4012 TTP,
4013 Converted);
4014 if (!ArgType)
4015 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004016
Douglas Gregor84d49a22009-11-11 21:54:23 +00004017 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4018 ArgType);
4019 } else if (NonTypeTemplateParmDecl *NTTP
4020 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004021 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004022 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4023 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004024
John McCalldadc5752010-08-24 06:29:42 +00004025 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004026 TemplateLoc,
4027 RAngleLoc,
4028 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004029 Converted);
4030 if (E.isInvalid())
4031 return true;
4032
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004033 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004034 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4035 } else {
4036 TemplateTemplateParmDecl *TempParm
4037 = cast<TemplateTemplateParmDecl>(*Param);
4038
Richard Smith95d83952015-06-10 20:36:34 +00004039 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004040 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4041 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004042
Douglas Gregordf846d12011-03-02 18:46:51 +00004043 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004044 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004045 TemplateLoc,
4046 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004047 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004048 Converted,
4049 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004050 if (Name.isNull())
4051 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004052
Douglas Gregor9d802122011-03-02 17:09:35 +00004053 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4054 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004056
Douglas Gregor84d49a22009-11-11 21:54:23 +00004057 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00004058 // the default template argument. We're not actually instantiating a
4059 // template here, we just create this object to put a note into the
4060 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004061 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4062 SourceRange(TemplateLoc, RAngleLoc));
4063 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004064 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065
Douglas Gregor84d49a22009-11-11 21:54:23 +00004066 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004067 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004068 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004069 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004070
Richard Trieu15b66532015-01-24 02:48:32 +00004071 // Core issue 150 (assumed resolution): if this is a template template
4072 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004073 // template definition.
4074 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004075 NewArgs.addArgument(Arg);
4076
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004077 // Move to the next template parameter and argument.
4078 ++Param;
4079 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004081
Richard Smith07f79912014-06-06 16:00:50 +00004082 // If we're performing a partial argument substitution, allow any trailing
4083 // pack expansions; they might be empty. This can happen even if
4084 // PartialTemplateArgs is false (the list of arguments is complete but
4085 // still dependent).
4086 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4087 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004088 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4089 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004090 }
4091
Douglas Gregor8e072612012-02-03 07:34:46 +00004092 // If we have any leftover arguments, then there were too many arguments.
4093 // Complain and fail.
4094 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004095 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4096
4097 // No problems found with the new argument list, propagate changes back
4098 // to caller.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00004099 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004100
Richard Smith1fde8ec2012-09-07 02:06:42 +00004101 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004102}
4103
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004104namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004105 class UnnamedLocalNoLinkageFinder
4106 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004107 {
4108 Sema &S;
4109 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004110
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004111 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004112
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004113 public:
4114 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4115
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004116 bool Visit(QualType T) {
4117 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004120#define TYPE(Class, Parent) \
4121 bool Visit##Class##Type(const Class##Type *);
4122#define ABSTRACT_TYPE(Class, Parent) \
4123 bool Visit##Class##Type(const Class##Type *) { return false; }
4124#define NON_CANONICAL_TYPE(Class, Parent) \
4125 bool Visit##Class##Type(const Class##Type *) { return false; }
4126#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004127
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004128 bool VisitTagDecl(const TagDecl *Tag);
4129 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4130 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004131} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004132
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004133bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004134 return false;
4135}
4136
4137bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4138 return Visit(T->getElementType());
4139}
4140
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004141bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004142 return Visit(T->getPointeeType());
4143}
4144
4145bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004146 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004147 return Visit(T->getPointeeType());
4148}
4149
4150bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004151 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004152 return Visit(T->getPointeeType());
4153}
4154
4155bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004156 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004157 return Visit(T->getPointeeType());
4158}
4159
4160bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004161 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004162 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4163}
4164
4165bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004166 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004167 return Visit(T->getElementType());
4168}
4169
4170bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004171 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004172 return Visit(T->getElementType());
4173}
4174
4175bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004176 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004177 return Visit(T->getElementType());
4178}
4179
4180bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004181 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004182 return Visit(T->getElementType());
4183}
4184
4185bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004186 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004187 return Visit(T->getElementType());
4188}
4189
4190bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4191 return Visit(T->getElementType());
4192}
4193
4194bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4195 return Visit(T->getElementType());
4196}
4197
4198bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4199 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004200 for (const auto &A : T->param_types()) {
4201 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004202 return true;
4203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004204
Alp Toker314cc812014-01-25 16:55:45 +00004205 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004206}
4207
4208bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4209 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004210 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004211}
4212
4213bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4214 const UnresolvedUsingType*) {
4215 return false;
4216}
4217
4218bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4219 return false;
4220}
4221
4222bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4223 return Visit(T->getUnderlyingType());
4224}
4225
4226bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4227 return false;
4228}
4229
Alexis Hunte852b102011-05-24 22:41:36 +00004230bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4231 const UnaryTransformType*) {
4232 return false;
4233}
4234
Richard Smith30482bc2011-02-20 03:19:35 +00004235bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4236 return Visit(T->getDeducedType());
4237}
4238
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004239bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4240 return VisitTagDecl(T->getDecl());
4241}
4242
4243bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4244 return VisitTagDecl(T->getDecl());
4245}
4246
4247bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4248 const TemplateTypeParmType*) {
4249 return false;
4250}
4251
Douglas Gregorada4b792011-01-14 02:55:32 +00004252bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4253 const SubstTemplateTypeParmPackType *) {
4254 return false;
4255}
4256
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004257bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4258 const TemplateSpecializationType*) {
4259 return false;
4260}
4261
4262bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4263 const InjectedClassNameType* T) {
4264 return VisitTagDecl(T->getDecl());
4265}
4266
4267bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4268 const DependentNameType* T) {
4269 return VisitNestedNameSpecifier(T->getQualifier());
4270}
4271
4272bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4273 const DependentTemplateSpecializationType* T) {
4274 return VisitNestedNameSpecifier(T->getQualifier());
4275}
4276
Douglas Gregord2fa7662010-12-20 02:24:11 +00004277bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4278 const PackExpansionType* T) {
4279 return Visit(T->getPattern());
4280}
4281
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004282bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4283 return false;
4284}
4285
4286bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4287 const ObjCInterfaceType *) {
4288 return false;
4289}
4290
4291bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4292 const ObjCObjectPointerType *) {
4293 return false;
4294}
4295
Eli Friedman0dfb8892011-10-06 23:00:33 +00004296bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4297 return Visit(T->getValueType());
4298}
4299
Xiuli Pan9c14e282016-01-09 12:53:17 +00004300bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4301 return false;
4302}
4303
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004304bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4305 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004306 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004307 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004308 diag::warn_cxx98_compat_template_arg_local_type :
4309 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004310 << S.Context.getTypeDeclType(Tag) << SR;
4311 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312 }
4313
John McCall5ea95772013-03-09 00:54:27 +00004314 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004315 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004316 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004317 diag::warn_cxx98_compat_template_arg_unnamed_type :
4318 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004319 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4320 return true;
4321 }
4322
4323 return false;
4324}
4325
4326bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4327 NestedNameSpecifier *NNS) {
4328 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4329 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004330
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004331 switch (NNS->getKind()) {
4332 case NestedNameSpecifier::Identifier:
4333 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004334 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004335 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004336 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004337 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004338
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004339 case NestedNameSpecifier::TypeSpec:
4340 case NestedNameSpecifier::TypeSpecWithTemplate:
4341 return Visit(QualType(NNS->getAsType(), 0));
4342 }
David Blaikie8a40f702012-01-17 06:56:22 +00004343 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004344}
4345
Douglas Gregord32e0282009-02-09 23:23:08 +00004346/// \brief Check a template argument against its corresponding
4347/// template type parameter.
4348///
4349/// This routine implements the semantics of C++ [temp.arg.type]. It
4350/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004351bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004352 TypeSourceInfo *ArgInfo) {
4353 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004354 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004355 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004356
4357 if (Arg->isVariablyModifiedType()) {
4358 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004359 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004360 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004361 }
4362
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004363 // C++03 [temp.arg.type]p2:
4364 // A local type, a type with no linkage, an unnamed type or a type
4365 // compounded from any of these types shall not be used as a
4366 // template-argument for a template type-parameter.
4367 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004368 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004369 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004370 bool NeedsCheck;
4371 if (LangOpts.CPlusPlus11)
4372 NeedsCheck =
4373 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4374 SR.getBegin()) ||
4375 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4376 SR.getBegin());
4377 else
4378 NeedsCheck = Arg->hasUnnamedOrLocalType();
4379
4380 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004381 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4382 (void)Finder.Visit(Context.getCanonicalType(Arg));
4383 }
4384
Douglas Gregord32e0282009-02-09 23:23:08 +00004385 return false;
4386}
4387
Douglas Gregor20fdef32012-04-10 17:08:25 +00004388enum NullPointerValueKind {
4389 NPV_NotNullPointer,
4390 NPV_NullPointer,
4391 NPV_Error
4392};
4393
4394/// \brief Determine whether the given template argument is a null pointer
4395/// value of the appropriate type.
4396static NullPointerValueKind
4397isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4398 QualType ParamType, Expr *Arg) {
4399 if (Arg->isValueDependent() || Arg->isTypeDependent())
4400 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004401
Richard Smithdb0ac552015-12-18 22:40:25 +00004402 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004403 llvm_unreachable(
4404 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004405
David Majnemer5c734ad2014-08-14 00:49:23 +00004406 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004407 return NPV_NotNullPointer;
4408
4409 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004410 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4411 if (ArgRV.isInvalid())
4412 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004413 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004414
Douglas Gregor20fdef32012-04-10 17:08:25 +00004415 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004416 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004417 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004418 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004419 EvalResult.HasSideEffects) {
4420 SourceLocation DiagLoc = Arg->getExprLoc();
4421
4422 // If our only note is the usual "invalid subexpression" note, just point
4423 // the caret at its location rather than producing an essentially
4424 // redundant note.
4425 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4426 diag::note_invalid_subexpr_in_const_expr) {
4427 DiagLoc = Notes[0].first;
4428 Notes.clear();
4429 }
4430
4431 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4432 << Arg->getType() << Arg->getSourceRange();
4433 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4434 S.Diag(Notes[I].first, Notes[I].second);
4435
4436 S.Diag(Param->getLocation(), diag::note_template_param_here);
4437 return NPV_Error;
4438 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004439
4440 // C++11 [temp.arg.nontype]p1:
4441 // - an address constant expression of type std::nullptr_t
4442 if (Arg->getType()->isNullPtrType())
4443 return NPV_NullPointer;
4444
4445 // - a constant expression that evaluates to a null pointer value (4.10); or
4446 // - a constant expression that evaluates to a null member pointer value
4447 // (4.11); or
4448 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4449 (EvalResult.Val.isMemberPointer() &&
4450 !EvalResult.Val.getMemberPointerDecl())) {
4451 // If our expression has an appropriate type, we've succeeded.
4452 bool ObjCLifetimeConversion;
4453 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4454 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4455 ObjCLifetimeConversion))
4456 return NPV_NullPointer;
4457
4458 // The types didn't match, but we know we got a null pointer; complain,
4459 // then recover as if the types were correct.
4460 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4461 << Arg->getType() << ParamType << Arg->getSourceRange();
4462 S.Diag(Param->getLocation(), diag::note_template_param_here);
4463 return NPV_NullPointer;
4464 }
4465
4466 // If we don't have a null pointer value, but we do have a NULL pointer
4467 // constant, suggest a cast to the appropriate type.
4468 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4469 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4470 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004471 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4472 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4473 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004474 S.Diag(Param->getLocation(), diag::note_template_param_here);
4475 return NPV_NullPointer;
4476 }
4477
4478 // FIXME: If we ever want to support general, address-constant expressions
4479 // as non-type template arguments, we should return the ExprResult here to
4480 // be interpreted by the caller.
4481 return NPV_NotNullPointer;
4482}
4483
David Majnemer61c39a12013-08-23 05:39:39 +00004484/// \brief Checks whether the given template argument is compatible with its
4485/// template parameter.
4486static bool CheckTemplateArgumentIsCompatibleWithParameter(
4487 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4488 Expr *Arg, QualType ArgType) {
4489 bool ObjCLifetimeConversion;
4490 if (ParamType->isPointerType() &&
4491 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4492 S.IsQualificationConversion(ArgType, ParamType, false,
4493 ObjCLifetimeConversion)) {
4494 // For pointer-to-object types, qualification conversions are
4495 // permitted.
4496 } else {
4497 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4498 if (!ParamRef->getPointeeType()->isFunctionType()) {
4499 // C++ [temp.arg.nontype]p5b3:
4500 // For a non-type template-parameter of type reference to
4501 // object, no conversions apply. The type referred to by the
4502 // reference may be more cv-qualified than the (otherwise
4503 // identical) type of the template- argument. The
4504 // template-parameter is bound directly to the
4505 // template-argument, which shall be an lvalue.
4506
4507 // FIXME: Other qualifiers?
4508 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4509 unsigned ArgQuals = ArgType.getCVRQualifiers();
4510
4511 if ((ParamQuals | ArgQuals) != ParamQuals) {
4512 S.Diag(Arg->getLocStart(),
4513 diag::err_template_arg_ref_bind_ignores_quals)
4514 << ParamType << Arg->getType() << Arg->getSourceRange();
4515 S.Diag(Param->getLocation(), diag::note_template_param_here);
4516 return true;
4517 }
4518 }
4519 }
4520
4521 // At this point, the template argument refers to an object or
4522 // function with external linkage. We now need to check whether the
4523 // argument and parameter types are compatible.
4524 if (!S.Context.hasSameUnqualifiedType(ArgType,
4525 ParamType.getNonReferenceType())) {
4526 // We can't perform this conversion or binding.
4527 if (ParamType->isReferenceType())
4528 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4529 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4530 else
4531 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4532 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4533 S.Diag(Param->getLocation(), diag::note_template_param_here);
4534 return true;
4535 }
4536 }
4537
4538 return false;
4539}
4540
Douglas Gregorccb07762009-02-11 19:52:55 +00004541/// \brief Checks whether the given template argument is the address
4542/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004543static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004544CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4545 NonTypeTemplateParmDecl *Param,
4546 QualType ParamType,
4547 Expr *ArgIn,
4548 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004549 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004550 Expr *Arg = ArgIn;
4551 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004552
Douglas Gregorb242683d2010-04-01 18:32:35 +00004553 bool AddressTaken = false;
4554 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004555 if (S.getLangOpts().MicrosoftExt) {
4556 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4557 // dereference and address-of operators.
4558 Arg = Arg->IgnoreParenCasts();
4559
4560 bool ExtWarnMSTemplateArg = false;
4561 UnaryOperatorKind FirstOpKind;
4562 SourceLocation FirstOpLoc;
4563 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4564 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4565 if (UnOpKind == UO_Deref)
4566 ExtWarnMSTemplateArg = true;
4567 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4568 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4569 if (!AddrOpLoc.isValid()) {
4570 FirstOpKind = UnOpKind;
4571 FirstOpLoc = UnOp->getOperatorLoc();
4572 }
4573 } else
4574 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004575 }
David Majnemer61c39a12013-08-23 05:39:39 +00004576 if (FirstOpLoc.isValid()) {
4577 if (ExtWarnMSTemplateArg)
4578 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4579 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004580
David Majnemer61c39a12013-08-23 05:39:39 +00004581 if (FirstOpKind == UO_AddrOf)
4582 AddressTaken = true;
4583 else if (Arg->getType()->isPointerType()) {
4584 // We cannot let pointers get dereferenced here, that is obviously not a
4585 // constant expression.
4586 assert(FirstOpKind == UO_Deref);
4587 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4588 << Arg->getSourceRange();
4589 }
4590 }
4591 } else {
4592 // See through any implicit casts we added to fix the type.
4593 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004594
David Majnemer61c39a12013-08-23 05:39:39 +00004595 // C++ [temp.arg.nontype]p1:
4596 //
4597 // A template-argument for a non-type, non-template
4598 // template-parameter shall be one of: [...]
4599 //
4600 // -- the address of an object or function with external
4601 // linkage, including function templates and function
4602 // template-ids but excluding non-static class members,
4603 // expressed as & id-expression where the & is optional if
4604 // the name refers to a function or array, or if the
4605 // corresponding template-parameter is a reference; or
4606
4607 // In C++98/03 mode, give an extension warning on any extra parentheses.
4608 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4609 bool ExtraParens = false;
4610 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4611 if (!Invalid && !ExtraParens) {
4612 S.Diag(Arg->getLocStart(),
4613 S.getLangOpts().CPlusPlus11
4614 ? diag::warn_cxx98_compat_template_arg_extra_parens
4615 : diag::ext_template_arg_extra_parens)
4616 << Arg->getSourceRange();
4617 ExtraParens = true;
4618 }
4619
4620 Arg = Parens->getSubExpr();
4621 }
4622
4623 while (SubstNonTypeTemplateParmExpr *subst =
4624 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4625 Arg = subst->getReplacement()->IgnoreImpCasts();
4626
4627 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4628 if (UnOp->getOpcode() == UO_AddrOf) {
4629 Arg = UnOp->getSubExpr();
4630 AddressTaken = true;
4631 AddrOpLoc = UnOp->getOperatorLoc();
4632 }
4633 }
4634
4635 while (SubstNonTypeTemplateParmExpr *subst =
4636 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4637 Arg = subst->getReplacement()->IgnoreImpCasts();
4638 }
John McCall7c454bb2011-07-15 05:09:51 +00004639
David Majnemer07910d62014-06-26 07:48:46 +00004640 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4641 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4642
4643 // If our parameter has pointer type, check for a null template value.
4644 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4645 NullPointerValueKind NPV;
4646 // dllimport'd entities aren't constant but are available inside of template
4647 // arguments.
4648 if (Entity && Entity->hasAttr<DLLImportAttr>())
4649 NPV = NPV_NotNullPointer;
4650 else
4651 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4652 switch (NPV) {
4653 case NPV_NullPointer:
4654 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004655 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4656 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004657 return false;
4658
4659 case NPV_Error:
4660 return true;
4661
4662 case NPV_NotNullPointer:
4663 break;
4664 }
4665 }
4666
Chandler Carruth724a8a12010-01-31 10:01:20 +00004667 // Stop checking the precise nature of the argument if it is value dependent,
4668 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004669 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004670 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004671 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004672 }
David Majnemer61c39a12013-08-23 05:39:39 +00004673
4674 if (isa<CXXUuidofExpr>(Arg)) {
4675 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4676 ArgIn, Arg, ArgType))
4677 return true;
4678
4679 Converted = TemplateArgument(ArgIn);
4680 return false;
4681 }
4682
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004683 if (!DRE) {
4684 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4685 << Arg->getSourceRange();
4686 S.Diag(Param->getLocation(), diag::note_template_param_here);
4687 return true;
4688 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004689
Douglas Gregorccb07762009-02-11 19:52:55 +00004690 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004691 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004692 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004693 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004694 S.Diag(Param->getLocation(), diag::note_template_param_here);
4695 return true;
4696 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004697
4698 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004699 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004700 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004701 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004702 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004703 S.Diag(Param->getLocation(), diag::note_template_param_here);
4704 return true;
4705 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004706 }
Mike Stump11289f42009-09-09 15:08:12 +00004707
Richard Smith9380e0e2012-04-04 21:11:30 +00004708 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4709 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004710
Richard Smith9380e0e2012-04-04 21:11:30 +00004711 // A non-type template argument must refer to an object or function.
4712 if (!Func && !Var) {
4713 // We found something, but we don't know specifically what it is.
4714 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4715 << Arg->getSourceRange();
4716 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4717 return true;
4718 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004719
Richard Smith9380e0e2012-04-04 21:11:30 +00004720 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004721 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004722 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004723 diag::warn_cxx98_compat_template_arg_object_internal :
4724 diag::ext_template_arg_object_internal)
4725 << !Func << Entity << Arg->getSourceRange();
4726 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4727 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004728 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004729 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4730 << !Func << Entity << Arg->getSourceRange();
4731 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4732 << !Func;
4733 return true;
4734 }
4735
4736 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004737 // If the template parameter has pointer type, the function decays.
4738 if (ParamType->isPointerType() && !AddressTaken)
4739 ArgType = S.Context.getPointerType(Func->getType());
4740 else if (AddressTaken && ParamType->isReferenceType()) {
4741 // If we originally had an address-of operator, but the
4742 // parameter has reference type, complain and (if things look
4743 // like they will work) drop the address-of operator.
4744 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4745 ParamType.getNonReferenceType())) {
4746 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4747 << ParamType;
4748 S.Diag(Param->getLocation(), diag::note_template_param_here);
4749 return true;
4750 }
4751
4752 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4753 << ParamType
4754 << FixItHint::CreateRemoval(AddrOpLoc);
4755 S.Diag(Param->getLocation(), diag::note_template_param_here);
4756
4757 ArgType = Func->getType();
4758 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004759 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004760 // A value of reference type is not an object.
4761 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004762 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004763 diag::err_template_arg_reference_var)
4764 << Var->getType() << Arg->getSourceRange();
4765 S.Diag(Param->getLocation(), diag::note_template_param_here);
4766 return true;
4767 }
4768
Richard Smith9380e0e2012-04-04 21:11:30 +00004769 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004770 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004771 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4772 << Arg->getSourceRange();
4773 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4774 return true;
4775 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004776
4777 // If the template parameter has pointer type, we must have taken
4778 // the address of this object.
4779 if (ParamType->isReferenceType()) {
4780 if (AddressTaken) {
4781 // If we originally had an address-of operator, but the
4782 // parameter has reference type, complain and (if things look
4783 // like they will work) drop the address-of operator.
4784 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4785 ParamType.getNonReferenceType())) {
4786 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4787 << ParamType;
4788 S.Diag(Param->getLocation(), diag::note_template_param_here);
4789 return true;
4790 }
4791
4792 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4793 << ParamType
4794 << FixItHint::CreateRemoval(AddrOpLoc);
4795 S.Diag(Param->getLocation(), diag::note_template_param_here);
4796
4797 ArgType = Var->getType();
4798 }
4799 } else if (!AddressTaken && ParamType->isPointerType()) {
4800 if (Var->getType()->isArrayType()) {
4801 // Array-to-pointer decay.
4802 ArgType = S.Context.getArrayDecayedType(Var->getType());
4803 } else {
4804 // If the template parameter has pointer type but the address of
4805 // this object was not taken, complain and (possibly) recover by
4806 // taking the address of the entity.
4807 ArgType = S.Context.getPointerType(Var->getType());
4808 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4809 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4810 << ParamType;
4811 S.Diag(Param->getLocation(), diag::note_template_param_here);
4812 return true;
4813 }
4814
4815 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4816 << ParamType
4817 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4818
4819 S.Diag(Param->getLocation(), diag::note_template_param_here);
4820 }
4821 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004822 }
Mike Stump11289f42009-09-09 15:08:12 +00004823
David Majnemer61c39a12013-08-23 05:39:39 +00004824 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4825 Arg, ArgType))
4826 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004827
4828 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004829 Converted =
4830 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004831 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004832 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004833}
4834
4835/// \brief Checks whether the given template argument is a pointer to
4836/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004837static bool CheckTemplateArgumentPointerToMember(Sema &S,
4838 NonTypeTemplateParmDecl *Param,
4839 QualType ParamType,
4840 Expr *&ResultArg,
4841 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004842 bool Invalid = false;
4843
Douglas Gregor20fdef32012-04-10 17:08:25 +00004844 // Check for a null pointer value.
4845 Expr *Arg = ResultArg;
4846 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4847 case NPV_Error:
4848 return true;
4849 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004850 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004851 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4852 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004853 return false;
4854 case NPV_NotNullPointer:
4855 break;
4856 }
4857
4858 bool ObjCLifetimeConversion;
4859 if (S.IsQualificationConversion(Arg->getType(),
4860 ParamType.getNonReferenceType(),
4861 false, ObjCLifetimeConversion)) {
4862 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004863 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004864 ResultArg = Arg;
4865 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4866 ParamType.getNonReferenceType())) {
4867 // We can't perform this conversion.
4868 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4869 << Arg->getType() << ParamType << Arg->getSourceRange();
4870 S.Diag(Param->getLocation(), diag::note_template_param_here);
4871 return true;
4872 }
4873
Douglas Gregorccb07762009-02-11 19:52:55 +00004874 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004875 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004876 Arg = Cast->getSubExpr();
4877
4878 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004879 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004880 // A template-argument for a non-type, non-template
4881 // template-parameter shall be one of: [...]
4882 //
4883 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004884 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004885
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004886 // In C++98/03 mode, give an extension warning on any extra parentheses.
4887 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4888 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004889 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004890 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004891 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004892 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004893 diag::warn_cxx98_compat_template_arg_extra_parens :
4894 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004895 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004896 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004897 }
4898
4899 Arg = Parens->getSubExpr();
4900 }
4901
John McCall7c454bb2011-07-15 05:09:51 +00004902 while (SubstNonTypeTemplateParmExpr *subst =
4903 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4904 Arg = subst->getReplacement()->IgnoreImpCasts();
4905
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004906 // A pointer-to-member constant written &Class::member.
4907 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004908 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004909 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4910 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004911 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004912 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004913 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004914 // A constant of pointer-to-member type.
4915 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4916 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4917 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004918 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004919 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004920 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004921 } else {
4922 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004923 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004924 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004925 return Invalid;
4926 }
4927 }
4928 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004929
Craig Topperc3ec1492014-05-26 06:22:03 +00004930 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004932
Douglas Gregorccb07762009-02-11 19:52:55 +00004933 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004934 return S.Diag(Arg->getLocStart(),
4935 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004936 << Arg->getSourceRange();
4937
David Majnemer3ac84e62013-10-22 21:56:38 +00004938 if (isa<FieldDecl>(DRE->getDecl()) ||
4939 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4940 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004941 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004942 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004943 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4944 "Only non-static member pointers can make it here");
4945
4946 // Okay: this is the address of a non-static member, and therefore
4947 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004948 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004949 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004950 } else {
4951 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004952 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004953 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004954 return Invalid;
4955 }
4956
4957 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004958 S.Diag(Arg->getLocStart(),
4959 diag::err_template_arg_not_pointer_to_member_form)
4960 << Arg->getSourceRange();
4961 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004962 return true;
4963}
4964
Douglas Gregord32e0282009-02-09 23:23:08 +00004965/// \brief Check a template argument against its corresponding
4966/// non-type template parameter.
4967///
Douglas Gregor463421d2009-03-03 04:44:36 +00004968/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004969/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004970/// returns the converted template argument. \p ParamType is the
4971/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004972ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004973 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004974 TemplateArgument &Converted,
4975 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004976 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004977
Douglas Gregor86560402009-02-10 23:36:10 +00004978 // If either the parameter has a dependent type or the argument is
4979 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004980 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004981 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004982 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004983 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004984 }
Douglas Gregor86560402009-02-10 23:36:10 +00004985
Richard Smithd663fdd2014-12-17 20:42:37 +00004986 // We should have already dropped all cv-qualifiers by now.
4987 assert(!ParamType.hasQualifiers() &&
4988 "non-type template parameter type cannot be qualified");
4989
4990 if (CTAK == CTAK_Deduced &&
4991 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4992 // C++ [temp.deduct.type]p17:
4993 // If, in the declaration of a function template with a non-type
4994 // template-parameter, the non-type template-parameter is used
4995 // in an expression in the function parameter-list and, if the
4996 // corresponding template-argument is deduced, the
4997 // template-argument type shall match the type of the
4998 // template-parameter exactly, except that a template-argument
4999 // deduced from an array bound may be of any integral type.
5000 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
5001 << Arg->getType().getUnqualifiedType()
5002 << ParamType.getUnqualifiedType();
5003 Diag(Param->getLocation(), diag::note_template_param_here);
5004 return ExprError();
5005 }
5006
Richard Smith410cc892014-11-26 03:26:53 +00005007 if (getLangOpts().CPlusPlus1z) {
5008 // FIXME: We can do some limited checking for a value-dependent but not
5009 // type-dependent argument.
5010 if (Arg->isValueDependent()) {
5011 Converted = TemplateArgument(Arg);
5012 return Arg;
5013 }
5014
5015 // C++1z [temp.arg.nontype]p1:
5016 // A template-argument for a non-type template parameter shall be
5017 // a converted constant expression of the type of the template-parameter.
5018 APValue Value;
5019 ExprResult ArgResult = CheckConvertedConstantExpression(
5020 Arg, ParamType, Value, CCEK_TemplateArg);
5021 if (ArgResult.isInvalid())
5022 return ExprError();
5023
Richard Smithd663fdd2014-12-17 20:42:37 +00005024 QualType CanonParamType = Context.getCanonicalType(ParamType);
5025
Richard Smith410cc892014-11-26 03:26:53 +00005026 // Convert the APValue to a TemplateArgument.
5027 switch (Value.getKind()) {
5028 case APValue::Uninitialized:
5029 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005030 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005031 break;
5032 case APValue::Int:
5033 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005034 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005035 break;
5036 case APValue::MemberPointer: {
5037 assert(ParamType->isMemberPointerType());
5038
5039 // FIXME: We need TemplateArgument representation and mangling for these.
5040 if (!Value.getMemberPointerPath().empty()) {
5041 Diag(Arg->getLocStart(),
5042 diag::err_template_arg_member_ptr_base_derived_not_supported)
5043 << Value.getMemberPointerDecl() << ParamType
5044 << Arg->getSourceRange();
5045 return ExprError();
5046 }
5047
5048 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005049 Converted = VD ? TemplateArgument(VD, CanonParamType)
5050 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005051 break;
5052 }
5053 case APValue::LValue: {
5054 // For a non-type template-parameter of pointer or reference type,
5055 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00005056 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5057 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00005058 // -- a temporary object
5059 // -- a string literal
5060 // -- the result of a typeid expression, or
5061 // -- a predefind __func__ variable
5062 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5063 if (isa<CXXUuidofExpr>(E)) {
5064 Converted = TemplateArgument(const_cast<Expr*>(E));
5065 break;
5066 }
5067 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5068 << Arg->getSourceRange();
5069 return ExprError();
5070 }
5071 auto *VD = const_cast<ValueDecl *>(
5072 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5073 // -- a subobject
5074 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5075 VD && VD->getType()->isArrayType() &&
5076 Value.getLValuePath()[0].ArrayIndex == 0 &&
5077 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5078 // Per defect report (no number yet):
5079 // ... other than a pointer to the first element of a complete array
5080 // object.
5081 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5082 Value.isLValueOnePastTheEnd()) {
5083 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5084 << Value.getAsString(Context, ParamType);
5085 return ExprError();
5086 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005087 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005088 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005089 assert((!VD || !ParamType->isNullPtrType()) &&
5090 "non-null value of type nullptr_t?");
5091 Converted = VD ? TemplateArgument(VD, CanonParamType)
5092 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005093 break;
5094 }
5095 case APValue::AddrLabelDiff:
5096 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5097 case APValue::Float:
5098 case APValue::ComplexInt:
5099 case APValue::ComplexFloat:
5100 case APValue::Vector:
5101 case APValue::Array:
5102 case APValue::Struct:
5103 case APValue::Union:
5104 llvm_unreachable("invalid kind for template argument");
5105 }
5106
5107 return ArgResult.get();
5108 }
5109
Douglas Gregor86560402009-02-10 23:36:10 +00005110 // C++ [temp.arg.nontype]p5:
5111 // The following conversions are performed on each expression used
5112 // as a non-type template-argument. If a non-type
5113 // template-argument cannot be converted to the type of the
5114 // corresponding template-parameter then the program is
5115 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005116 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005117 // C++11:
5118 // -- for a non-type template-parameter of integral or
5119 // enumeration type, conversions permitted in a converted
5120 // constant expression are applied.
5121 //
5122 // C++98:
5123 // -- for a non-type template-parameter of integral or
5124 // enumeration type, integral promotions (4.5) and integral
5125 // conversions (4.7) are applied.
5126
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005127 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005128 // We can't check arbitrary value-dependent arguments.
5129 // FIXME: If there's no viable conversion to the template parameter type,
5130 // we should be able to diagnose that prior to instantiation.
5131 if (Arg->isValueDependent()) {
5132 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005133 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00005134 }
5135
5136 // C++ [temp.arg.nontype]p1:
5137 // A template-argument for a non-type, non-template template-parameter
5138 // shall be one of:
5139 //
5140 // -- for a non-type template-parameter of integral or enumeration
5141 // type, a converted constant expression of the type of the
5142 // template-parameter; or
5143 llvm::APSInt Value;
5144 ExprResult ArgResult =
5145 CheckConvertedConstantExpression(Arg, ParamType, Value,
5146 CCEK_TemplateArg);
5147 if (ArgResult.isInvalid())
5148 return ExprError();
5149
5150 // Widen the argument value to sizeof(parameter type). This is almost
5151 // always a no-op, except when the parameter type is bool. In
5152 // that case, this may extend the argument from 1 bit to 8 bits.
5153 QualType IntegerType = ParamType;
5154 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5155 IntegerType = Enum->getDecl()->getIntegerType();
5156 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5157
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005158 Converted = TemplateArgument(Context, Value,
5159 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005160 return ArgResult;
5161 }
5162
Richard Smith08b12f12011-10-27 22:11:44 +00005163 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5164 if (ArgResult.isInvalid())
5165 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005166 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005167
5168 QualType ArgType = Arg->getType();
5169
Douglas Gregor86560402009-02-10 23:36:10 +00005170 // C++ [temp.arg.nontype]p1:
5171 // A template-argument for a non-type, non-template
5172 // template-parameter shall be one of:
5173 //
5174 // -- an integral constant-expression of integral or enumeration
5175 // type; or
5176 // -- the name of a non-type template-parameter; or
5177 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005178 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005179 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005180 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005181 diag::err_template_arg_not_integral_or_enumeral)
5182 << ArgType << Arg->getSourceRange();
5183 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005184 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005185 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005186 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5187 QualType T;
5188
5189 public:
5190 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005191
5192 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5193 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005194 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5195 }
5196 } Diagnoser(ArgType);
5197
5198 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005199 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005200 if (!Arg)
5201 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005202 }
5203
Richard Smithd663fdd2014-12-17 20:42:37 +00005204 // From here on out, all we care about is the unqualified form
5205 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005206 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005207
5208 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005209 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005210 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005211 } else if (ParamType->isBooleanType()) {
5212 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005213 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005214 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5215 !ParamType->isEnumeralType()) {
5216 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005217 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005218 } else {
5219 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005220 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005221 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005222 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005223 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005224 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005225 }
5226
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005227 // Add the value of this argument to the list of converted
5228 // arguments. We use the bitwidth and signedness of the template
5229 // parameter.
5230 if (Arg->isValueDependent()) {
5231 // The argument is value-dependent. Create a new
5232 // TemplateArgument with the converted expression.
5233 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005234 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005235 }
5236
Douglas Gregor52aba872009-03-14 00:20:21 +00005237 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005238 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005239 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005240
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005241 if (ParamType->isBooleanType()) {
5242 // Value must be zero or one.
5243 Value = Value != 0;
5244 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5245 if (Value.getBitWidth() != AllowedBits)
5246 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005247 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005248 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005249 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005250
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005251 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005252 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005253 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005254 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005255 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005256 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005257
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005258 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005259 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005260 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005261 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005262 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5263 << Arg->getSourceRange();
5264 Diag(Param->getLocation(), diag::note_template_param_here);
5265 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005266
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005267 // Complain if we overflowed the template parameter's type.
5268 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005269 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005270 RequiredBits = OldValue.getActiveBits();
5271 else if (OldValue.isUnsigned())
5272 RequiredBits = OldValue.getActiveBits() + 1;
5273 else
5274 RequiredBits = OldValue.getMinSignedBits();
5275 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005276 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005277 diag::warn_template_arg_too_large)
5278 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5279 << Arg->getSourceRange();
5280 Diag(Param->getLocation(), diag::note_template_param_here);
5281 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005282 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005283
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005284 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005285 ParamType->isEnumeralType()
5286 ? Context.getCanonicalType(ParamType)
5287 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005288 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005289 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005290
Richard Smith08b12f12011-10-27 22:11:44 +00005291 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005292 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5293
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005294 // Handle pointer-to-function, reference-to-function, and
5295 // pointer-to-member-function all in (roughly) the same way.
5296 if (// -- For a non-type template-parameter of type pointer to
5297 // function, only the function-to-pointer conversion (4.3) is
5298 // applied. If the template-argument represents a set of
5299 // overloaded functions (or a pointer to such), the matching
5300 // function is selected from the set (13.4).
5301 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005302 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005303 // -- For a non-type template-parameter of type reference to
5304 // function, no conversions apply. If the template-argument
5305 // represents a set of overloaded functions, the matching
5306 // function is selected from the set (13.4).
5307 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005308 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005309 // -- For a non-type template-parameter of type pointer to
5310 // member function, no conversions apply. If the
5311 // template-argument represents a set of overloaded member
5312 // functions, the matching member function is selected from
5313 // the set (13.4).
5314 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005315 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005316 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005317
Douglas Gregor064fdb22010-04-14 23:11:21 +00005318 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005319 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005320 true,
5321 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005322 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005323 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005324
5325 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5326 ArgType = Arg->getType();
5327 } else
John Wiegley01296292011-04-08 18:41:53 +00005328 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005329 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005330
John Wiegley01296292011-04-08 18:41:53 +00005331 if (!ParamType->isMemberPointerType()) {
5332 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5333 ParamType,
5334 Arg, Converted))
5335 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005336 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005337 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005338
Douglas Gregor20fdef32012-04-10 17:08:25 +00005339 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5340 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005341 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005342 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005343 }
5344
Chris Lattner696197c2009-02-20 21:37:53 +00005345 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005346 // -- for a non-type template-parameter of type pointer to
5347 // object, qualification conversions (4.4) and the
5348 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005349 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005350 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005351 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005352
John Wiegley01296292011-04-08 18:41:53 +00005353 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5354 ParamType,
5355 Arg, Converted))
5356 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005357 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005358 }
Mike Stump11289f42009-09-09 15:08:12 +00005359
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005360 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005361 // -- For a non-type template-parameter of type reference to
5362 // object, no conversions apply. The type referred to by the
5363 // reference may be more cv-qualified than the (otherwise
5364 // identical) type of the template-argument. The
5365 // template-parameter is bound directly to the
5366 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005367 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005368 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005369
Douglas Gregor064fdb22010-04-14 23:11:21 +00005370 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005371 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5372 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005373 true,
5374 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005375 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005376 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005377
5378 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5379 ArgType = Arg->getType();
5380 } else
John Wiegley01296292011-04-08 18:41:53 +00005381 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005382 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005383
John Wiegley01296292011-04-08 18:41:53 +00005384 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5385 ParamType,
5386 Arg, Converted))
5387 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005388 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005389 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005390
Douglas Gregor20fdef32012-04-10 17:08:25 +00005391 // Deal with parameters of type std::nullptr_t.
5392 if (ParamType->isNullPtrType()) {
5393 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5394 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005395 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005396 }
5397
5398 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5399 case NPV_NotNullPointer:
5400 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5401 << Arg->getType() << ParamType;
5402 Diag(Param->getLocation(), diag::note_template_param_here);
5403 return ExprError();
5404
5405 case NPV_Error:
5406 return ExprError();
5407
5408 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005409 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005410 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5411 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005412 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005413 }
5414 }
5415
Douglas Gregor0e558532009-02-11 16:16:59 +00005416 // -- For a non-type template-parameter of type pointer to data
5417 // member, qualification conversions (4.4) are applied.
5418 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5419
Douglas Gregor20fdef32012-04-10 17:08:25 +00005420 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5421 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005422 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005423 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005424}
5425
5426/// \brief Check a template argument against its corresponding
5427/// template template parameter.
5428///
5429/// This routine implements the semantics of C++ [temp.arg.template].
5430/// It returns true if an error occurred, and false otherwise.
5431bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005432 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005433 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005434 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005435 TemplateDecl *Template = Name.getAsTemplateDecl();
5436 if (!Template) {
5437 // Any dependent template name is fine.
5438 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5439 return false;
5440 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005441
Richard Smith3f1b5d02011-05-05 21:57:07 +00005442 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005443 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005444 // the name of a class template or an alias template, expressed as an
5445 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005446 // primary class templates are considered when matching the
5447 // template template argument with the corresponding parameter;
5448 // partial specializations are not considered even if their
5449 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005450 //
5451 // Note that we also allow template template parameters here, which
5452 // will happen when we are dealing with, e.g., class template
5453 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005454 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005455 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00005456 !isa<TypeAliasTemplateDecl>(Template) &&
5457 !isa<BuiltinTemplateDecl>(Template)) {
5458 assert(isa<FunctionTemplateDecl>(Template) &&
5459 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00005460 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00005461 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5462 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00005463 }
5464
Richard Smith1fde8ec2012-09-07 02:06:42 +00005465 TemplateParameterList *Params = Param->getTemplateParameters();
5466 if (Param->isExpandedParameterPack())
5467 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5468
Douglas Gregor85e0f662009-02-10 00:24:35 +00005469 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005470 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005471 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005472 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005473 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005474}
5475
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005476/// \brief Given a non-type template argument that refers to a
5477/// declaration and the type of its corresponding non-type template
5478/// parameter, produce an expression that properly refers to that
5479/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005480ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005481Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5482 QualType ParamType,
5483 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005484 // C++ [temp.param]p8:
5485 //
5486 // A non-type template-parameter of type "array of T" or
5487 // "function returning T" is adjusted to be of type "pointer to
5488 // T" or "pointer to function returning T", respectively.
5489 if (ParamType->isArrayType())
5490 ParamType = Context.getArrayDecayedType(ParamType);
5491 else if (ParamType->isFunctionType())
5492 ParamType = Context.getPointerType(ParamType);
5493
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005494 // For a NULL non-type template argument, return nullptr casted to the
5495 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005496 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005497 return ImpCastExprToType(
5498 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5499 ParamType,
5500 ParamType->getAs<MemberPointerType>()
5501 ? CK_NullToMemberPointer
5502 : CK_NullToPointer);
5503 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005504 assert(Arg.getKind() == TemplateArgument::Declaration &&
5505 "Only declaration template arguments permitted here");
5506
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005507 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5508
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005509 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005510 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5511 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005512 // If the value is a class member, we might have a pointer-to-member.
5513 // Determine whether the non-type template template parameter is of
5514 // pointer-to-member type. If so, we need to build an appropriate
5515 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5516 // would refer to the member itself.
5517 if (ParamType->isMemberPointerType()) {
5518 QualType ClassType
5519 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5520 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005521 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005522 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005523 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005524 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005525
5526 // The actual value-ness of this is unimportant, but for
5527 // internal consistency's sake, references to instance methods
5528 // are r-values.
5529 ExprValueKind VK = VK_LValue;
5530 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5531 VK = VK_RValue;
5532
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005533 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005534 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005535 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005536 Loc,
5537 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005538 if (RefExpr.isInvalid())
5539 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005540
John McCalle3027922010-08-25 11:45:40 +00005541 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005542
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005543 // We might need to perform a trailing qualification conversion, since
5544 // the element type on the parameter could be more qualified than the
5545 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005546 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005547 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005548 ParamType.getUnqualifiedType(), false,
5549 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005550 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005551
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005552 assert(!RefExpr.isInvalid() &&
5553 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005554 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005555 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005556 }
5557 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005558
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005559 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005560
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005561 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005562 // When the non-type template parameter is a pointer, take the
5563 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005564 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005565 if (RefExpr.isInvalid())
5566 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005567
5568 if (T->isFunctionType() || T->isArrayType()) {
5569 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005570 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005571 if (RefExpr.isInvalid())
5572 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005573
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005574 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005575 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005576
Douglas Gregorb242683d2010-04-01 18:32:35 +00005577 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005578 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005579 }
5580
John McCall7decc9e2010-11-18 06:31:45 +00005581 ExprValueKind VK = VK_RValue;
5582
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005583 // If the non-type template parameter has reference type, qualify the
5584 // resulting declaration reference with the extra qualifiers on the
5585 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005586 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5587 VK = VK_LValue;
5588 T = Context.getQualifiedType(T,
5589 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005590 } else if (isa<FunctionDecl>(VD)) {
5591 // References to functions are always lvalues.
5592 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005594
John McCall7decc9e2010-11-18 06:31:45 +00005595 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005596}
5597
5598/// \brief Construct a new expression that refers to the given
5599/// integral template argument with the given source-location
5600/// information.
5601///
5602/// This routine takes care of the mapping from an integral template
5603/// argument (which may have any integral type) to the appropriate
5604/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005605ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005606Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5607 SourceLocation Loc) {
5608 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005609 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005610 QualType OrigT = Arg.getIntegralType();
5611
5612 // If this is an enum type that we're instantiating, we need to use an integer
5613 // type the same size as the enumerator. We don't want to build an
5614 // IntegerLiteral with enum type. The integer type of an enum type can be of
5615 // any integral type with C++11 enum classes, make sure we create the right
5616 // type of literal for it.
5617 QualType T = OrigT;
5618 if (const EnumType *ET = OrigT->getAs<EnumType>())
5619 T = ET->getDecl()->getIntegerType();
5620
5621 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005622 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005623 // This does not need to handle u8 character literals because those are
5624 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005625 CharacterLiteral::CharacterKind Kind;
5626 if (T->isWideCharType())
5627 Kind = CharacterLiteral::Wide;
5628 else if (T->isChar16Type())
5629 Kind = CharacterLiteral::UTF16;
5630 else if (T->isChar32Type())
5631 Kind = CharacterLiteral::UTF32;
5632 else
5633 Kind = CharacterLiteral::Ascii;
5634
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005635 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5636 Kind, T, Loc);
5637 } else if (T->isBooleanType()) {
5638 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5639 T, Loc);
5640 } else if (T->isNullPtrType()) {
5641 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5642 } else {
5643 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005644 }
5645
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005646 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005647 // FIXME: This is a hack. We need a better way to handle substituted
5648 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005649 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5650 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005651 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005652 Loc, Loc);
5653 }
5654
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005655 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005656}
5657
Douglas Gregor641040a2011-01-12 23:45:44 +00005658/// \brief Match two template parameters within template parameter lists.
5659static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5660 bool Complain,
5661 Sema::TemplateParameterListEqualKind Kind,
5662 SourceLocation TemplateArgLoc) {
5663 // Check the actual kind (type, non-type, template).
5664 if (Old->getKind() != New->getKind()) {
5665 if (Complain) {
5666 unsigned NextDiag = diag::err_template_param_different_kind;
5667 if (TemplateArgLoc.isValid()) {
5668 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5669 NextDiag = diag::note_template_param_different_kind;
5670 }
5671 S.Diag(New->getLocation(), NextDiag)
5672 << (Kind != Sema::TPL_TemplateMatch);
5673 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5674 << (Kind != Sema::TPL_TemplateMatch);
5675 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005676
Douglas Gregor641040a2011-01-12 23:45:44 +00005677 return false;
5678 }
5679
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005680 // Check that both are parameter packs are neither are parameter packs.
5681 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005682 // template template parameter, the template template parameter can have
5683 // a parameter pack where the template template argument does not.
5684 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5685 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5686 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005687 if (Complain) {
5688 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5689 if (TemplateArgLoc.isValid()) {
5690 S.Diag(TemplateArgLoc,
5691 diag::err_template_arg_template_params_mismatch);
5692 NextDiag = diag::note_template_parameter_pack_non_pack;
5693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005694
Douglas Gregor641040a2011-01-12 23:45:44 +00005695 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5696 : isa<NonTypeTemplateParmDecl>(New)? 1
5697 : 2;
5698 S.Diag(New->getLocation(), NextDiag)
5699 << ParamKind << New->isParameterPack();
5700 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5701 << ParamKind << Old->isParameterPack();
5702 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005703
Douglas Gregor641040a2011-01-12 23:45:44 +00005704 return false;
5705 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005706
Douglas Gregor641040a2011-01-12 23:45:44 +00005707 // For non-type template parameters, check the type of the parameter.
5708 if (NonTypeTemplateParmDecl *OldNTTP
5709 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5710 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005711
Douglas Gregor641040a2011-01-12 23:45:44 +00005712 // If we are matching a template template argument to a template
5713 // template parameter and one of the non-type template parameter types
5714 // is dependent, then we must wait until template instantiation time
5715 // to actually compare the arguments.
5716 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5717 (OldNTTP->getType()->isDependentType() ||
5718 NewNTTP->getType()->isDependentType()))
5719 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720
Douglas Gregor641040a2011-01-12 23:45:44 +00005721 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5722 if (Complain) {
5723 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5724 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005725 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005726 diag::err_template_arg_template_params_mismatch);
5727 NextDiag = diag::note_template_nontype_parm_different_type;
5728 }
5729 S.Diag(NewNTTP->getLocation(), NextDiag)
5730 << NewNTTP->getType()
5731 << (Kind != Sema::TPL_TemplateMatch);
5732 S.Diag(OldNTTP->getLocation(),
5733 diag::note_template_nontype_parm_prev_declaration)
5734 << OldNTTP->getType();
5735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005736
Douglas Gregor641040a2011-01-12 23:45:44 +00005737 return false;
5738 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005739
Douglas Gregor641040a2011-01-12 23:45:44 +00005740 return true;
5741 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005742
Douglas Gregor641040a2011-01-12 23:45:44 +00005743 // For template template parameters, check the template parameter types.
5744 // The template parameter lists of template template
5745 // parameters must agree.
5746 if (TemplateTemplateParmDecl *OldTTP
5747 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005748 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005749 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5750 OldTTP->getTemplateParameters(),
5751 Complain,
5752 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005754 : Kind),
5755 TemplateArgLoc);
5756 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005757
Douglas Gregor641040a2011-01-12 23:45:44 +00005758 return true;
5759}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005760
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005761/// \brief Diagnose a known arity mismatch when comparing template argument
5762/// lists.
5763static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005764void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005765 TemplateParameterList *New,
5766 TemplateParameterList *Old,
5767 Sema::TemplateParameterListEqualKind Kind,
5768 SourceLocation TemplateArgLoc) {
5769 unsigned NextDiag = diag::err_template_param_list_different_arity;
5770 if (TemplateArgLoc.isValid()) {
5771 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5772 NextDiag = diag::note_template_param_list_different_arity;
5773 }
5774 S.Diag(New->getTemplateLoc(), NextDiag)
5775 << (New->size() > Old->size())
5776 << (Kind != Sema::TPL_TemplateMatch)
5777 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5778 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5779 << (Kind != Sema::TPL_TemplateMatch)
5780 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5781}
5782
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005783/// \brief Determine whether the given template parameter lists are
5784/// equivalent.
5785///
Mike Stump11289f42009-09-09 15:08:12 +00005786/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005787/// source code as part of a new template declaration.
5788///
5789/// \param Old The old template parameter list, typically found via
5790/// name lookup of the template declared with this template parameter
5791/// list.
5792///
5793/// \param Complain If true, this routine will produce a diagnostic if
5794/// the template parameter lists are not equivalent.
5795///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005796/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005797///
5798/// \param TemplateArgLoc If this source location is valid, then we
5799/// are actually checking the template parameter list of a template
5800/// argument (New) against the template parameter list of its
5801/// corresponding template template parameter (Old). We produce
5802/// slightly different diagnostics in this scenario.
5803///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005804/// \returns True if the template parameter lists are equal, false
5805/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005806bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005807Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5808 TemplateParameterList *Old,
5809 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005810 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005811 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005812 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5813 if (Complain)
5814 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5815 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005816
5817 return false;
5818 }
5819
Douglas Gregor641040a2011-01-12 23:45:44 +00005820 // C++0x [temp.arg.template]p3:
5821 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005822 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005823 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005824 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005825 // template-parameter-list of P. [...]
5826 TemplateParameterList::iterator NewParm = New->begin();
5827 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005828 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005829 OldParmEnd = Old->end();
5830 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005831 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5832 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005833 if (NewParm == NewParmEnd) {
5834 if (Complain)
5835 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5836 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005837
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005838 return false;
5839 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005840
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005841 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5842 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005843 return false;
5844
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005845 ++NewParm;
5846 continue;
5847 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005848
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005849 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005850 // [...] When P's template- parameter-list contains a template parameter
5851 // pack (14.5.3), the template parameter pack will match zero or more
5852 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005853 // template-parameter-list of A with the same type and form as the
5854 // template parameter pack in P (ignoring whether those template
5855 // parameters are template parameter packs).
5856 for (; NewParm != NewParmEnd; ++NewParm) {
5857 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5858 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005859 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005860 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005862
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005863 // Make sure we exhausted all of the arguments.
5864 if (NewParm != NewParmEnd) {
5865 if (Complain)
5866 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5867 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005868
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005869 return false;
5870 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005871
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005872 return true;
5873}
5874
5875/// \brief Check whether a template can be declared within this scope.
5876///
5877/// If the template declaration is valid in this scope, returns
5878/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005879bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005880Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005881 if (!S)
5882 return false;
5883
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005884 // Find the nearest enclosing declaration scope.
5885 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5886 (S->getFlags() & Scope::TemplateParamScope) != 0)
5887 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005888
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005889 // C++ [temp]p4:
5890 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005891 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005892 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005893 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005894 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005895
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005896 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005897 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005898
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005899 // C++ [temp]p2:
5900 // A template-declaration can appear only as a namespace scope or
5901 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005902 if (Ctx) {
5903 if (Ctx->isFileContext())
5904 return false;
5905 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5906 // C++ [temp.mem]p2:
5907 // A local class shall not have member templates.
5908 if (RD->isLocalClass())
5909 return Diag(TemplateParams->getTemplateLoc(),
5910 diag::err_template_inside_local_class)
5911 << TemplateParams->getSourceRange();
5912 else
5913 return false;
5914 }
5915 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005916
Mike Stump11289f42009-09-09 15:08:12 +00005917 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005918 diag::err_template_outside_namespace_or_class_scope)
5919 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005920}
Douglas Gregor67a65642009-02-17 23:15:12 +00005921
Douglas Gregor54888652009-10-07 00:13:32 +00005922/// \brief Determine what kind of template specialization the given declaration
5923/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005924static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005925 if (!D)
5926 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005927
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005928 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5929 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005930 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5931 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005932 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5933 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005934
Douglas Gregor54888652009-10-07 00:13:32 +00005935 return TSK_Undeclared;
5936}
5937
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005938/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005939/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005940///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005941/// This routine determines whether a template specialization can be declared
5942/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005943///
5944/// \param S the semantic analysis object for which this check is being
5945/// performed.
5946///
5947/// \param Specialized the entity being specialized or instantiated, which
5948/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005949/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005950/// member class).
5951///
5952/// \param PrevDecl the previous declaration of this entity, if any.
5953///
5954/// \param Loc the location of the explicit specialization or instantiation of
5955/// this entity.
5956///
5957/// \param IsPartialSpecialization whether this is a partial specialization of
5958/// a class template.
5959///
Douglas Gregor54888652009-10-07 00:13:32 +00005960/// \returns true if there was an error that we cannot recover from, false
5961/// otherwise.
5962static bool CheckTemplateSpecializationScope(Sema &S,
5963 NamedDecl *Specialized,
5964 NamedDecl *PrevDecl,
5965 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005966 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005967 // Keep these "kind" numbers in sync with the %select statements in the
5968 // various diagnostics emitted by this routine.
5969 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005970 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005971 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005972 else if (isa<VarTemplateDecl>(Specialized))
5973 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005974 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005975 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005976 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005977 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005978 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005979 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005980 else if (isa<RecordDecl>(Specialized))
5981 EntityKind = 7;
5982 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5983 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005984 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005985 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005986 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005987 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005988 return true;
5989 }
5990
Douglas Gregorf47b9112009-02-25 22:02:03 +00005991 // C++ [temp.expl.spec]p2:
5992 // An explicit specialization shall be declared in the namespace
5993 // of which the template is a member, or, for member templates, in
5994 // the namespace of which the enclosing class or enclosing class
5995 // template is a member. An explicit specialization of a member
5996 // function, member class or static data member of a class
5997 // template shall be declared in the namespace of which the class
5998 // template is a member. Such a declaration may also be a
5999 // definition. If the declaration is not a definition, the
6000 // specialization may be defined later in the name- space in which
6001 // the explicit specialization was declared, or in a namespace
6002 // that encloses the one in which the explicit specialization was
6003 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00006004 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00006005 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006006 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006007 return true;
6008 }
Douglas Gregore4b05162009-10-07 17:21:34 +00006009
Douglas Gregor40fb7442009-10-07 17:30:37 +00006010 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006011 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006012 // Do not warn for class scope explicit specialization during
6013 // instantiation, warning was already emitted during pattern
6014 // semantic analysis.
6015 if (!S.ActiveTemplateInstantiations.size())
6016 S.Diag(Loc, diag::ext_function_specialization_in_class)
6017 << Specialized;
6018 } else {
6019 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6020 << Specialized;
6021 return true;
6022 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006024
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006025 if (S.CurContext->isRecord() &&
6026 !S.CurContext->Equals(Specialized->getDeclContext())) {
6027 // Make sure that we're specializing in the right record context.
6028 // Otherwise, things can go horribly wrong.
6029 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6030 << Specialized;
6031 return true;
6032 }
6033
Douglas Gregore4b05162009-10-07 17:21:34 +00006034 // C++ [temp.class.spec]p6:
6035 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006036 // in any namespace scope in which its definition may be defined (14.5.1
6037 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00006038 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00006039 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00006040 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00006041
6042 // Make sure that this redeclaration (or definition) occurs in an enclosing
6043 // namespace.
6044 // Note that HandleDeclarator() performs this check for explicit
6045 // specializations of function templates, static data members, and member
6046 // functions, so we skip the check here for those kinds of entities.
6047 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6048 // Should we refactor that check, so that it occurs later?
6049 if (!DC->Encloses(SpecializedContext) &&
6050 !(isa<FunctionTemplateDecl>(Specialized) ||
6051 isa<FunctionDecl>(Specialized) ||
6052 isa<VarTemplateDecl>(Specialized) ||
6053 isa<VarDecl>(Specialized))) {
6054 if (isa<TranslationUnitDecl>(SpecializedContext))
6055 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6056 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00006057 else if (isa<NamespaceDecl>(SpecializedContext)) {
6058 int Diag = diag::err_template_spec_redecl_out_of_scope;
6059 if (S.getLangOpts().MicrosoftExt)
6060 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6061 S.Diag(Loc, Diag) << EntityKind << Specialized
6062 << cast<NamedDecl>(SpecializedContext);
6063 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00006064 llvm_unreachable("unexpected namespace context for specialization");
6065
6066 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6067 } else if ((!PrevDecl ||
6068 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6069 getTemplateSpecializationKind(PrevDecl) ==
6070 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006071 // C++ [temp.exp.spec]p2:
6072 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006073 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006074 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006075 // An explicit specialization of a member function, member class or
6076 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006077 // namespace of which the class template is a member.
6078 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006079 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006080 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006081 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006082 // C++11 [temp.explicit]p3:
6083 // An explicit instantiation shall appear in an enclosing namespace of its
6084 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006085 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006086 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006087 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006088 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006089 "DC encloses TU but isn't in enclosing namespace set");
6090 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006091 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006092 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6093 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006094 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006095 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006096 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006097 Diag = diag::ext_template_spec_decl_out_of_scope;
6098 else
6099 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6100 S.Diag(Loc, Diag)
6101 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6102 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006103
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006104 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006105 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006107
Douglas Gregorf47b9112009-02-25 22:02:03 +00006108 return false;
6109}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006110
Richard Smith6056d5e2014-02-09 00:54:43 +00006111static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
6112 if (!E->isInstantiationDependent())
6113 return SourceLocation();
6114 DependencyChecker Checker(Depth);
6115 Checker.TraverseStmt(E);
6116 if (Checker.Match && Checker.MatchLoc.isInvalid())
6117 return E->getSourceRange();
6118 return Checker.MatchLoc;
6119}
6120
6121static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6122 if (!TL.getType()->isDependentType())
6123 return SourceLocation();
6124 DependencyChecker Checker(Depth);
6125 Checker.TraverseTypeLoc(TL);
6126 if (Checker.Match && Checker.MatchLoc.isInvalid())
6127 return TL.getSourceRange();
6128 return Checker.MatchLoc;
6129}
6130
Larisse Voufo39a1e502013-08-06 01:03:05 +00006131/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006132/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006133static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006134 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6135 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006136 for (unsigned I = 0; I != NumArgs; ++I) {
6137 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006138 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006139 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6140 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006141 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006142
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006143 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006144 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006145
Eli Friedmanb826a002012-09-26 02:36:12 +00006146 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006147 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006148
6149 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006150
Douglas Gregor98318c22011-01-03 21:37:45 +00006151 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006152 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6153 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006154
6155 // Strip off any implicit casts we added as part of type checking.
6156 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6157 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006158
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006159 // C++ [temp.class.spec]p8:
6160 // A non-type argument is non-specialized if it is the name of a
6161 // non-type parameter. All other non-type arguments are
6162 // specialized.
6163 //
6164 // Below, we check the two conditions that only apply to
6165 // specialized non-type arguments, so skip any non-specialized
6166 // arguments.
6167 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006168 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006169 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006170
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006171 // C++ [temp.class.spec]p9:
6172 // Within the argument list of a class template partial
6173 // specialization, the following restrictions apply:
6174 // -- A partially specialized non-type argument expression
6175 // shall not involve a template parameter of the partial
6176 // specialization except when the argument expression is a
6177 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006178 SourceRange ParamUseRange =
6179 findTemplateParameter(Param->getDepth(), ArgExpr);
6180 if (ParamUseRange.isValid()) {
6181 if (IsDefaultArgument) {
6182 S.Diag(TemplateNameLoc,
6183 diag::err_dependent_non_type_arg_in_partial_spec);
6184 S.Diag(ParamUseRange.getBegin(),
6185 diag::note_dependent_non_type_default_arg_in_partial_spec)
6186 << ParamUseRange;
6187 } else {
6188 S.Diag(ParamUseRange.getBegin(),
6189 diag::err_dependent_non_type_arg_in_partial_spec)
6190 << ParamUseRange;
6191 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006192 return true;
6193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006194
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006195 // -- The type of a template parameter corresponding to a
6196 // specialized non-type argument shall not be dependent on a
6197 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006198 //
6199 // FIXME: We need to delay this check until instantiation in some cases:
6200 //
6201 // template<template<typename> class X> struct A {
6202 // template<typename T, X<T> N> struct B;
6203 // template<typename T> struct B<T, 0>;
6204 // };
6205 // template<typename> using X = int;
6206 // A<X>::B<int, 0> b;
6207 ParamUseRange = findTemplateParameter(
6208 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6209 if (ParamUseRange.isValid()) {
6210 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6211 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6212 << Param->getType() << ParamUseRange;
6213 S.Diag(Param->getLocation(), diag::note_template_param_here)
6214 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006215 return true;
6216 }
6217 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006218
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006219 return false;
6220}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006221
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006222/// \brief Check the non-type template arguments of a class template
6223/// partial specialization according to C++ [temp.class.spec]p9.
6224///
Richard Smith6056d5e2014-02-09 00:54:43 +00006225/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006226/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006227/// template.
6228/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006229/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006230/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006231///
Richard Smith6056d5e2014-02-09 00:54:43 +00006232/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006233static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006234 Sema &S, SourceLocation TemplateNameLoc,
6235 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006236 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006237 const TemplateArgument *ArgList = TemplateArgs.data();
6238
6239 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6240 NonTypeTemplateParmDecl *Param
6241 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6242 if (!Param)
6243 continue;
6244
Richard Smith6056d5e2014-02-09 00:54:43 +00006245 if (CheckNonTypeTemplatePartialSpecializationArgs(
6246 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006247 return true;
6248 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006249
6250 return false;
6251}
6252
John McCall48871652010-08-21 09:40:31 +00006253DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006254Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6255 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006256 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006257 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006258 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006259 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006260 MultiTemplateParamsArg
6261 TemplateParameterLists,
6262 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006263 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006264
Richard Smith4b55a9c2014-04-17 03:29:33 +00006265 CXXScopeSpec &SS = TemplateId.SS;
6266
Abramo Bagnara60804e12011-03-18 15:16:37 +00006267 // NOTE: KWLoc is the location of the tag keyword. This will instead
6268 // store the location of the outermost template keyword in the declaration.
6269 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006270 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6271 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6272 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6273 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006274
Douglas Gregor67a65642009-02-17 23:15:12 +00006275 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006276 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006277 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006278 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6279
6280 if (!ClassTemplate) {
6281 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006282 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006283 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6284 return true;
6285 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006286
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006287 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006288 bool isPartialSpecialization = false;
6289
Douglas Gregorf47b9112009-02-25 22:02:03 +00006290 // Check the validity of the template headers that introduce this
6291 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006292 // FIXME: We probably shouldn't complain about these headers for
6293 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006294 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006295 TemplateParameterList *TemplateParams =
6296 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006297 KWLoc, TemplateNameLoc, SS, &TemplateId,
6298 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6299 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006300 if (Invalid)
6301 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006302
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006303 if (TemplateParams && TemplateParams->size() > 0) {
6304 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006305
Douglas Gregorec9518b2010-12-21 08:14:57 +00006306 if (TUK == TUK_Friend) {
6307 Diag(KWLoc, diag::err_partial_specialization_friend)
6308 << SourceRange(LAngleLoc, RAngleLoc);
6309 return true;
6310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006311
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006312 // C++ [temp.class.spec]p10:
6313 // The template parameter list of a specialization shall not
6314 // contain default template argument values.
6315 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6316 Decl *Param = TemplateParams->getParam(I);
6317 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6318 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006319 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006320 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006321 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006322 }
6323 } else if (NonTypeTemplateParmDecl *NTTP
6324 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6325 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006326 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006327 diag::err_default_arg_in_partial_spec)
6328 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006329 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006330 }
6331 } else {
6332 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006333 if (TTP->hasDefaultArgument()) {
6334 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006335 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006336 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006337 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006338 }
6339 }
6340 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006341 } else if (TemplateParams) {
6342 if (TUK == TUK_Friend)
6343 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006344 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006345 SourceRange(TemplateParams->getTemplateLoc(),
6346 TemplateParams->getRAngleLoc()))
6347 << SourceRange(LAngleLoc, RAngleLoc);
6348 else
6349 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006350 } else {
6351 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006352 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006353
Douglas Gregor67a65642009-02-17 23:15:12 +00006354 // Check that the specialization uses the same tag kind as the
6355 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006356 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6357 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006358 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006359 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006360 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006361 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006362 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006363 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006364 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006365 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006366 diag::note_previous_use);
6367 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6368 }
6369
Douglas Gregorc40290e2009-03-09 23:48:35 +00006370 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006371 TemplateArgumentListInfo TemplateArgs =
6372 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006373
Douglas Gregor14406932011-01-03 20:35:03 +00006374 // Check for unexpanded parameter packs in any of the template arguments.
6375 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006376 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006377 UPPC_PartialSpecialization))
6378 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006379
Douglas Gregor67a65642009-02-17 23:15:12 +00006380 // Check that the template argument list is well-formed for this
6381 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006382 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006383 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6384 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006385 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006386
Douglas Gregor2373c592009-05-31 09:31:02 +00006387 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006388 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006389 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006390 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006391 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6392 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006393 return true;
6394
Douglas Gregor678d76c2011-07-01 01:22:09 +00006395 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006396 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006397 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00006398 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006399 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6400 << ClassTemplate->getDeclName();
6401 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006402 }
6403 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006404
Craig Topperc3ec1492014-05-26 06:22:03 +00006405 void *InsertPos = nullptr;
6406 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006407
6408 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006409 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006410 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006411 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006412 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006413
Craig Topperc3ec1492014-05-26 06:22:03 +00006414 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006415
Douglas Gregorf47b9112009-02-25 22:02:03 +00006416 // Check whether we can declare a class template specialization in
6417 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006418 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006419 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6420 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006421 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006422 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006423
Douglas Gregor15301382009-07-30 17:40:51 +00006424 // The canonical type
6425 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006426 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006427 // Build the canonical type that describes the converted template
6428 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006429 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6430 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00006431 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006432
6433 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006434 ClassTemplate->getInjectedClassNameSpecialization())) {
6435 // C++ [temp.class.spec]p9b3:
6436 //
6437 // -- The argument list of the specialization shall not be identical
6438 // to the implicit argument list of the primary template.
6439 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006440 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006441 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006442 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6443 ClassTemplate->getIdentifier(),
6444 TemplateNameLoc,
6445 Attr,
6446 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006447 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006448 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006449 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006450 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006451 }
Douglas Gregor15301382009-07-30 17:40:51 +00006452
Douglas Gregor2373c592009-05-31 09:31:02 +00006453 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006454 ClassTemplatePartialSpecializationDecl *PrevPartial
6455 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006456 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006457 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006458 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006459 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006460 TemplateParams,
6461 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006462 Converted,
John McCall6b51f282009-11-23 01:53:49 +00006463 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006464 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006465 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006466 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006467 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006468 Partial->setTemplateParameterListsInfo(
6469 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006470 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006471
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006472 if (!PrevPartial)
6473 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006474 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006475
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006476 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006477 // template specialization, make a note of that.
6478 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6479 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006480
Douglas Gregor91772d12009-06-13 00:26:55 +00006481 // Check that all of the template parameters of the class template
6482 // partial specialization are deducible from the template
6483 // arguments. If not, this class template partial specialization
6484 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006485 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006486 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006487 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006488 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006489
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006490 if (!DeducibleParams.all()) {
6491 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006492 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006493 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006494 << SourceRange(TemplateNameLoc, RAngleLoc);
6495 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6496 if (!DeducibleParams[I]) {
6497 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6498 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006499 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006500 diag::note_partial_spec_unused_parameter)
6501 << Param->getDeclName();
6502 else
Mike Stump11289f42009-09-09 15:08:12 +00006503 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006504 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006505 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006506 }
6507 }
6508 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006509 } else {
6510 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006511 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006512 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006513 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006514 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006515 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006516 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006517 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00006518 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006519 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006520 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006521 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006522 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006523 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006524
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006525 if (!PrevDecl)
6526 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006527
David Majnemer678f50b2015-11-18 19:49:19 +00006528 if (CurContext->isDependentContext()) {
6529 // -fms-extensions permits specialization of nested classes without
6530 // fully specializing the outer class(es).
6531 assert(getLangOpts().MicrosoftExt &&
6532 "Only possible with -fms-extensions!");
6533 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6534 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00006535 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00006536 } else {
6537 CanonType = Context.getTypeDeclType(Specialization);
6538 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006539 }
6540
Douglas Gregor06db9f52009-10-12 20:18:28 +00006541 // C++ [temp.expl.spec]p6:
6542 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006543 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006544 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006545 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006546 // use occurs; no diagnostic is required.
6547 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006548 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006549 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006550 // Is there any previous explicit specialization declaration?
6551 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6552 Okay = true;
6553 break;
6554 }
6555 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006556
Douglas Gregorc854c662010-02-26 06:03:23 +00006557 if (!Okay) {
6558 SourceRange Range(TemplateNameLoc, RAngleLoc);
6559 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6560 << Context.getTypeDeclType(Specialization) << Range;
6561
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006562 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006563 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006564 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006565 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006566 return true;
6567 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006569
Douglas Gregor2208a292009-09-26 20:57:03 +00006570 // If this is not a friend, note that this is an explicit specialization.
6571 if (TUK != TUK_Friend)
6572 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006573
6574 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006575 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006576 RecordDecl *Def = Specialization->getDefinition();
6577 NamedDecl *Hidden = nullptr;
6578 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6579 SkipBody->ShouldSkip = true;
6580 makeMergedDefinitionVisible(Hidden, KWLoc);
6581 // From here on out, treat this as just a redeclaration.
6582 TUK = TUK_Declaration;
6583 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006584 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006585 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006586 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006587 Diag(Def->getLocation(), diag::note_previous_definition);
6588 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006589 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006590 }
6591 }
6592
John McCall659a3372010-12-18 03:30:47 +00006593 if (Attr)
6594 ProcessDeclAttributeList(S, Specialization, Attr);
6595
Richard Smith034b94a2012-08-17 03:20:55 +00006596 // Add alignment attributes if necessary; these attributes are checked when
6597 // the ASTContext lays out the structure.
6598 if (TUK == TUK_Definition) {
6599 AddAlignmentAttributesForRecord(Specialization);
6600 AddMsStructLayoutForRecord(Specialization);
6601 }
6602
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006603 if (ModulePrivateLoc.isValid())
6604 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6605 << (isPartialSpecialization? 1 : 0)
6606 << FixItHint::CreateRemoval(ModulePrivateLoc);
6607
Douglas Gregord56a91e2009-02-26 22:19:44 +00006608 // Build the fully-sugared type for this class template
6609 // specialization as the user wrote in the specialization
6610 // itself. This means that we'll pretty-print the type retrieved
6611 // from the specialization's declaration the way that the user
6612 // actually wrote the specialization, rather than formatting the
6613 // name based on the "canonical" representation used to store the
6614 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006615 TypeSourceInfo *WrittenTy
6616 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6617 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006618 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006619 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006620 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006621 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006622
Douglas Gregor1e249f82009-02-25 22:18:32 +00006623 // C++ [temp.expl.spec]p9:
6624 // A template explicit specialization is in the scope of the
6625 // namespace in which the template was defined.
6626 //
6627 // We actually implement this paragraph where we set the semantic
6628 // context (in the creation of the ClassTemplateSpecializationDecl),
6629 // but we also maintain the lexical context where the actual
6630 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006631 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006632
Douglas Gregor67a65642009-02-17 23:15:12 +00006633 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006634 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006635 Specialization->startDefinition();
6636
Douglas Gregor2208a292009-09-26 20:57:03 +00006637 if (TUK == TUK_Friend) {
6638 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6639 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006640 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006641 /*FIXME:*/KWLoc);
6642 Friend->setAccess(AS_public);
6643 CurContext->addDecl(Friend);
6644 } else {
6645 // Add the specialization into its lexical context, so that it can
6646 // be seen when iterating through the list of declarations in that
6647 // context. However, specializations are not found by name lookup.
6648 CurContext->addDecl(Specialization);
6649 }
John McCall48871652010-08-21 09:40:31 +00006650 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006651}
Douglas Gregor333489b2009-03-27 23:10:48 +00006652
John McCall48871652010-08-21 09:40:31 +00006653Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006654 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006655 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006656 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006657 ActOnDocumentableDecl(NewDecl);
6658 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006659}
6660
John McCall4f7ced62010-02-11 01:33:53 +00006661/// \brief Strips various properties off an implicit instantiation
6662/// that has just been explicitly specialized.
6663static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006664 D->dropAttr<DLLImportAttr>();
6665 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006666
Nico Webere4974382014-12-19 23:52:45 +00006667 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006668 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006669}
6670
Nico Webera8f80b32012-01-09 19:52:25 +00006671/// \brief Compute the diagnostic location for an explicit instantiation
6672// declaration or definition.
6673static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006674 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006675 // Explicit instantiations following a specialization have no effect and
6676 // hence no PointOfInstantiation. In that case, walk decl backwards
6677 // until a valid name loc is found.
6678 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006679 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6680 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006681 PrevDiagLoc = Prev->getLocation();
6682 }
6683 assert(PrevDiagLoc.isValid() &&
6684 "Explicit instantiation without point of instantiation?");
6685 return PrevDiagLoc;
6686}
6687
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006688/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006689/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006690/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006691/// new specialization/instantiation will have any effect.
6692///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006693/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006694/// instantiation.
6695///
6696/// \param NewTSK the kind of the new explicit specialization or instantiation.
6697///
6698/// \param PrevDecl the previous declaration of the entity.
6699///
6700/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6701///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006702/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006703/// declaration was instantiated (either implicitly or explicitly).
6704///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006705/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006706/// specialization or instantiation has no effect and should be ignored.
6707///
6708/// \returns true if there was an error that should prevent the introduction of
6709/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006710bool
6711Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6712 TemplateSpecializationKind NewTSK,
6713 NamedDecl *PrevDecl,
6714 TemplateSpecializationKind PrevTSK,
6715 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006716 bool &HasNoEffect) {
6717 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006718
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006719 switch (NewTSK) {
6720 case TSK_Undeclared:
6721 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006722 assert(
6723 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6724 "previous declaration must be implicit!");
6725 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006726
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006727 case TSK_ExplicitSpecialization:
6728 switch (PrevTSK) {
6729 case TSK_Undeclared:
6730 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006731 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006732 // explicitly specialized or has merely been mentioned without any
6733 // instantiation.
6734 return false;
6735
6736 case TSK_ImplicitInstantiation:
6737 if (PrevPointOfInstantiation.isInvalid()) {
6738 // The declaration itself has not actually been instantiated, so it is
6739 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006740 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006741 return false;
6742 }
6743 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006744
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006745 case TSK_ExplicitInstantiationDeclaration:
6746 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006747 assert((PrevTSK == TSK_ImplicitInstantiation ||
6748 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006749 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006750
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006751 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006752 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006753 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006754 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006755 // implicit instantiation to take place, in every translation unit in
6756 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006757 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006758 // Is there any previous explicit specialization declaration?
6759 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6760 return false;
6761 }
6762
Douglas Gregor1d957a32009-10-27 18:42:08 +00006763 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006764 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006765 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006766 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006767
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006768 return true;
6769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006771 case TSK_ExplicitInstantiationDeclaration:
6772 switch (PrevTSK) {
6773 case TSK_ExplicitInstantiationDeclaration:
6774 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006775 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006776 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006777
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006778 case TSK_Undeclared:
6779 case TSK_ImplicitInstantiation:
6780 // We're explicitly instantiating something that may have already been
6781 // implicitly instantiated; that's fine.
6782 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006783
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006784 case TSK_ExplicitSpecialization:
6785 // C++0x [temp.explicit]p4:
6786 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006787 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006788 // specialization for that template, the explicit instantiation has no
6789 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006790 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006791 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006792
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006793 case TSK_ExplicitInstantiationDefinition:
6794 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006795 // If an entity is the subject of both an explicit instantiation
6796 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006797 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006798 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006799 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006800
6801 // Explicit instantiations following a specialization have no effect and
6802 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6803 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006804 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6805 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006806 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006807 return false;
6808 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006809
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006810 case TSK_ExplicitInstantiationDefinition:
6811 switch (PrevTSK) {
6812 case TSK_Undeclared:
6813 case TSK_ImplicitInstantiation:
6814 // We're explicitly instantiating something that may have already been
6815 // implicitly instantiated; that's fine.
6816 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006817
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006818 case TSK_ExplicitSpecialization:
6819 // C++ DR 259, C++0x [temp.explicit]p4:
6820 // For a given set of template parameters, if an explicit
6821 // instantiation of a template appears after a declaration of
6822 // an explicit specialization for that template, the explicit
6823 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00006824 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006825 << PrevDecl;
6826 Diag(PrevDecl->getLocation(),
6827 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006828 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006829 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006830
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006831 case TSK_ExplicitInstantiationDeclaration:
6832 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006833 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006834
6835 // C++0x [temp.explicit]p4:
6836 // For a given set of template parameters, if an explicit instantiation
6837 // of a template appears after a declaration of an explicit
6838 // specialization for that template, the explicit instantiation has no
6839 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006840 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006841 // Is there any previous explicit specialization declaration?
6842 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6843 HasNoEffect = true;
6844 break;
6845 }
6846 }
6847
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006848 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006849
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006850 case TSK_ExplicitInstantiationDefinition:
6851 // C++0x [temp.spec]p5:
6852 // For a given template and a given set of template-arguments,
6853 // - an explicit instantiation definition shall appear at most once
6854 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006855
6856 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6857 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006858 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006859 : diag::err_explicit_instantiation_duplicate)
6860 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006861 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006862 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006863 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006864 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006865 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006867
David Blaikie83d382b2011-09-23 05:06:16 +00006868 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006869}
6870
John McCallb9c78482010-04-08 09:05:18 +00006871/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006872/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006873///
James Dennettf14a6e52012-06-15 22:23:43 +00006874/// The only possible way to get a dependent function template specialization
6875/// is with a friend declaration, like so:
6876///
6877/// \code
6878/// template \<class T> void foo(T);
6879/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006880/// friend void foo<>(T);
6881/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006882/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006883///
6884/// There really isn't any useful analysis we can do here, so we
6885/// just store the information.
6886bool
6887Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6888 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6889 LookupResult &Previous) {
6890 // Remove anything from Previous that isn't a function template in
6891 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006892 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006893 LookupResult::Filter F = Previous.makeFilter();
6894 while (F.hasNext()) {
6895 NamedDecl *D = F.next()->getUnderlyingDecl();
6896 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006897 !FDLookupContext->InEnclosingNamespaceSetOf(
6898 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006899 F.erase();
6900 }
6901 F.done();
6902
6903 // Should this be diagnosed here?
6904 if (Previous.empty()) return true;
6905
6906 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6907 ExplicitTemplateArgs);
6908 return false;
6909}
6910
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006911/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006912/// specialization.
6913///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006914/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006915/// explicit function template specialization. On successful completion,
6916/// the function declaration \p FD will become a function template
6917/// specialization.
6918///
6919/// \param FD the function declaration, which will be updated to become a
6920/// function template specialization.
6921///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006922/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6923/// if any. Note that this may be valid info even when 0 arguments are
6924/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6925/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006926///
Francois Pichet3a44e432011-07-08 06:21:47 +00006927/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006928/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006929bool Sema::CheckFunctionTemplateSpecialization(
6930 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6931 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006932 // The set of function template specializations that could match this
6933 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006934 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006935 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6936 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006937
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006938 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6939 ConvertedTemplateArgs;
6940
Sebastian Redl50c68252010-08-31 00:36:30 +00006941 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006942 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6943 I != E; ++I) {
6944 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6945 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006946 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006947 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006948 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6949 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006950 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006951
Richard Smith574f4f62013-01-14 05:37:29 +00006952 // When matching a constexpr member function template specialization
6953 // against the primary template, we don't yet know whether the
6954 // specialization has an implicit 'const' (because we don't know whether
6955 // it will be a static member function until we know which template it
6956 // specializes), so adjust it now assuming it specializes this template.
6957 QualType FT = FD->getType();
6958 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006959 CXXMethodDecl *OldMD =
6960 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006961 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006962 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006963 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6964 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006965 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006966 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006967 }
6968 }
6969
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006970 TemplateArgumentListInfo Args;
6971 if (ExplicitTemplateArgs)
6972 Args = *ExplicitTemplateArgs;
6973
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006974 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006975 // A trailing template-argument can be left unspecified in the
6976 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006977 // provided it can be deduced from the function argument type.
6978 // Perform template argument deduction to determine whether we may be
6979 // specializing this template.
6980 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006981 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006982 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006983 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6984 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00006985 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
6986 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006987 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006988 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00006989 FailedCandidates.addCandidate().set(
6990 I.getPair(), FunTmpl->getTemplatedDecl(),
6991 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006992 (void)TDK;
6993 continue;
6994 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006995
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006996 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006997 if (ExplicitTemplateArgs)
6998 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00006999 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007000 }
7001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007002
Douglas Gregor5de279c2009-09-26 03:41:46 +00007003 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007004 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007005 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007006 FD->getLocation(),
7007 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7008 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00007009 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007010 PDiag(diag::note_function_template_spec_matched));
7011
John McCall58cc69d2010-01-27 01:50:18 +00007012 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007013 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007014
7015 // Ignore access information; it doesn't figure into redeclaration checking.
7016 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007017
Nathan Wilson83839122016-04-09 02:55:27 +00007018 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7019 // an explicit specialization (14.8.3) [...] of a concept definition.
7020 if (Specialization->getPrimaryTemplate()->isConcept()) {
7021 Diag(FD->getLocation(), diag::err_concept_specialized)
7022 << 0 /*function*/ << 1 /*explicitly specialized*/;
7023 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7024 return true;
7025 }
7026
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007027 FunctionTemplateSpecializationInfo *SpecInfo
7028 = Specialization->getTemplateSpecializationInfo();
7029 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007030
7031 // Note: do not overwrite location info if previous template
7032 // specialization kind was explicit.
7033 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00007034 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00007035 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00007036 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7037 // function can differ from the template declaration with respect to
7038 // the constexpr specifier.
7039 Specialization->setConstexpr(FD->isConstexpr());
7040 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007041
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007042 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00007043 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00007044
7045 // If this is a friend declaration, then we're not really declaring
7046 // an explicit specialization.
7047 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007048
Douglas Gregor54888652009-10-07 00:13:32 +00007049 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00007050 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007051 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00007052 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007053 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007054 false))
Douglas Gregor54888652009-10-07 00:13:32 +00007055 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007056
7057 // C++ [temp.expl.spec]p6:
7058 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007059 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007060 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007061 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007062 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007063 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007064 if (!isFriend &&
7065 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007066 TSK_ExplicitSpecialization,
7067 Specialization,
7068 SpecInfo->getTemplateSpecializationKind(),
7069 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007070 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007071 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007072
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007073 // Mark the prior declaration as an explicit specialization, so that later
7074 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007075 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007076 // Since explicit specializations do not inherit '=delete' from their
7077 // primary function template - check if the 'specialization' that was
7078 // implicitly generated (during template argument deduction for partial
7079 // ordering) from the most specialized of all the function templates that
7080 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7081 // first check that it was implicitly generated during template argument
7082 // deduction by making sure it wasn't referenced, and then reset the deleted
7083 // flag to not-deleted, so that we can inherit that information from 'FD'.
7084 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7085 !Specialization->getCanonicalDecl()->isReferenced()) {
7086 assert(
7087 Specialization->getCanonicalDecl() == Specialization &&
7088 "This must be the only existing declaration of this specialization");
7089 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007090 }
John McCall816d75b2010-03-24 07:46:06 +00007091 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007092 MarkUnusedFileScopedDecl(Specialization);
7093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007094
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007095 // Turn the given function declaration into a function template
7096 // specialization, with the template arguments from the previous
7097 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007098 // Take copies of (semantic and syntactic) template argument lists.
7099 const TemplateArgumentList* TemplArgs = new (Context)
7100 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007101 FD->setFunctionTemplateSpecialization(
7102 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7103 SpecInfo->getTemplateSpecializationKind(),
7104 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007105
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007106 // The "previous declaration" for this function template specialization is
7107 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007108 Previous.clear();
7109 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007110 return false;
7111}
7112
Douglas Gregor86d142a2009-10-08 07:24:58 +00007113/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007114/// specialization.
7115///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007116/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007117/// explicit member function specialization. On successful completion,
7118/// the function declaration \p FD will become a member function
7119/// specialization.
7120///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007121/// \param Member the member declaration, which will be updated to become a
7122/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007123///
John McCall1f82f242009-11-18 22:49:29 +00007124/// \param Previous the set of declarations, one of which may be specialized
7125/// by this function specialization; the set will be modified to contain the
7126/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007127bool
John McCall1f82f242009-11-18 22:49:29 +00007128Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007129 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007130
Douglas Gregor86d142a2009-10-08 07:24:58 +00007131 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007132 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007133 NamedDecl *Instantiation = nullptr;
7134 NamedDecl *InstantiatedFrom = nullptr;
7135 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007136
John McCall1f82f242009-11-18 22:49:29 +00007137 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007138 // Nowhere to look anyway.
7139 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007140 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7141 I != E; ++I) {
7142 NamedDecl *D = (*I)->getUnderlyingDecl();
7143 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007144 QualType Adjusted = Function->getType();
7145 if (!hasExplicitCallingConv(Adjusted))
7146 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7147 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007148 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007149 Instantiation = Method;
7150 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007151 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007152 break;
7153 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007154 }
7155 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007156 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007157 VarDecl *PrevVar;
7158 if (Previous.isSingleResult() &&
7159 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007160 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007161 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007162 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007163 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007164 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007165 }
7166 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007167 CXXRecordDecl *PrevRecord;
7168 if (Previous.isSingleResult() &&
7169 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007170 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007171 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007172 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007173 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007174 }
Richard Smith7d137e32012-03-23 03:33:32 +00007175 } else if (isa<EnumDecl>(Member)) {
7176 EnumDecl *PrevEnum;
7177 if (Previous.isSingleResult() &&
7178 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007179 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007180 Instantiation = PrevEnum;
7181 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7182 MSInfo = PrevEnum->getMemberSpecializationInfo();
7183 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007185
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007186 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007187 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007188 // specializations are always out-of-line, the caller will complain about
7189 // this mismatch later.
7190 return false;
7191 }
John McCalle820e5e2010-04-13 20:37:33 +00007192
7193 // If this is a friend, just bail out here before we start turning
7194 // things into explicit specializations.
7195 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7196 // Preserve instantiation information.
7197 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7198 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7199 cast<CXXMethodDecl>(InstantiatedFrom),
7200 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7201 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7202 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7203 cast<CXXRecordDecl>(InstantiatedFrom),
7204 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7205 }
7206
7207 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007208 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007209 return false;
7210 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007211
Douglas Gregor86d142a2009-10-08 07:24:58 +00007212 // Make sure that this is a specialization of a member.
7213 if (!InstantiatedFrom) {
7214 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7215 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007216 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7217 return true;
7218 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007219
Douglas Gregor06db9f52009-10-12 20:18:28 +00007220 // C++ [temp.expl.spec]p6:
7221 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007222 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007223 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007224 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007225 // use occurs; no diagnostic is required.
7226 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007227
Abramo Bagnara8075c852010-06-12 07:44:57 +00007228 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007229 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7230 TSK_ExplicitSpecialization,
7231 Instantiation,
7232 MSInfo->getTemplateSpecializationKind(),
7233 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007234 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007235 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007236
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007237 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007238 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007239 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007240 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007241 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007242 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007243
Douglas Gregor86d142a2009-10-08 07:24:58 +00007244 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007245 // the original declaration to note that it is an explicit specialization
7246 // (if it was previously an implicit instantiation). This latter step
7247 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007248 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007249 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7250 if (InstantiationFunction->getTemplateSpecializationKind() ==
7251 TSK_ImplicitInstantiation) {
7252 InstantiationFunction->setTemplateSpecializationKind(
7253 TSK_ExplicitSpecialization);
7254 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007255 // Explicit specializations of member functions of class templates do not
7256 // inherit '=delete' from the member function they are specializing.
7257 if (InstantiationFunction->isDeleted()) {
7258 assert(InstantiationFunction->getCanonicalDecl() ==
7259 InstantiationFunction);
7260 InstantiationFunction->setDeletedAsWritten(false);
7261 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007263
Douglas Gregor86d142a2009-10-08 07:24:58 +00007264 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7265 cast<CXXMethodDecl>(InstantiatedFrom),
7266 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007267 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007268 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007269 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7270 if (InstantiationVar->getTemplateSpecializationKind() ==
7271 TSK_ImplicitInstantiation) {
7272 InstantiationVar->setTemplateSpecializationKind(
7273 TSK_ExplicitSpecialization);
7274 InstantiationVar->setLocation(Member->getLocation());
7275 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007276
Larisse Voufo39a1e502013-08-06 01:03:05 +00007277 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7278 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007279 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007280 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007281 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7282 if (InstantiationClass->getTemplateSpecializationKind() ==
7283 TSK_ImplicitInstantiation) {
7284 InstantiationClass->setTemplateSpecializationKind(
7285 TSK_ExplicitSpecialization);
7286 InstantiationClass->setLocation(Member->getLocation());
7287 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007288
Douglas Gregor86d142a2009-10-08 07:24:58 +00007289 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007290 cast<CXXRecordDecl>(InstantiatedFrom),
7291 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007292 } else {
7293 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7294 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7295 if (InstantiationEnum->getTemplateSpecializationKind() ==
7296 TSK_ImplicitInstantiation) {
7297 InstantiationEnum->setTemplateSpecializationKind(
7298 TSK_ExplicitSpecialization);
7299 InstantiationEnum->setLocation(Member->getLocation());
7300 }
7301
7302 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7303 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007304 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007305
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007306 // Save the caller the trouble of having to figure out which declaration
7307 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007308 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007309 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007310 return false;
7311}
7312
Douglas Gregore47f5a72009-10-14 23:41:34 +00007313/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007314///
7315/// \returns true if a serious error occurs, false otherwise.
7316static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007317 SourceLocation InstLoc,
7318 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007319 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7320 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007321
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007322 if (CurContext->isRecord()) {
7323 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7324 << D;
7325 return true;
7326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007327
Richard Smith050d2612011-10-18 02:28:33 +00007328 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007329 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007330 // template. If the name declared in the explicit instantiation is an
7331 // unqualified name, the explicit instantiation shall appear in the
7332 // namespace where its template is declared or, if that namespace is inline
7333 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007334 //
7335 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007336 if (WasQualifiedName) {
7337 if (CurContext->Encloses(OrigContext))
7338 return false;
7339 } else {
7340 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7341 return false;
7342 }
7343
7344 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7345 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007346 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007347 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007348 diag::err_explicit_instantiation_out_of_scope :
7349 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007350 << D << NS;
7351 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007352 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007353 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007354 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7355 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7356 << D << NS;
7357 } else
7358 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007359 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007360 diag::err_explicit_instantiation_must_be_global :
7361 diag::warn_explicit_instantiation_must_be_global_0x)
7362 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007363 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007364 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007365}
7366
7367/// \brief Determine whether the given scope specifier has a template-id in it.
7368static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7369 if (!SS.isSet())
7370 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007371
Richard Smith050d2612011-10-18 02:28:33 +00007372 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007373 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007374 // or a static data member of a class template specialization, the name of
7375 // the class template specialization in the qualified-id for the member
7376 // name shall be a simple-template-id.
7377 //
7378 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007379 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7380 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007381 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007382 if (isa<TemplateSpecializationType>(T))
7383 return true;
7384
7385 return false;
7386}
7387
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007388// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007389DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007390Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007391 SourceLocation ExternLoc,
7392 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007393 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007394 SourceLocation KWLoc,
7395 const CXXScopeSpec &SS,
7396 TemplateTy TemplateD,
7397 SourceLocation TemplateNameLoc,
7398 SourceLocation LAngleLoc,
7399 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007400 SourceLocation RAngleLoc,
7401 AttributeList *Attr) {
7402 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007403 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007404 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007405 // Check that the specialization uses the same tag kind as the
7406 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007407 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7408 assert(Kind != TTK_Enum &&
7409 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007410
Richard Trieu265c3442016-04-05 21:13:54 +00007411 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7412
7413 if (!ClassTemplate) {
7414 unsigned ErrorKind = 0;
7415 if (isa<TypeAliasTemplateDecl>(TD)) {
7416 ErrorKind = 4;
7417 } else if (isa<TemplateTemplateParmDecl>(TD)) {
7418 ErrorKind = 5;
7419 }
7420
7421 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << ErrorKind;
7422 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00007423 return true;
7424 }
7425
Douglas Gregord9034f02009-05-14 16:41:31 +00007426 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007427 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007428 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007429 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007430 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007431 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007432 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007433 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007434 diag::note_previous_use);
7435 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7436 }
7437
Douglas Gregore47f5a72009-10-14 23:41:34 +00007438 // C++0x [temp.explicit]p2:
7439 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007440 // definition and an explicit instantiation declaration. An explicit
7441 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007442 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7443 ? TSK_ExplicitInstantiationDefinition
7444 : TSK_ExplicitInstantiationDeclaration;
7445
7446 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7447 // Check for dllexport class template instantiation declarations.
7448 for (AttributeList *A = Attr; A; A = A->getNext()) {
7449 if (A->getKind() == AttributeList::AT_DLLExport) {
7450 Diag(ExternLoc,
7451 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7452 Diag(A->getLoc(), diag::note_attribute);
7453 break;
7454 }
7455 }
7456
7457 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7458 Diag(ExternLoc,
7459 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7460 Diag(A->getLocation(), diag::note_attribute);
7461 }
7462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007463
Hans Wennborga86a83b2016-05-26 19:42:56 +00007464 // In MSVC mode, dllimported explicit instantiation definitions are treated as
7465 // instantiation declarations for most purposes.
7466 bool DLLImportExplicitInstantiationDef = false;
7467 if (TSK == TSK_ExplicitInstantiationDefinition &&
7468 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7469 // Check for dllimport class template instantiation definitions.
7470 bool DLLImport =
7471 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7472 for (AttributeList *A = Attr; A; A = A->getNext()) {
7473 if (A->getKind() == AttributeList::AT_DLLImport)
7474 DLLImport = true;
7475 if (A->getKind() == AttributeList::AT_DLLExport) {
7476 // dllexport trumps dllimport here.
7477 DLLImport = false;
7478 break;
7479 }
7480 }
7481 if (DLLImport) {
7482 TSK = TSK_ExplicitInstantiationDeclaration;
7483 DLLImportExplicitInstantiationDef = true;
7484 }
7485 }
7486
Douglas Gregora1f49972009-05-13 00:25:59 +00007487 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007488 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007489 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007490
7491 // Check that the template argument list is well-formed for this
7492 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007493 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007494 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7495 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007496 return true;
7497
Douglas Gregora1f49972009-05-13 00:25:59 +00007498 // Find the class template specialization declaration that
7499 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007500 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007501 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007502 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007503
Abramo Bagnara8075c852010-06-12 07:44:57 +00007504 TemplateSpecializationKind PrevDecl_TSK
7505 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7506
Douglas Gregor54888652009-10-07 00:13:32 +00007507 // C++0x [temp.explicit]p2:
7508 // [...] An explicit instantiation shall appear in an enclosing
7509 // namespace of its template. [...]
7510 //
7511 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007512 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7513 SS.isSet()))
7514 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007515
Craig Topperc3ec1492014-05-26 06:22:03 +00007516 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007517
Abramo Bagnara8075c852010-06-12 07:44:57 +00007518 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007519 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007520 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007521 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007522 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007523 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007524 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007525
Abramo Bagnara8075c852010-06-12 07:44:57 +00007526 // Even though HasNoEffect == true means that this explicit instantiation
7527 // has no effect on semantics, we go on to put its syntax in the AST.
7528
7529 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7530 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007531 // Since the only prior class template specialization with these
7532 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007533 // declaration node as our own, updating the source location
7534 // for the template name to reflect our new declaration.
7535 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007536 Specialization = PrevDecl;
7537 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007538 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007539 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00007540
7541 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7542 DLLImportExplicitInstantiationDef) {
7543 // The new specialization might add a dllimport attribute.
7544 HasNoEffect = false;
7545 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007546 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007547
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007548 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007549 // Create a new class template specialization declaration node for
7550 // this explicit specialization.
7551 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007552 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007553 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007554 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007555 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007556 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007557 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007558 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007559
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007560 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007561 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007562 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007563 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007564 }
7565
7566 // Build the fully-sugared type for this explicit instantiation as
7567 // the user wrote in the explicit instantiation itself. This means
7568 // that we'll pretty-print the type retrieved from the
7569 // specialization's declaration the way that the user actually wrote
7570 // the explicit instantiation, rather than formatting the name based
7571 // on the "canonical" representation used to store the template
7572 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007573 TypeSourceInfo *WrittenTy
7574 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7575 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007576 Context.getTypeDeclType(Specialization));
7577 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007578
Abramo Bagnara8075c852010-06-12 07:44:57 +00007579 // Set source locations for keywords.
7580 Specialization->setExternLoc(ExternLoc);
7581 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00007582 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007583
Rafael Espindola0b062072012-01-03 06:04:21 +00007584 if (Attr)
7585 ProcessDeclAttributeList(S, Specialization, Attr);
7586
Abramo Bagnara8075c852010-06-12 07:44:57 +00007587 // Add the explicit instantiation into its lexical context. However,
7588 // since explicit instantiations are never found by name lookup, we
7589 // just put it into the declaration context directly.
7590 Specialization->setLexicalDeclContext(CurContext);
7591 CurContext->addDecl(Specialization);
7592
7593 // Syntax is now OK, so return if it has no other effect on semantics.
7594 if (HasNoEffect) {
7595 // Set the template specialization kind.
7596 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007597 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007598 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007599
7600 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007601 // A definition of a class template or class member template
7602 // shall be in scope at the point of the explicit instantiation of
7603 // the class template or class member template.
7604 //
7605 // This check comes when we actually try to perform the
7606 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007607 ClassTemplateSpecializationDecl *Def
7608 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007609 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007610 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007611 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007612 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007613 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007614 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7615 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007616
Douglas Gregor1d957a32009-10-27 18:42:08 +00007617 // Instantiate the members of this class template specialization.
7618 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007619 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007620 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007621 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007622 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7623 // TSK_ExplicitInstantiationDefinition
7624 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00007625 (TSK == TSK_ExplicitInstantiationDefinition ||
7626 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007627 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007628 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007629
Hans Wennborgc0875502015-06-09 00:39:05 +00007630 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7631 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7632 // In the MS ABI, an explicit instantiation definition can add a dll
7633 // attribute to a template with a previous instantiation declaration.
7634 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007635 auto *A = cast<InheritableAttr>(
7636 getDLLAttr(Specialization)->clone(getASTContext()));
7637 A->setInherited(true);
7638 Def->addAttr(A);
Reid Kleckner5b640342016-02-26 19:51:02 +00007639
7640 // We reject explicit instantiations in class scope, so there should
7641 // never be any delayed exported classes to worry about.
7642 assert(DelayedDllExportClasses.empty() &&
7643 "delayed exports present at explicit instantiation");
Hans Wennborg17f9b442015-05-27 00:06:45 +00007644 checkClassLevelDLLAttribute(Def);
Reid Kleckner5b640342016-02-26 19:51:02 +00007645 referenceDLLExportedClassMethods();
Hans Wennborgfce87ca2015-06-09 00:39:09 +00007646
7647 // Propagate attribute to base class templates.
7648 for (auto &B : Def->bases()) {
7649 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7650 B.getType()->getAsCXXRecordDecl()))
7651 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7652 }
Hans Wennborg17f9b442015-05-27 00:06:45 +00007653 }
7654 }
7655
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007656 // Set the template specialization kind. Make sure it is set before
7657 // instantiating the members which will trigger ASTConsumer callbacks.
7658 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007659 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007660 } else {
7661
7662 // Set the template specialization kind.
7663 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007664 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007665
John McCall48871652010-08-21 09:40:31 +00007666 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007667}
7668
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007669// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007670DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007671Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007672 SourceLocation ExternLoc,
7673 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007674 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007675 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007676 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007677 IdentifierInfo *Name,
7678 SourceLocation NameLoc,
7679 AttributeList *Attr) {
7680
Douglas Gregord6ab8742009-05-28 23:31:59 +00007681 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007682 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007683 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007684 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007685 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007686 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007687 SourceLocation(), false, TypeResult(),
7688 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007689 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7690
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007691 if (!TagD)
7692 return true;
7693
John McCall48871652010-08-21 09:40:31 +00007694 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007695 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007696
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007697 if (Tag->isInvalidDecl())
7698 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007699
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007700 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7701 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7702 if (!Pattern) {
7703 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7704 << Context.getTypeDeclType(Record);
7705 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7706 return true;
7707 }
7708
Douglas Gregore47f5a72009-10-14 23:41:34 +00007709 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007710 // If the explicit instantiation is for a class or member class, the
7711 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007712 // simple-template-id.
7713 //
7714 // C++98 has the same restriction, just worded differently.
7715 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007716 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007717 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007718
Douglas Gregore47f5a72009-10-14 23:41:34 +00007719 // C++0x [temp.explicit]p2:
7720 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007721 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007722 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007723 TemplateSpecializationKind TSK
7724 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7725 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007726
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007727 // C++0x [temp.explicit]p2:
7728 // [...] An explicit instantiation shall appear in an enclosing
7729 // namespace of its template. [...]
7730 //
7731 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007732 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007733
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007734 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007735 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007736 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007737 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007738 PrevDecl = Record;
7739 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007740 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007741 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007742 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007743 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007744 PrevDecl,
7745 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007746 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007747 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007748 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007749 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007750 return TagD;
7751 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007752
Douglas Gregor12e49d32009-10-15 22:53:21 +00007753 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007754 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007755 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007756 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007757 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007758 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007759 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007760 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007761 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007762 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7763 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007764 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7765 << Pattern;
7766 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007767 } else {
7768 if (InstantiateClass(NameLoc, Record, Def,
7769 getTemplateInstantiationArgs(Record),
7770 TSK))
7771 return true;
7772
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007773 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007774 if (!RecordDef)
7775 return true;
7776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007777 }
7778
Douglas Gregor1d957a32009-10-27 18:42:08 +00007779 // Instantiate all of the members of the class.
7780 InstantiateClassMembers(NameLoc, RecordDef,
7781 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007782
Douglas Gregor88d292c2010-05-13 16:44:06 +00007783 if (TSK == TSK_ExplicitInstantiationDefinition)
7784 MarkVTableUsed(NameLoc, RecordDef, true);
7785
Mike Stump87c57ac2009-05-16 07:39:55 +00007786 // FIXME: We don't have any representation for explicit instantiations of
7787 // member classes. Such a representation is not needed for compilation, but it
7788 // should be available for clients that want to see all of the declarations in
7789 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007790 return TagD;
7791}
7792
John McCallfaf5fb42010-08-26 23:41:50 +00007793DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7794 SourceLocation ExternLoc,
7795 SourceLocation TemplateLoc,
7796 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007797 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007798 // TODO: check if/when DNInfo should replace Name.
7799 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7800 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007801 if (!Name) {
7802 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007803 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007804 diag::err_explicit_instantiation_requires_name)
7805 << D.getDeclSpec().getSourceRange()
7806 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007807
Douglas Gregor450f00842009-09-25 18:43:00 +00007808 return true;
7809 }
7810
7811 // The scope passed in may not be a decl scope. Zip up the scope tree until
7812 // we find one that is.
7813 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7814 (S->getFlags() & Scope::TemplateParamScope) != 0)
7815 S = S->getParent();
7816
7817 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007818 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7819 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007820 if (R.isNull())
7821 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007822
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007823 // C++ [dcl.stc]p1:
7824 // A storage-class-specifier shall not be specified in [...] an explicit
7825 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007826 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007827 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7828 << Name;
7829 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007830 } else if (D.getDeclSpec().getStorageClassSpec()
7831 != DeclSpec::SCS_unspecified) {
7832 // Complain about then remove the storage class specifier.
7833 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7834 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7835
7836 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007837 }
7838
Douglas Gregor3c74d412009-10-14 20:14:33 +00007839 // C++0x [temp.explicit]p1:
7840 // [...] An explicit instantiation of a function template shall not use the
7841 // inline or constexpr specifiers.
7842 // Presumably, this also applies to member functions of class templates as
7843 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007844 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007845 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007846 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007847 diag::err_explicit_instantiation_inline :
7848 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007849 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007850 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007851 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7852 // not already specified.
7853 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7854 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007855
Nathan Wilsonde498452016-02-08 05:34:00 +00007856 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7857 // applied only to the definition of a function template or variable template,
7858 // declared in namespace scope.
7859 if (D.getDeclSpec().isConceptSpecified()) {
7860 Diag(D.getDeclSpec().getConceptSpecLoc(),
7861 diag::err_concept_specified_specialization) << 0;
7862 return true;
7863 }
7864
Douglas Gregore47f5a72009-10-14 23:41:34 +00007865 // C++0x [temp.explicit]p2:
7866 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007867 // definition and an explicit instantiation declaration. An explicit
7868 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007869 TemplateSpecializationKind TSK
7870 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7871 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007872
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007873 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007874 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007875
7876 if (!R->isFunctionType()) {
7877 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007878 // A [...] static data member of a class template can be explicitly
7879 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007880 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007881 // C++1y [temp.explicit]p1:
7882 // A [...] variable [...] template specialization can be explicitly
7883 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007884 if (Previous.isAmbiguous())
7885 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007886
John McCall67c00872009-12-02 08:25:40 +00007887 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007888 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007889
Larisse Voufo39a1e502013-08-06 01:03:05 +00007890 if (!PrevTemplate) {
7891 if (!Prev || !Prev->isStaticDataMember()) {
7892 // We expect to see a data data member here.
7893 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7894 << Name;
7895 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7896 P != PEnd; ++P)
7897 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7898 return true;
7899 }
7900
7901 if (!Prev->getInstantiatedFromStaticDataMember()) {
7902 // FIXME: Check for explicit specialization?
7903 Diag(D.getIdentifierLoc(),
7904 diag::err_explicit_instantiation_data_member_not_instantiated)
7905 << Prev;
7906 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7907 // FIXME: Can we provide a note showing where this was declared?
7908 return true;
7909 }
7910 } else {
7911 // Explicitly instantiate a variable template.
7912
7913 // C++1y [dcl.spec.auto]p6:
7914 // ... A program that uses auto or decltype(auto) in a context not
7915 // explicitly allowed in this section is ill-formed.
7916 //
7917 // This includes auto-typed variable template instantiations.
7918 if (R->isUndeducedType()) {
7919 Diag(T->getTypeLoc().getLocStart(),
7920 diag::err_auto_not_allowed_var_inst);
7921 return true;
7922 }
7923
Richard Smithef985ac2013-09-18 02:10:12 +00007924 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7925 // C++1y [temp.explicit]p3:
7926 // If the explicit instantiation is for a variable, the unqualified-id
7927 // in the declaration shall be a template-id.
7928 Diag(D.getIdentifierLoc(),
7929 diag::err_explicit_instantiation_without_template_id)
7930 << PrevTemplate;
7931 Diag(PrevTemplate->getLocation(),
7932 diag::note_explicit_instantiation_here);
7933 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007934 }
7935
Nathan Wilson83839122016-04-09 02:55:27 +00007936 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
7937 // explicit instantiation (14.8.2) [...] of a concept definition.
7938 if (PrevTemplate->isConcept()) {
7939 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
7940 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
7941 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
7942 return true;
7943 }
7944
Richard Smithef985ac2013-09-18 02:10:12 +00007945 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007946 TemplateArgumentListInfo TemplateArgs =
7947 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007948
Larisse Voufo39a1e502013-08-06 01:03:05 +00007949 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7950 D.getIdentifierLoc(), TemplateArgs);
7951 if (Res.isInvalid())
7952 return true;
7953
7954 // Ignore access control bits, we don't need them for redeclaration
7955 // checking.
7956 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007958
Douglas Gregore47f5a72009-10-14 23:41:34 +00007959 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007960 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007961 // or a static data member of a class template specialization, the name of
7962 // the class template specialization in the qualified-id for the member
7963 // name shall be a simple-template-id.
7964 //
7965 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007966 //
Richard Smith5977d872013-09-18 21:55:14 +00007967 // This does not apply to variable template specializations, where the
7968 // template-id is in the unqualified-id instead.
7969 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007970 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007971 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007972 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007973
Douglas Gregore47f5a72009-10-14 23:41:34 +00007974 // Check the scope of this explicit instantiation.
7975 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007976
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007977 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007978 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7979 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007980 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007981 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007982 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007983 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007984
Larisse Voufo39a1e502013-08-06 01:03:05 +00007985 if (!HasNoEffect) {
7986 // Instantiate static data member or variable template.
7987
7988 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7989 if (PrevTemplate) {
7990 // Merge attributes.
7991 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7992 ProcessDeclAttributeList(S, Prev, Attr);
7993 }
7994 if (TSK == TSK_ExplicitInstantiationDefinition)
7995 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7996 }
7997
7998 // Check the new variable specialization against the parsed input.
7999 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8000 Diag(T->getTypeLoc().getLocStart(),
8001 diag::err_invalid_var_template_spec_type)
8002 << 0 << PrevTemplate << R << Prev->getType();
8003 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8004 << 2 << PrevTemplate->getDeclName();
8005 return true;
8006 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008007
Douglas Gregor450f00842009-09-25 18:43:00 +00008008 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00008009 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008010 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008011
8012 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00008013 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00008014 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00008015 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00008016 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00008017 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00008018 HasExplicitTemplateArgs = true;
8019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008020
Douglas Gregor450f00842009-09-25 18:43:00 +00008021 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008022 // A [...] function [...] can be explicitly instantiated from its template.
8023 // A member function [...] of a class template can be explicitly
8024 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008025 // template.
John McCall58cc69d2010-01-27 01:50:18 +00008026 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00008027 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00008028 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8029 P != PEnd; ++P) {
8030 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00008031 if (!HasExplicitTemplateArgs) {
8032 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00008033 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
8034 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00008035 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008036
John McCall58cc69d2010-01-27 01:50:18 +00008037 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008038 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8039 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00008040 }
Douglas Gregor450f00842009-09-25 18:43:00 +00008041 }
8042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008043
Douglas Gregor450f00842009-09-25 18:43:00 +00008044 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8045 if (!FunTmpl)
8046 continue;
8047
Larisse Voufo98b20f12013-07-19 23:00:19 +00008048 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008049 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008050 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008051 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00008052 (HasExplicitTemplateArgs ? &TemplateArgs
8053 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00008054 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008055 // Keep track of almost-matches.
8056 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00008057 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008058 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008059 (void)TDK;
8060 continue;
8061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008062
John McCall58cc69d2010-01-27 01:50:18 +00008063 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008064 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008065
Douglas Gregor450f00842009-09-25 18:43:00 +00008066 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008067 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008068 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008069 D.getIdentifierLoc(),
8070 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8071 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8072 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008073
John McCall58cc69d2010-01-27 01:50:18 +00008074 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008075 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008076
8077 // Ignore access control bits, we don't need them for redeclaration checking.
8078 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008079
Alexey Bataev73983912014-11-06 10:10:50 +00008080 // C++11 [except.spec]p4
8081 // In an explicit instantiation an exception-specification may be specified,
8082 // but is not required.
8083 // If an exception-specification is specified in an explicit instantiation
8084 // directive, it shall be compatible with the exception-specifications of
8085 // other declarations of that function.
8086 if (auto *FPT = R->getAs<FunctionProtoType>())
8087 if (FPT->hasExceptionSpec()) {
8088 unsigned DiagID =
8089 diag::err_mismatched_exception_spec_explicit_instantiation;
8090 if (getLangOpts().MicrosoftExt)
8091 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8092 bool Result = CheckEquivalentExceptionSpec(
8093 PDiag(DiagID) << Specialization->getType(),
8094 PDiag(diag::note_explicit_instantiation_here),
8095 Specialization->getType()->getAs<FunctionProtoType>(),
8096 Specialization->getLocation(), FPT, D.getLocStart());
8097 // In Microsoft mode, mismatching exception specifications just cause a
8098 // warning.
8099 if (!getLangOpts().MicrosoftExt && Result)
8100 return true;
8101 }
8102
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008103 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008104 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008105 diag::err_explicit_instantiation_member_function_not_instantiated)
8106 << Specialization
8107 << (Specialization->getTemplateSpecializationKind() ==
8108 TSK_ExplicitSpecialization);
8109 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8110 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008111 }
8112
Douglas Gregorec9fd132012-01-14 16:38:05 +00008113 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008114 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8115 PrevDecl = Specialization;
8116
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008117 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008118 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008119 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008120 PrevDecl,
8121 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008122 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008123 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008124 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008125
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008126 // FIXME: We may still want to build some representation of this
8127 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008128 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008129 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008130 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008131
8132 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008133 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
8134 if (Attr)
8135 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008136
Richard Smitheb36ddf2014-04-24 22:45:46 +00008137 if (Specialization->isDefined()) {
8138 // Let the ASTConsumer know that this function has been explicitly
8139 // instantiated now, and its linkage might have changed.
8140 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8141 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008142 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008143
Douglas Gregore47f5a72009-10-14 23:41:34 +00008144 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008145 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008146 // or a static data member of a class template specialization, the name of
8147 // the class template specialization in the qualified-id for the member
8148 // name shall be a simple-template-id.
8149 //
8150 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008151 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008152 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008153 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008154 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008155 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008156 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008157 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008158
Nathan Wilson83839122016-04-09 02:55:27 +00008159 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8160 // explicit instantiation (14.8.2) [...] of a concept definition.
8161 if (FunTmpl && FunTmpl->isConcept() &&
8162 !D.getDeclSpec().isConceptSpecified()) {
8163 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8164 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8165 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8166 return true;
8167 }
8168
Douglas Gregore47f5a72009-10-14 23:41:34 +00008169 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008170 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008171 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008172 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008173 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008174
Douglas Gregor450f00842009-09-25 18:43:00 +00008175 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008176 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008177}
8178
John McCallfaf5fb42010-08-26 23:41:50 +00008179TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008180Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8181 const CXXScopeSpec &SS, IdentifierInfo *Name,
8182 SourceLocation TagLoc, SourceLocation NameLoc) {
8183 // This has to hold, because SS is expected to be defined.
8184 assert(Name && "Expected a name in a dependent tag");
8185
Aaron Ballman4a979672014-01-03 13:56:08 +00008186 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008187 if (!NNS)
8188 return true;
8189
Abramo Bagnara6150c882010-05-11 21:36:43 +00008190 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008191
Douglas Gregorba41d012010-04-24 16:38:41 +00008192 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8193 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008194 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008195 return true;
8196 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008197
Douglas Gregore7c20652011-03-02 00:47:37 +00008198 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008199 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008200 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8201
8202 // Create type-source location information for this type.
8203 TypeLocBuilder TLB;
8204 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008205 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008206 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8207 TL.setNameLoc(NameLoc);
8208 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008209}
8210
John McCallfaf5fb42010-08-26 23:41:50 +00008211TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008212Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8213 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008214 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008215 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008216 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008217
Richard Smith0bf8a4922011-10-18 20:49:44 +00008218 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8219 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008220 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008221 diag::warn_cxx98_compat_typename_outside_of_template :
8222 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008223 << FixItHint::CreateRemoval(TypenameLoc);
8224
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008225 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008226 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8227 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008228 if (T.isNull())
8229 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008230
8231 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8232 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008233 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008234 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008235 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008236 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008237 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008238 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008239 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008240 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008241 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008242 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008243
John McCallba7bf592010-08-24 05:47:05 +00008244 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008245}
8246
John McCallfaf5fb42010-08-26 23:41:50 +00008247TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008248Sema::ActOnTypenameType(Scope *S,
8249 SourceLocation TypenameLoc,
8250 const CXXScopeSpec &SS,
8251 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008252 TemplateTy TemplateIn,
8253 SourceLocation TemplateNameLoc,
8254 SourceLocation LAngleLoc,
8255 ASTTemplateArgsPtr TemplateArgsIn,
8256 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008257 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8258 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008259 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008260 diag::warn_cxx98_compat_typename_outside_of_template :
8261 diag::ext_typename_outside_of_template)
8262 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008263
8264 // Translate the parser's template argument list in our AST format.
8265 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8266 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8267
8268 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008269 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8270 // Construct a dependent template specialization type.
8271 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008272 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008273 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8274 DTN->getQualifier(),
8275 DTN->getIdentifier(),
8276 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008277
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008278 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008279 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008280 DependentTemplateSpecializationTypeLoc SpecTL
8281 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008282 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8283 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008284 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008285 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008286 SpecTL.setLAngleLoc(LAngleLoc);
8287 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008288 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8289 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008290 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008291 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008292
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008293 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8294 if (T.isNull())
8295 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008296
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008297 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008298 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008299 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008300 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008301 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8302 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008303 SpecTL.setLAngleLoc(LAngleLoc);
8304 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008305 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8306 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8307
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008308 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8309 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008310 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008311 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8312
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008313 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8314 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008315}
8316
Douglas Gregorb09518c2011-02-27 22:46:49 +00008317
Richard Smith6f8d2c62012-05-09 05:17:00 +00008318/// Determine whether this failed name lookup should be treated as being
8319/// disabled by a usage of std::enable_if.
8320static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8321 SourceRange &CondRange) {
8322 // We must be looking for a ::type...
8323 if (!II.isStr("type"))
8324 return false;
8325
8326 // ... within an explicitly-written template specialization...
8327 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8328 return false;
8329 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008330 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8331 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8332 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008333 return false;
8334 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008335 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008336
8337 // ... which names a complete class template declaration...
8338 const TemplateDecl *EnableIfDecl =
8339 EnableIfTST->getTemplateName().getAsTemplateDecl();
8340 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8341 return false;
8342
8343 // ... called "enable_if".
8344 const IdentifierInfo *EnableIfII =
8345 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8346 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8347 return false;
8348
8349 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008350 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008351 return true;
8352}
8353
Douglas Gregor333489b2009-03-27 23:10:48 +00008354/// \brief Build the type that describes a C++ typename specifier,
8355/// e.g., "typename T::type".
8356QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008357Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8358 SourceLocation KeywordLoc,
8359 NestedNameSpecifierLoc QualifierLoc,
8360 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008361 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008362 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008363 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008364
John McCall0b66eb32010-05-01 00:40:08 +00008365 DeclContext *Ctx = computeDeclContext(SS);
8366 if (!Ctx) {
8367 // If the nested-name-specifier is dependent and couldn't be
8368 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008369 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8370 return Context.getDependentNameType(Keyword,
8371 QualifierLoc.getNestedNameSpecifier(),
8372 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008373 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008374
John McCall0b66eb32010-05-01 00:40:08 +00008375 // If the nested-name-specifier refers to the current instantiation,
8376 // the "typename" keyword itself is superfluous. In C++03, the
8377 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8378 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008379 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008380
John McCall0b66eb32010-05-01 00:40:08 +00008381 if (RequireCompleteDeclContext(SS, Ctx))
8382 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008383
8384 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008385 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008386 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008387 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008388 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008389 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008390 case LookupResult::NotFound: {
8391 // If we're looking up 'type' within a template named 'enable_if', produce
8392 // a more specific diagnostic.
8393 SourceRange CondRange;
8394 if (isEnableIf(QualifierLoc, II, CondRange)) {
8395 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8396 << Ctx << CondRange;
8397 return QualType();
8398 }
8399
Douglas Gregore40876a2009-10-13 21:16:44 +00008400 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008401 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008402 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008403
8404 case LookupResult::FoundUnresolvedValue: {
8405 // We found a using declaration that is a value. Most likely, the using
8406 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008407 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008408 IILoc);
8409 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8410 << Name << Ctx << FullRange;
8411 if (UnresolvedUsingValueDecl *Using
8412 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008413 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008414 Diag(Loc, diag::note_using_value_decl_missing_typename)
8415 << FixItHint::CreateInsertion(Loc, "typename ");
8416 }
8417 }
8418 // Fall through to create a dependent typename type, from which we can recover
8419 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008420
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008421 case LookupResult::NotFoundInCurrentInstantiation:
8422 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008423 return Context.getDependentNameType(Keyword,
8424 QualifierLoc.getNestedNameSpecifier(),
8425 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008426
8427 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008428 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008429 // We found a type. Build an ElaboratedType, since the
8430 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008431 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008432 return Context.getElaboratedType(ETK_Typename,
8433 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008434 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008435 }
8436
8437 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008438 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008439 break;
8440
8441 case LookupResult::FoundOverloaded:
8442 DiagID = diag::err_typename_nested_not_type;
8443 Referenced = *Result.begin();
8444 break;
8445
John McCall6538c932009-10-10 05:48:19 +00008446 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008447 return QualType();
8448 }
8449
8450 // If we get here, it's because name lookup did not find a
8451 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008452 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008453 IILoc);
8454 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008455 if (Referenced)
8456 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8457 << Name;
8458 return QualType();
8459}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008460
8461namespace {
8462 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008463 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008464 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008465 SourceLocation Loc;
8466 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008467
Douglas Gregor15acfb92009-08-06 16:20:37 +00008468 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008469 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008470
Mike Stump11289f42009-09-09 15:08:12 +00008471 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008472 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008473 DeclarationName Entity)
8474 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008475 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008476
8477 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008478 /// transformed.
8479 ///
8480 /// For the purposes of type reconstruction, a type has already been
8481 /// transformed if it is NULL or if it is not dependent.
8482 bool AlreadyTransformed(QualType T) {
8483 return T.isNull() || !T->isDependentType();
8484 }
Mike Stump11289f42009-09-09 15:08:12 +00008485
8486 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008487 /// rebuilt.
8488 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008489
Douglas Gregor15acfb92009-08-06 16:20:37 +00008490 /// \brief Returns the name of the entity whose type is being rebuilt.
8491 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008492
Douglas Gregoref6ab412009-10-27 06:26:26 +00008493 /// \brief Sets the "base" location and entity when that
8494 /// information is known based on another transformation.
8495 void setBase(SourceLocation Loc, DeclarationName Entity) {
8496 this->Loc = Loc;
8497 this->Entity = Entity;
8498 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008499
8500 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8501 // Lambdas never need to be transformed.
8502 return E;
8503 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008504 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008505} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008506
Douglas Gregor15acfb92009-08-06 16:20:37 +00008507/// \brief Rebuilds a type within the context of the current instantiation.
8508///
Mike Stump11289f42009-09-09 15:08:12 +00008509/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008510/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008511/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008512/// partial specialization thereof). This routine will rebuild that type now
8513/// that we have entered the declarator's scope, which may produce different
8514/// canonical types, e.g.,
8515///
8516/// \code
8517/// template<typename T>
8518/// struct X {
8519/// typedef T* pointer;
8520/// pointer data();
8521/// };
8522///
8523/// template<typename T>
8524/// typename X<T>::pointer X<T>::data() { ... }
8525/// \endcode
8526///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008527/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008528/// since we do not know that we can look into X<T> when we parsed the type.
8529/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008530/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008531/// as the canonical type of T*, allowing the return types of the out-of-line
8532/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008533TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8534 SourceLocation Loc,
8535 DeclarationName Name) {
8536 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008537 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008538
Douglas Gregor15acfb92009-08-06 16:20:37 +00008539 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8540 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008541}
Douglas Gregorbe999392009-09-15 16:23:51 +00008542
John McCalldadc5752010-08-24 06:29:42 +00008543ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008544 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8545 DeclarationName());
8546 return Rebuilder.TransformExpr(E);
8547}
8548
John McCall99b2fe52010-04-29 23:50:39 +00008549bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008550 if (SS.isInvalid())
8551 return true;
John McCall2408e322010-04-27 00:57:59 +00008552
Douglas Gregor10176412011-02-25 16:07:42 +00008553 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008554 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8555 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008556 NestedNameSpecifierLoc Rebuilt
8557 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8558 if (!Rebuilt)
8559 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008560
Douglas Gregor10176412011-02-25 16:07:42 +00008561 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008562 return false;
John McCall2408e322010-04-27 00:57:59 +00008563}
8564
Douglas Gregor041b0842011-10-14 15:31:12 +00008565/// \brief Rebuild the template parameters now that we know we're in a current
8566/// instantiation.
8567bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8568 TemplateParameterList *Params) {
8569 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8570 Decl *Param = Params->getParam(I);
8571
8572 // There is nothing to rebuild in a type parameter.
8573 if (isa<TemplateTypeParmDecl>(Param))
8574 continue;
8575
8576 // Rebuild the template parameter list of a template template parameter.
8577 if (TemplateTemplateParmDecl *TTP
8578 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8579 if (RebuildTemplateParamsInCurrentInstantiation(
8580 TTP->getTemplateParameters()))
8581 return true;
8582
8583 continue;
8584 }
8585
8586 // Rebuild the type of a non-type template parameter.
8587 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8588 TypeSourceInfo *NewTSI
8589 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8590 NTTP->getLocation(),
8591 NTTP->getDeclName());
8592 if (!NewTSI)
8593 return true;
8594
8595 if (NewTSI != NTTP->getTypeSourceInfo()) {
8596 NTTP->setTypeSourceInfo(NewTSI);
8597 NTTP->setType(NewTSI->getType());
8598 }
8599 }
8600
8601 return false;
8602}
8603
Douglas Gregorbe999392009-09-15 16:23:51 +00008604/// \brief Produces a formatted string that describes the binding of
8605/// template parameters to template arguments.
8606std::string
8607Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8608 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008609 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008610}
8611
8612std::string
8613Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8614 const TemplateArgument *Args,
8615 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008616 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008617 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008618
Douglas Gregore62e6a02009-11-11 19:13:48 +00008619 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008620 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008621
Douglas Gregorbe999392009-09-15 16:23:51 +00008622 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008623 if (I >= NumArgs)
8624 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008625
Douglas Gregorbe999392009-09-15 16:23:51 +00008626 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008627 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008628 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008629 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008630
Douglas Gregorbe999392009-09-15 16:23:51 +00008631 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008632 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008633 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008634 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008636
Douglas Gregor0192c232010-12-20 16:52:59 +00008637 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008638 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008639 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008640
8641 Out << ']';
8642 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008643}
Francois Pichet1c229c02011-04-22 22:18:13 +00008644
Richard Smithe40f2ba2013-08-07 21:41:30 +00008645void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8646 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008647 if (!FD)
8648 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008649
8650 LateParsedTemplate *LPT = new LateParsedTemplate;
8651
8652 // Take tokens to avoid allocations
8653 LPT->Toks.swap(Toks);
8654 LPT->D = FnD;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00008655 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008656
8657 FD->setLateTemplateParsed(true);
8658}
8659
8660void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8661 if (!FD)
8662 return;
8663 FD->setLateTemplateParsed(false);
8664}
Francois Pichet1c229c02011-04-22 22:18:13 +00008665
8666bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8667 DeclContext *DC = CurContext;
8668
8669 while (DC) {
8670 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8671 const FunctionDecl *FD = RD->isLocalClass();
8672 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8673 } else if (DC->isTranslationUnit() || DC->isNamespace())
8674 return false;
8675
8676 DC = DC->getParent();
8677 }
8678 return false;
8679}
Richard Smith6739a102016-05-05 00:56:12 +00008680
Benjamin Kramera0a13c32016-08-06 11:21:04 +00008681namespace {
Richard Smith6739a102016-05-05 00:56:12 +00008682/// \brief Walk the path from which a declaration was instantiated, and check
8683/// that every explicit specialization along that path is visible. This enforces
8684/// C++ [temp.expl.spec]/6:
8685///
8686/// If a template, a member template or a member of a class template is
8687/// explicitly specialized then that specialization shall be declared before
8688/// the first use of that specialization that would cause an implicit
8689/// instantiation to take place, in every translation unit in which such a
8690/// use occurs; no diagnostic is required.
8691///
8692/// and also C++ [temp.class.spec]/1:
8693///
8694/// A partial specialization shall be declared before the first use of a
8695/// class template specialization that would make use of the partial
8696/// specialization as the result of an implicit or explicit instantiation
8697/// in every translation unit in which such a use occurs; no diagnostic is
8698/// required.
8699class ExplicitSpecializationVisibilityChecker {
8700 Sema &S;
8701 SourceLocation Loc;
8702 llvm::SmallVector<Module *, 8> Modules;
8703
8704public:
8705 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
8706 : S(S), Loc(Loc) {}
8707
8708 void check(NamedDecl *ND) {
8709 if (auto *FD = dyn_cast<FunctionDecl>(ND))
8710 return checkImpl(FD);
8711 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
8712 return checkImpl(RD);
8713 if (auto *VD = dyn_cast<VarDecl>(ND))
8714 return checkImpl(VD);
8715 if (auto *ED = dyn_cast<EnumDecl>(ND))
8716 return checkImpl(ED);
8717 }
8718
8719private:
8720 void diagnose(NamedDecl *D, bool IsPartialSpec) {
8721 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
8722 : Sema::MissingImportKind::ExplicitSpecialization;
8723 const bool Recover = true;
8724
8725 // If we got a custom set of modules (because only a subset of the
8726 // declarations are interesting), use them, otherwise let
8727 // diagnoseMissingImport intelligently pick some.
8728 if (Modules.empty())
8729 S.diagnoseMissingImport(Loc, D, Kind, Recover);
8730 else
8731 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
8732 }
8733
8734 // Check a specific declaration. There are three problematic cases:
8735 //
8736 // 1) The declaration is an explicit specialization of a template
8737 // specialization.
8738 // 2) The declaration is an explicit specialization of a member of an
8739 // templated class.
8740 // 3) The declaration is an instantiation of a template, and that template
8741 // is an explicit specialization of a member of a templated class.
8742 //
8743 // We don't need to go any deeper than that, as the instantiation of the
8744 // surrounding class / etc is not triggered by whatever triggered this
8745 // instantiation, and thus should be checked elsewhere.
8746 template<typename SpecDecl>
8747 void checkImpl(SpecDecl *Spec) {
8748 bool IsHiddenExplicitSpecialization = false;
8749 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
8750 IsHiddenExplicitSpecialization =
8751 Spec->getMemberSpecializationInfo()
8752 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
8753 : !S.hasVisibleDeclaration(Spec);
8754 } else {
8755 checkInstantiated(Spec);
8756 }
8757
8758 if (IsHiddenExplicitSpecialization)
8759 diagnose(Spec->getMostRecentDecl(), false);
8760 }
8761
8762 void checkInstantiated(FunctionDecl *FD) {
8763 if (auto *TD = FD->getPrimaryTemplate())
8764 checkTemplate(TD);
8765 }
8766
8767 void checkInstantiated(CXXRecordDecl *RD) {
8768 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
8769 if (!SD)
8770 return;
8771
8772 auto From = SD->getSpecializedTemplateOrPartial();
8773 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
8774 checkTemplate(TD);
8775 else if (auto *TD =
8776 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
8777 if (!S.hasVisibleDeclaration(TD))
8778 diagnose(TD, true);
8779 checkTemplate(TD);
8780 }
8781 }
8782
8783 void checkInstantiated(VarDecl *RD) {
8784 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
8785 if (!SD)
8786 return;
8787
8788 auto From = SD->getSpecializedTemplateOrPartial();
8789 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
8790 checkTemplate(TD);
8791 else if (auto *TD =
8792 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
8793 if (!S.hasVisibleDeclaration(TD))
8794 diagnose(TD, true);
8795 checkTemplate(TD);
8796 }
8797 }
8798
8799 void checkInstantiated(EnumDecl *FD) {}
8800
8801 template<typename TemplDecl>
8802 void checkTemplate(TemplDecl *TD) {
8803 if (TD->isMemberSpecialization()) {
8804 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
8805 diagnose(TD->getMostRecentDecl(), false);
8806 }
8807 }
8808};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00008809} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00008810
8811void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
8812 if (!getLangOpts().Modules)
8813 return;
8814
8815 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
8816}
8817
8818/// \brief Check whether a template partial specialization that we've discovered
8819/// is hidden, and produce suitable diagnostics if so.
8820void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
8821 NamedDecl *Spec) {
8822 llvm::SmallVector<Module *, 8> Modules;
8823 if (!hasVisibleDeclaration(Spec, &Modules))
8824 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
8825 MissingImportKind::PartialSpecialization,
8826 /*Recover*/true);
8827}