blob: 90de88ac3327a33a8e23678e34010eb1b67237db [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
Simon Pilgrim6905d222016-12-30 22:55:33 +000091void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000092 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();
Simon Pilgrim6905d222016-12-30 22:55:33 +000098 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000099 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;
Simon Pilgrim6905d222016-12-30 22:55:33 +0000134
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");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000268
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000269 // 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);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000315
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000316 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
Akira Hatanakad644e022016-12-16 03:19:41 +0000432 // Check if the nested name specifier is an enum type.
433 bool IsEnum = false;
434 if (NestedNameSpecifier *NNS = SS.getScopeRep())
435 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
436
437 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000438 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000439 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000440
John McCalle66edc12009-11-24 19:00:30 +0000441 // Since the 'this' expression is synthesized, we don't need to
442 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000443 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000444
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000445 return CXXDependentScopeMemberExpr::Create(
446 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
447 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
448 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000449 }
450
Abramo Bagnara7945c982012-01-27 09:46:47 +0000451 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000452}
453
John McCalldadc5752010-08-24 06:29:42 +0000454ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000455Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000456 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000457 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000458 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000459 return DependentScopeDeclRefExpr::Create(
460 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
461 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000462}
463
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000464
465/// Determine whether we would be unable to instantiate this template (because
466/// it either has no definition, or is in the process of being instantiated).
467bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
468 NamedDecl *Instantiation,
469 bool InstantiatedFromMember,
470 const NamedDecl *Pattern,
471 const NamedDecl *PatternDef,
472 TemplateSpecializationKind TSK,
473 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000474 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
475 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000476
Richard Smithedbc6e92016-10-14 21:41:24 +0000477 bool IsEntityBeingDefined = false;
478 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
479 IsEntityBeingDefined = TD->isBeingDefined();
480
481 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000482 NamedDecl *SuggestedDef = nullptr;
483 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
484 /*OnlyNeedComplete*/false)) {
485 // If we're allowed to diagnose this and recover, do so.
486 bool Recover = Complain && !isSFINAEContext();
487 if (Complain)
488 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
489 Sema::MissingImportKind::Definition, Recover);
490 return !Recover;
491 }
492 return false;
493 }
494
Richard Smith6f4e2e02016-08-23 19:41:39 +0000495 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
496 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000497
Richard Smithedbc6e92016-10-14 21:41:24 +0000498 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000499 QualType InstantiationTy;
500 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
501 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000502 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000503 Diag(PointOfInstantiation,
504 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000505 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000506 << InstantiationTy;
507 // Not much point in noting the template declaration here, since
508 // we're lexically inside it.
509 Instantiation->setInvalidDecl();
510 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000511 if (isa<FunctionDecl>(Instantiation)) {
512 Diag(PointOfInstantiation,
513 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000514 << /*member function*/ 1 << Instantiation->getDeclName()
515 << Instantiation->getDeclContext();
516 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000517 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000518 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000519 Diag(PointOfInstantiation,
520 diag::err_implicit_instantiate_member_undefined)
521 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000522 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000523 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000524 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000525 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000526 Diag(PointOfInstantiation,
527 diag::err_explicit_instantiation_undefined_func_template)
528 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000529 Note = diag::note_explicit_instantiation_here;
530 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000531 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
532 << (TSK != TSK_ImplicitInstantiation)
533 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000534 Note = diag::note_template_decl_here;
535 } else {
536 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
537 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
538 Diag(PointOfInstantiation,
539 diag::err_explicit_instantiation_undefined_var_template)
540 << Instantiation;
541 Instantiation->setInvalidDecl();
542 } else
543 Diag(PointOfInstantiation,
544 diag::err_explicit_instantiation_undefined_member)
545 << /*static data member*/ 2 << Instantiation->getDeclName()
546 << Instantiation->getDeclContext();
547 Note = diag::note_explicit_instantiation_here;
548 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000549 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000550 if (Note) // Diagnostics were emitted.
551 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000552
553 // In general, Instantiation isn't marked invalid to get more than one
554 // error for multiple undefined instantiations. But the code that does
555 // explicit declaration -> explicit definition conversion can't handle
556 // invalid declarations, so mark as invalid in that case.
557 if (TSK == TSK_ExplicitInstantiationDeclaration)
558 Instantiation->setInvalidDecl();
559 return true;
560}
561
Douglas Gregor5101c242008-12-05 18:15:24 +0000562/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
563/// that the template parameter 'PrevDecl' is being shadowed by a new
564/// declaration at location Loc. Returns true to indicate that this is
565/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000566void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000567 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000568
569 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000570 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000571 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000572
573 // C++ [temp.local]p4:
574 // A template-parameter shall not be redeclared within its
575 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000576 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000577 << cast<NamedDecl>(PrevDecl)->getDeclName();
578 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000579}
580
Douglas Gregor463421d2009-03-03 04:44:36 +0000581/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000582/// the parameter D to reference the templated declaration and return a pointer
583/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000584TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
585 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
586 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000587 return Temp;
588 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000589 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000590}
591
Douglas Gregoreb29d182011-01-05 17:40:24 +0000592ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
593 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000595 "Only template template arguments can be pack expansions here");
596 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
597 "Template template argument pack expansion without packs");
598 ParsedTemplateArgument Result(*this);
599 Result.EllipsisLoc = EllipsisLoc;
600 return Result;
601}
602
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000603static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
604 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000606 switch (Arg.getKind()) {
607 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000608 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000609 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000611 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000612 return TemplateArgumentLoc(TemplateArgument(T), DI);
613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000615 case ParsedTemplateArgument::NonType: {
616 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
617 return TemplateArgumentLoc(TemplateArgument(E), E);
618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000620 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000621 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000622 TemplateArgument TArg;
623 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000624 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000625 else
626 TArg = Template;
627 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000628 Arg.getScopeSpec().getWithLocInContext(
629 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000630 Arg.getLocation(),
631 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000632 }
633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000635 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000636}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000637
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000638/// \brief Translates template arguments as provided by the parser
639/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000640void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
641 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000642 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000643 TemplateArgs.addArgument(translateTemplateArgument(*this,
644 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000645}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000646
Richard Smithb80d5402013-06-25 22:21:36 +0000647static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
648 SourceLocation Loc,
649 IdentifierInfo *Name) {
650 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
651 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
652 if (PrevDecl && PrevDecl->isTemplateParameter())
653 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
654}
655
Douglas Gregor5101c242008-12-05 18:15:24 +0000656/// ActOnTypeParameter - Called when a C++ template type parameter
657/// (e.g., "typename T") has been parsed. Typename specifies whether
658/// the keyword "typename" was used to declare the type parameter
659/// (otherwise, "class" was used), and KeyLoc is the location of the
660/// "class" or "typename" keyword. ParamName is the name of the
661/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000662/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000663/// If the type parameter has a default argument, it will be added
664/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000665Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000666 SourceLocation EllipsisLoc,
667 SourceLocation KeyLoc,
668 IdentifierInfo *ParamName,
669 SourceLocation ParamNameLoc,
670 unsigned Depth, unsigned Position,
671 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000672 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000673 assert(S->isTemplateParamScope() &&
674 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000675
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000676 SourceLocation Loc = ParamNameLoc;
677 if (!ParamName)
678 Loc = KeyLoc;
679
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000680 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000681 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000682 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000683 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000684 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000685 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000686
687 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000688 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
689
Douglas Gregor5101c242008-12-05 18:15:24 +0000690 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000691 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000692 IdResolver.AddDecl(Param);
693 }
694
Douglas Gregorf5500772011-01-05 15:48:55 +0000695 // C++0x [temp.param]p9:
696 // A default template-argument may be specified for any kind of
697 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000698 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000699 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000700 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000701 }
702
Douglas Gregordc13ded2010-07-01 00:00:45 +0000703 // Handle the default argument, if provided.
704 if (DefaultArg) {
705 TypeSourceInfo *DefaultTInfo;
706 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707
Douglas Gregordc13ded2010-07-01 00:00:45 +0000708 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000710 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000711 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000712 UPPC_DefaultArgument))
713 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Douglas Gregordc13ded2010-07-01 00:00:45 +0000715 // Check the template argument itself.
716 if (CheckTemplateArgument(Param, DefaultTInfo)) {
717 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000718 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000719 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000720
Richard Smith1469b912015-06-10 00:29:03 +0000721 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723
John McCall48871652010-08-21 09:40:31 +0000724 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000725}
726
Douglas Gregor463421d2009-03-03 04:44:36 +0000727/// \brief Check that the type of a non-type template parameter is
728/// well-formed.
729///
730/// \returns the (possibly-promoted) parameter type if valid;
731/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000732QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
733 SourceLocation Loc) {
734 if (TSI->getType()->isUndeducedType()) {
735 // C++1z [temp.dep.expr]p3:
736 // An id-expression is type-dependent if it contains
737 // - an identifier associated by name lookup with a non-type
738 // template-parameter declared with a type that contains a
739 // placeholder type (7.1.7.4),
740 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
741 }
742
743 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
744}
745
746QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
747 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000748 // We don't allow variably-modified types as the type of non-type template
749 // parameters.
750 if (T->isVariablyModifiedType()) {
751 Diag(Loc, diag::err_variably_modified_nontype_template_param)
752 << T;
753 return QualType();
754 }
755
Douglas Gregor463421d2009-03-03 04:44:36 +0000756 // C++ [temp.param]p4:
757 //
758 // A non-type template-parameter shall have one of the following
759 // (optionally cv-qualified) types:
760 //
761 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000762 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000763 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000764 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000765 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000766 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000767 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000768 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000769 // -- std::nullptr_t.
770 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000771 // If T is a dependent type, we can't do the check now, so we
772 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +0000773 T->isDependentType() ||
774 // Allow use of auto in template parameter declarations.
775 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +0000776 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
777 // are ignored when determining its type.
778 return T.getUnqualifiedType();
779 }
780
Douglas Gregor463421d2009-03-03 04:44:36 +0000781 // C++ [temp.param]p8:
782 //
783 // A non-type template-parameter of type "array of T" or
784 // "function returning T" is adjusted to be of type "pointer to
785 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000786 else if (T->isArrayType() || T->isFunctionType())
787 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000788
Douglas Gregor463421d2009-03-03 04:44:36 +0000789 Diag(Loc, diag::err_template_nontype_parm_bad_type)
790 << T;
791
792 return QualType();
793}
794
John McCall48871652010-08-21 09:40:31 +0000795Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
796 unsigned Depth,
797 unsigned Position,
798 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000799 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000800 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +0000801
802 if (TInfo->getType()->isUndeducedType()) {
803 Diag(D.getIdentifierLoc(),
804 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
805 << QualType(TInfo->getType()->getContainedAutoType(), 0);
806 }
Douglas Gregor5101c242008-12-05 18:15:24 +0000807
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000808 assert(S->isTemplateParamScope() &&
809 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000810 bool Invalid = false;
811
Richard Smith15361a22016-12-28 06:27:18 +0000812 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000813 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000814 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000815 Invalid = true;
816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817
Richard Smithb80d5402013-06-25 22:21:36 +0000818 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000819 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000820 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000821 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000822 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000823 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000825 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000826 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000827
Douglas Gregor5101c242008-12-05 18:15:24 +0000828 if (Invalid)
829 Param->setInvalidDecl();
830
Richard Smithb80d5402013-06-25 22:21:36 +0000831 if (ParamName) {
832 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
833 ParamName);
834
Douglas Gregor5101c242008-12-05 18:15:24 +0000835 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000836 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000837 IdResolver.AddDecl(Param);
838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839
Douglas Gregorf5500772011-01-05 15:48:55 +0000840 // C++0x [temp.param]p9:
841 // A default template-argument may be specified for any kind of
842 // template-parameter that is not a template parameter pack.
843 if (Default && IsParameterPack) {
844 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000845 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000846 }
847
Douglas Gregordc13ded2010-07-01 00:00:45 +0000848 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000849 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000850 // Check for unexpanded parameter packs.
851 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
852 return Param;
853
Douglas Gregordc13ded2010-07-01 00:00:45 +0000854 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000855 ExprResult DefaultRes =
856 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000857 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000858 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000859 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000860 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000861 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000862
Richard Smith1469b912015-06-10 00:29:03 +0000863 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000865
John McCall48871652010-08-21 09:40:31 +0000866 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000867}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000868
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000869/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000870/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000871/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000872Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
873 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000874 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000875 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000876 IdentifierInfo *Name,
877 SourceLocation NameLoc,
878 unsigned Depth,
879 unsigned Position,
880 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000881 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000882 assert(S->isTemplateParamScope() &&
883 "Template template parameter not in template parameter scope!");
884
885 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000886 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000887 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000888 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889 NameLoc.isInvalid()? TmpLoc : NameLoc,
890 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000891 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000892 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000893
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000894 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000895 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000896 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000897 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
898
John McCall48871652010-08-21 09:40:31 +0000899 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000900 IdResolver.AddDecl(Param);
901 }
902
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000903 if (Params->size() == 0) {
904 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
905 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
906 Param->setInvalidDecl();
907 }
908
Douglas Gregorf5500772011-01-05 15:48:55 +0000909 // C++0x [temp.param]p9:
910 // A default template-argument may be specified for any kind of
911 // template-parameter that is not a template parameter pack.
912 if (IsParameterPack && !Default.isInvalid()) {
913 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
914 Default = ParsedTemplateArgument();
915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916
Douglas Gregordc13ded2010-07-01 00:00:45 +0000917 if (!Default.isInvalid()) {
918 // Check only that we have a template template argument. We don't want to
919 // try to check well-formedness now, because our template template parameter
920 // might have dependent types in its template parameters, which we wouldn't
921 // be able to match now.
922 //
923 // If none of the template template parameter's template arguments mention
924 // other template parameters, we could actually perform more checking here.
925 // However, it isn't worth doing.
926 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
927 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000928 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000929 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000930 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000932
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000933 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000934 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000935 DefaultArg.getArgument().getAsTemplate(),
936 UPPC_DefaultArgument))
937 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000938
Richard Smith1469b912015-06-10 00:29:03 +0000939 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000941
John McCall48871652010-08-21 09:40:31 +0000942 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000943}
944
Hubert Tongf608c052016-04-29 18:05:37 +0000945/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
946/// constrained by RequiresClause, that contains the template parameters in
947/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000948TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000949Sema::ActOnTemplateParameterList(unsigned Depth,
950 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000951 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000952 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000953 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +0000954 SourceLocation RAngleLoc,
955 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000956 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000957 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000958
David Majnemer902f8c62015-12-27 07:16:27 +0000959 return TemplateParameterList::Create(
960 Context, TemplateLoc, LAngleLoc,
961 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000962 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000963}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000964
John McCall3e11ebe2010-03-15 10:12:16 +0000965static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
966 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000967 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000968}
969
John McCallfaf5fb42010-08-26 23:41:50 +0000970DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000971Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000972 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000973 IdentifierInfo *Name, SourceLocation NameLoc,
974 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000975 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000976 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000977 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000978 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000979 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000980 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000981 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000982 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000983 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000984 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000985
986 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000987 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000988 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000989
Abramo Bagnara6150c882010-05-11 21:36:43 +0000990 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
991 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000992
993 // There is no such thing as an unnamed class template.
994 if (!Name) {
995 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000996 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000997 }
998
Richard Smith6483d222012-04-21 01:27:54 +0000999 // Find any previous declaration with this name. For a friend with no
1000 // scope explicitly specified, we only look for tag declarations (per
1001 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001002 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001003 LookupResult Previous(*this, Name, NameLoc,
1004 (SS.isEmpty() && TUK == TUK_Friend)
1005 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00001006 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001007 if (SS.isNotEmpty() && !SS.isInvalid()) {
1008 SemanticContext = computeDeclContext(SS, true);
1009 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001010 // FIXME: Horrible, horrible hack! We can't currently represent this
1011 // in the AST, and historically we have just ignored such friend
1012 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001013 Diag(NameLoc, TUK == TUK_Friend
1014 ? diag::warn_template_qualified_friend_ignored
1015 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001016 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001017 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001018 }
Mike Stump11289f42009-09-09 15:08:12 +00001019
John McCall0b66eb32010-05-01 00:40:08 +00001020 if (RequireCompleteDeclContext(SS, SemanticContext))
1021 return true;
1022
Simon Pilgrim6905d222016-12-30 22:55:33 +00001023 // If we're adding a template to a dependent context, we may need to
1024 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001025 // now that we know what the current instantiation is.
1026 if (SemanticContext->isDependentContext()) {
1027 ContextRAII SavedContext(*this, SemanticContext);
1028 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1029 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001030 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1031 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +00001032
John McCall27b18f82009-11-17 02:14:36 +00001033 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001034 } else {
1035 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001036
1037 // C++14 [class.mem]p14:
1038 // If T is the name of a class, then each of the following shall have a
1039 // name different from T:
1040 // -- every member template of class T
1041 if (TUK != TUK_Friend &&
1042 DiagnoseClassNameShadow(SemanticContext,
1043 DeclarationNameInfo(Name, NameLoc)))
1044 return true;
1045
John McCall27b18f82009-11-17 02:14:36 +00001046 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001047 }
Mike Stump11289f42009-09-09 15:08:12 +00001048
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001049 if (Previous.isAmbiguous())
1050 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001051
Craig Topperc3ec1492014-05-26 06:22:03 +00001052 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001053 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001054 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001055
Serge Pavlove50bf752016-06-10 04:39:07 +00001056 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1057 // Maybe we will complain about the shadowed template parameter.
1058 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1059 // Just pretend that we didn't see the previous declaration.
1060 PrevDecl = nullptr;
1061 }
1062
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001063 // If there is a previous declaration with the same name, check
1064 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +00001065 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001066 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001067
1068 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001069 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001070 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001071 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001072 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1073 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001074 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001075 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1076 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1077 PrevClassTemplate
1078 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1079 ->getSpecializedTemplate();
1080 }
1081 }
1082
John McCalld43784f2009-12-18 11:25:59 +00001083 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001084 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001085 // [...] When looking for a prior declaration of a class or a function
1086 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001087 // function is neither a qualified name nor a template-id, scopes outside
1088 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001089 if (!SS.isSet()) {
1090 DeclContext *OutermostContext = CurContext;
1091 while (!OutermostContext->isFileContext())
1092 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001093
Richard Smith61e582f2012-04-20 07:12:26 +00001094 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001095 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1096 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1097 SemanticContext = PrevDecl->getDeclContext();
1098 } else {
1099 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001100 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001101 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001102 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001103 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001104
1105 // Check that the chosen semantic context doesn't already contain a
1106 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001107 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001108 DeclContext *LookupContext = SemanticContext;
1109 while (LookupContext->isTransparentContext())
1110 LookupContext = LookupContext->getLookupParent();
1111 LookupQualifiedName(Previous, LookupContext);
1112
1113 if (Previous.isAmbiguous())
1114 return true;
1115
1116 if (Previous.begin() != Previous.end())
1117 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001118 }
John McCall90d3bb92009-12-17 23:21:11 +00001119 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001120 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001121 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1122 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001123 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001124
Richard Smithfc805ca2015-07-06 04:43:58 +00001125 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1126 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1127 if (SS.isEmpty() &&
1128 !(PrevClassTemplate &&
1129 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1130 SemanticContext->getRedeclContext()))) {
1131 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1132 Diag(Shadow->getTargetDecl()->getLocation(),
1133 diag::note_using_decl_target);
1134 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1135 // Recover by ignoring the old declaration.
1136 PrevDecl = PrevClassTemplate = nullptr;
1137 }
1138 }
1139
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001140 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001141 // Ensure that the template parameter lists are compatible. Skip this check
1142 // for a friend in a dependent context: the template parameter list itself
1143 // could be dependent.
1144 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1145 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001146 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001147 /*Complain=*/true,
1148 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001149 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001150
1151 // C++ [temp.class]p4:
1152 // In a redeclaration, partial specialization, explicit
1153 // specialization or explicit instantiation of a class template,
1154 // the class-key shall agree in kind with the original class
1155 // template declaration (7.1.5.3).
1156 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001157 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001158 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001159 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001160 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001161 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001162 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001163 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001164 }
1165
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001166 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001167 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001168 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001169 // If we have a prior definition that is not visible, treat this as
1170 // simply making that previous definition visible.
1171 NamedDecl *Hidden = nullptr;
1172 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001173 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001174 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1175 assert(Tmpl && "original definition of a class template is not a "
1176 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001177 makeMergedDefinitionVisible(Hidden, KWLoc);
1178 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001179 return Def;
1180 }
1181
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001182 Diag(NameLoc, diag::err_redefinition) << Name;
1183 Diag(Def->getLocation(), diag::note_previous_definition);
1184 // FIXME: Would it make sense to try to "forget" the previous
1185 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001186 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001187 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001188 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001189 } else if (PrevDecl) {
1190 // C++ [temp]p5:
1191 // A class template shall not have the same name as any other
1192 // template, class, function, object, enumeration, enumerator,
1193 // namespace, or type in the same scope (3.3), except as specified
1194 // in (14.5.4).
1195 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1196 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001197 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001198 }
1199
Douglas Gregordba32632009-02-10 19:49:53 +00001200 // Check the template parameter list of this declaration, possibly
1201 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001202 // template declaration. Skip this check for a friend in a dependent
1203 // context, because the template parameter list might be dependent.
1204 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001205 CheckTemplateParameterList(
1206 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001207 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1208 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001209 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1210 SemanticContext->isDependentContext())
1211 ? TPC_ClassTemplateMember
1212 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1213 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001214 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001215
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001216 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001217 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001218 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001219 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1220 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001221 : diag::err_member_decl_does_not_match)
1222 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001223 Invalid = true;
1224 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001225 }
1226
Vassil Vassilev352e4412017-01-12 09:16:26 +00001227 // If this is a templated friend in a dependent context we should not put it
1228 // on the redecl chain. In some cases, the templated friend can be the most
1229 // recent declaration tricking the template instantiator to make substitutions
1230 // there.
1231 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1232 bool ShouldAddRedecl
1233 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1234
Mike Stump11289f42009-09-09 15:08:12 +00001235 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001236 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001237 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001238 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001239 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001240 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001241 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001242 NewClass->setTemplateParameterListsInfo(
1243 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1244 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001245
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001246 // Add alignment attributes if necessary; these attributes are checked when
1247 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001248 if (TUK == TUK_Definition) {
1249 AddAlignmentAttributesForRecord(NewClass);
1250 AddMsStructLayoutForRecord(NewClass);
1251 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001252
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001253 ClassTemplateDecl *NewTemplate
1254 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1255 DeclarationName(Name), TemplateParams,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001256 NewClass);
1257
1258 if (ShouldAddRedecl)
1259 NewTemplate->setPreviousDecl(PrevClassTemplate);
1260
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001261 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001262
Douglas Gregor21823bf2011-12-20 18:11:52 +00001263 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001264 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001265
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001266 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001267 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001268 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001269 assert(T->isDependentType() && "Class template type is not dependent?");
1270 (void)T;
1271
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001272 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001273 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001274 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001275 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1276 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001277
Anders Carlsson137108d2009-03-26 01:24:28 +00001278 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001279 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001280 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001281
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001282 // Set the lexical context of these templates
1283 NewClass->setLexicalDeclContext(CurContext);
1284 NewTemplate->setLexicalDeclContext(CurContext);
1285
John McCall9bb74a52009-07-31 02:45:11 +00001286 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001287 NewClass->startDefinition();
1288
1289 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001290 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001291
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001292 if (PrevClassTemplate)
1293 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1294
Rafael Espindola385c0422012-07-13 18:04:45 +00001295 AddPushedVisibilityAttribute(NewClass);
1296
Richard Smith234ff472014-08-23 00:49:01 +00001297 if (TUK != TUK_Friend) {
1298 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1299 Scope *Outer = S;
1300 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1301 Outer = Outer->getParent();
1302 PushOnScopeChains(NewTemplate, Outer);
1303 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001304 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001305 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001306 NewClass->setAccess(PrevClassTemplate->getAccess());
1307 }
John McCall27b5c252009-09-14 21:59:20 +00001308
Richard Smith64017682013-07-17 23:53:16 +00001309 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001310
John McCall27b5c252009-09-14 21:59:20 +00001311 // Friend templates are visible in fairly strange ways.
1312 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001313 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001314 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001315 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1316 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001317 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001318 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001319
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001320 FriendDecl *Friend = FriendDecl::Create(
1321 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001322 Friend->setAccess(AS_public);
1323 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001324 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001325
Douglas Gregordba32632009-02-10 19:49:53 +00001326 if (Invalid) {
1327 NewTemplate->setInvalidDecl();
1328 NewClass->setInvalidDecl();
1329 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001330
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001331 ActOnDocumentableDecl(NewTemplate);
1332
John McCall48871652010-08-21 09:40:31 +00001333 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001334}
1335
Douglas Gregored5731f2009-11-25 17:50:39 +00001336/// \brief Diagnose the presence of a default template argument on a
1337/// template parameter, which is ill-formed in certain contexts.
1338///
1339/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001340static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001341 Sema::TemplateParamListContext TPC,
1342 SourceLocation ParamLoc,
1343 SourceRange DefArgRange) {
1344 switch (TPC) {
1345 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001346 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001347 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001348 return false;
1349
1350 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001351 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001352 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001353 // A default template-argument shall not be specified in a
1354 // function template declaration or a function template
1355 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00001356 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001357 // template-argument, that declaration shall be a definition and shall be
1358 // the only declaration of the function template in the translation unit.
1359 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001360 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001361 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1362 : diag::ext_template_parameter_default_in_function_template)
1363 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001364 return false;
1365
1366 case Sema::TPC_ClassTemplateMember:
1367 // C++0x [temp.param]p9:
1368 // A default template-argument shall not be specified in the
1369 // template-parameter-lists of the definition of a member of a
1370 // class template that appears outside of the member's class.
1371 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1372 << DefArgRange;
1373 return true;
1374
David Majnemerba8f17a2013-06-25 22:08:55 +00001375 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001376 case Sema::TPC_FriendFunctionTemplate:
1377 // C++ [temp.param]p9:
1378 // A default template-argument shall not be specified in a
1379 // friend template declaration.
1380 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1381 << DefArgRange;
1382 return true;
1383
1384 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1385 // for friend function templates if there is only a single
1386 // declaration (and it is a definition). Strange!
1387 }
1388
David Blaikie8a40f702012-01-17 06:56:22 +00001389 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001390}
1391
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001392/// \brief Check for unexpanded parameter packs within the template parameters
1393/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001394static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1395 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001396 // A template template parameter which is a parameter pack is also a pack
1397 // expansion.
1398 if (TTP->isParameterPack())
1399 return false;
1400
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001401 TemplateParameterList *Params = TTP->getTemplateParameters();
1402 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1403 NamedDecl *P = Params->getParam(I);
1404 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001405 if (!NTTP->isParameterPack() &&
1406 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001407 NTTP->getTypeSourceInfo(),
1408 Sema::UPPC_NonTypeTemplateParameterType))
1409 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001410
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001411 continue;
1412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001413
1414 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001415 = dyn_cast<TemplateTemplateParmDecl>(P))
1416 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1417 return true;
1418 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001419
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001420 return false;
1421}
1422
Douglas Gregordba32632009-02-10 19:49:53 +00001423/// \brief Checks the validity of a template parameter list, possibly
1424/// considering the template parameter list from a previous
1425/// declaration.
1426///
1427/// If an "old" template parameter list is provided, it must be
1428/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1429/// template parameter list.
1430///
1431/// \param NewParams Template parameter list for a new template
1432/// declaration. This template parameter list will be updated with any
1433/// default arguments that are carried through from the previous
1434/// template parameter list.
1435///
1436/// \param OldParams If provided, template parameter list from a
1437/// previous declaration of the same template. Default template
1438/// arguments will be merged from the old template parameter list to
1439/// the new template parameter list.
1440///
Douglas Gregored5731f2009-11-25 17:50:39 +00001441/// \param TPC Describes the context in which we are checking the given
1442/// template parameter list.
1443///
Douglas Gregordba32632009-02-10 19:49:53 +00001444/// \returns true if an error occurred, false otherwise.
1445bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001446 TemplateParameterList *OldParams,
1447 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001448 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001449
Douglas Gregordba32632009-02-10 19:49:53 +00001450 // C++ [temp.param]p10:
1451 // The set of default template-arguments available for use with a
1452 // template declaration or definition is obtained by merging the
1453 // default arguments from the definition (if in scope) and all
1454 // declarations in scope in the same way default function
1455 // arguments are (8.3.6).
1456 bool SawDefaultArgument = false;
1457 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001458
Mike Stumpc89c8e32009-02-11 23:03:27 +00001459 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001460 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001461 if (OldParams)
1462 OldParam = OldParams->begin();
1463
Douglas Gregor0693def2011-01-27 01:40:17 +00001464 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001465 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1466 NewParamEnd = NewParams->end();
1467 NewParam != NewParamEnd; ++NewParam) {
1468 // Variables used to diagnose redundant default arguments
1469 bool RedundantDefaultArg = false;
1470 SourceLocation OldDefaultLoc;
1471 SourceLocation NewDefaultLoc;
1472
David Blaikie651c73c2011-10-19 05:19:50 +00001473 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001474 bool MissingDefaultArg = false;
1475
David Blaikie651c73c2011-10-19 05:19:50 +00001476 // Variable used to diagnose non-final parameter packs
1477 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001478
Douglas Gregordba32632009-02-10 19:49:53 +00001479 if (TemplateTypeParmDecl *NewTypeParm
1480 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001481 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001482 if (NewTypeParm->hasDefaultArgument() &&
1483 DiagnoseDefaultTemplateArgument(*this, TPC,
1484 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001485 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001486 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001487 NewTypeParm->removeDefaultArgument();
1488
1489 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001490 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001491 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001492 if (NewTypeParm->isParameterPack()) {
1493 assert(!NewTypeParm->hasDefaultArgument() &&
1494 "Parameter packs can't have a default argument!");
1495 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001496 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001497 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001498 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1499 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1500 SawDefaultArgument = true;
1501 RedundantDefaultArg = true;
1502 PreviousDefaultArgLoc = NewDefaultLoc;
1503 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1504 // Merge the default argument from the old declaration to the
1505 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001506 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001507 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1508 } else if (NewTypeParm->hasDefaultArgument()) {
1509 SawDefaultArgument = true;
1510 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1511 } else if (SawDefaultArgument)
1512 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001513 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001514 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001515 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001516 if (!NewNonTypeParm->isParameterPack() &&
1517 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001518 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001519 UPPC_NonTypeTemplateParameterType)) {
1520 Invalid = true;
1521 continue;
1522 }
1523
Douglas Gregored5731f2009-11-25 17:50:39 +00001524 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001525 if (NewNonTypeParm->hasDefaultArgument() &&
1526 DiagnoseDefaultTemplateArgument(*this, TPC,
1527 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001528 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001529 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001530 }
1531
Mike Stump12b8ce12009-08-04 21:02:39 +00001532 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001533 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001534 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001535 if (NewNonTypeParm->isParameterPack()) {
1536 assert(!NewNonTypeParm->hasDefaultArgument() &&
1537 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001538 if (!NewNonTypeParm->isPackExpansion())
1539 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001540 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001541 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001542 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1543 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1544 SawDefaultArgument = true;
1545 RedundantDefaultArg = true;
1546 PreviousDefaultArgLoc = NewDefaultLoc;
1547 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1548 // Merge the default argument from the old declaration to the
1549 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001550 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001551 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1552 } else if (NewNonTypeParm->hasDefaultArgument()) {
1553 SawDefaultArgument = true;
1554 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1555 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001556 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001557 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001558 TemplateTemplateParmDecl *NewTemplateParm
1559 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001560
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001561 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001562 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001563 Invalid = true;
1564 continue;
1565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001566
David Blaikie651c73c2011-10-19 05:19:50 +00001567 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001568 if (NewTemplateParm->hasDefaultArgument() &&
1569 DiagnoseDefaultTemplateArgument(*this, TPC,
1570 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001571 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001572 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001573
1574 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001575 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001576 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001577 if (NewTemplateParm->isParameterPack()) {
1578 assert(!NewTemplateParm->hasDefaultArgument() &&
1579 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001580 if (!NewTemplateParm->isPackExpansion())
1581 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001582 } else if (OldTemplateParm &&
1583 hasVisibleDefaultArgument(OldTemplateParm) &&
1584 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001585 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1586 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001587 SawDefaultArgument = true;
1588 RedundantDefaultArg = true;
1589 PreviousDefaultArgLoc = NewDefaultLoc;
1590 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1591 // Merge the default argument from the old declaration to the
1592 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001593 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001594 PreviousDefaultArgLoc
1595 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001596 } else if (NewTemplateParm->hasDefaultArgument()) {
1597 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001598 PreviousDefaultArgLoc
1599 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001600 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001601 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001602 }
1603
Richard Smith1fde8ec2012-09-07 02:06:42 +00001604 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001605 // If a template parameter of a primary class template or alias template
1606 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001607 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001608 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1609 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001610 Diag((*NewParam)->getLocation(),
1611 diag::err_template_param_pack_must_be_last_template_parameter);
1612 Invalid = true;
1613 }
1614
Douglas Gregordba32632009-02-10 19:49:53 +00001615 if (RedundantDefaultArg) {
1616 // C++ [temp.param]p12:
1617 // A template-parameter shall not be given default arguments
1618 // by two different declarations in the same scope.
1619 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1620 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1621 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001622 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001623 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001624 // If a template-parameter of a class template has a default
1625 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001626 // have a default template-argument supplied or be a template parameter
1627 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001628 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001629 diag::err_template_param_default_arg_missing);
1630 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1631 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001632 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001633 }
1634
1635 // If we have an old template parameter list that we're merging
1636 // in, move on to the next parameter.
1637 if (OldParams)
1638 ++OldParam;
1639 }
1640
Douglas Gregor0693def2011-01-27 01:40:17 +00001641 // We were missing some default arguments at the end of the list, so remove
1642 // all of the default arguments.
1643 if (RemoveDefaultArguments) {
1644 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1645 NewParamEnd = NewParams->end();
1646 NewParam != NewParamEnd; ++NewParam) {
1647 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1648 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001649 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001650 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1651 NTTP->removeDefaultArgument();
1652 else
1653 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1654 }
1655 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001656
Douglas Gregordba32632009-02-10 19:49:53 +00001657 return Invalid;
1658}
Douglas Gregord32e0282009-02-09 23:23:08 +00001659
John McCalla020a012010-10-20 05:44:58 +00001660namespace {
1661
1662/// A class which looks for a use of a certain level of template
1663/// parameter.
1664struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1665 typedef RecursiveASTVisitor<DependencyChecker> super;
1666
1667 unsigned Depth;
Richard Smith43a833b2017-01-09 23:54:33 +00001668 bool FindLessThanDepth;
Richard Smith57aae072016-12-28 02:37:25 +00001669
1670 // Whether we're looking for a use of a template parameter that makes the
1671 // overall construct type-dependent / a dependent type. This is strictly
1672 // best-effort for now; we may fail to match at all for a dependent type
1673 // in some cases if this is set.
1674 bool IgnoreNonTypeDependent;
1675
John McCalla020a012010-10-20 05:44:58 +00001676 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001677 SourceLocation MatchLoc;
1678
Richard Smith43a833b2017-01-09 23:54:33 +00001679 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent,
1680 bool FindLessThanDepth = false)
1681 : Depth(Depth), FindLessThanDepth(FindLessThanDepth),
1682 IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001683
Richard Smith57aae072016-12-28 02:37:25 +00001684 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith43a833b2017-01-09 23:54:33 +00001685 : DependencyChecker(Params->getDepth(), IgnoreNonTypeDependent) {}
John McCalla020a012010-10-20 05:44:58 +00001686
Richard Smith6056d5e2014-02-09 00:54:43 +00001687 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith43a833b2017-01-09 23:54:33 +00001688 if (FindLessThanDepth ^ (ParmDepth >= Depth)) {
John McCalla020a012010-10-20 05:44:58 +00001689 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001690 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001691 return true;
1692 }
1693 return false;
1694 }
1695
Richard Smith57aae072016-12-28 02:37:25 +00001696 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
1697 // Prune out non-type-dependent expressions if requested. This can
1698 // sometimes result in us failing to find a template parameter reference
1699 // (if a value-dependent expression creates a dependent type), but this
1700 // mode is best-effort only.
1701 if (auto *E = dyn_cast_or_null<Expr>(S))
1702 if (IgnoreNonTypeDependent && !E->isTypeDependent())
1703 return true;
1704 return super::TraverseStmt(S, Q);
1705 }
1706
1707 bool TraverseTypeLoc(TypeLoc TL) {
1708 if (IgnoreNonTypeDependent && !TL.isNull() &&
1709 !TL.getType()->isDependentType())
1710 return true;
1711 return super::TraverseTypeLoc(TL);
1712 }
1713
Richard Smith6056d5e2014-02-09 00:54:43 +00001714 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1715 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1716 }
1717
John McCalla020a012010-10-20 05:44:58 +00001718 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00001719 // For a best-effort search, keep looking until we find a location.
1720 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00001721 }
1722
1723 bool TraverseTemplateName(TemplateName N) {
1724 if (TemplateTemplateParmDecl *PD =
1725 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001726 if (Matches(PD->getDepth()))
1727 return false;
John McCalla020a012010-10-20 05:44:58 +00001728 return super::TraverseTemplateName(N);
1729 }
1730
1731 bool VisitDeclRefExpr(DeclRefExpr *E) {
1732 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001733 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1734 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001735 return false;
John McCalla020a012010-10-20 05:44:58 +00001736 return super::VisitDeclRefExpr(E);
1737 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001738
1739 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1740 return TraverseType(T->getReplacementType());
1741 }
1742
1743 bool
1744 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1745 return TraverseTemplateArgument(T->getArgumentPack());
1746 }
1747
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001748 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1749 return TraverseType(T->getInjectedSpecializationType());
1750 }
John McCalla020a012010-10-20 05:44:58 +00001751};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001752} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001753
Douglas Gregor972fe532011-05-10 18:27:06 +00001754/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001755/// list.
1756static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001757DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00001758 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00001759 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001760 return Checker.Match;
1761}
1762
Douglas Gregor972fe532011-05-10 18:27:06 +00001763// Find the source range corresponding to the named type in the given
1764// nested-name-specifier, if any.
1765static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1766 QualType T,
1767 const CXXScopeSpec &SS) {
1768 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1769 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1770 if (const Type *CurType = NNS->getAsType()) {
1771 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1772 return NNSLoc.getTypeLoc().getSourceRange();
1773 } else
1774 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001775
Douglas Gregor972fe532011-05-10 18:27:06 +00001776 NNSLoc = NNSLoc.getPrefix();
1777 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001778
Douglas Gregor972fe532011-05-10 18:27:06 +00001779 return SourceRange();
1780}
1781
Mike Stump11289f42009-09-09 15:08:12 +00001782/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001783/// specifier, returning the template parameter list that applies to the
1784/// name.
1785///
1786/// \param DeclStartLoc the start of the declaration that has a scope
1787/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001788///
Douglas Gregor972fe532011-05-10 18:27:06 +00001789/// \param DeclLoc The location of the declaration itself.
1790///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001791/// \param SS the scope specifier that will be matched to the given template
1792/// parameter lists. This scope specifier precedes a qualified name that is
1793/// being declared.
1794///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001795/// \param TemplateId The template-id following the scope specifier, if there
1796/// is one. Used to check for a missing 'template<>'.
1797///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001798/// \param ParamLists the template parameter lists, from the outermost to the
1799/// innermost template parameter lists.
1800///
John McCalle820e5e2010-04-13 20:37:33 +00001801/// \param IsFriend Whether to apply the slightly different rules for
1802/// matching template parameters to scope specifiers in friend
1803/// declarations.
1804///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001805/// \param IsExplicitSpecialization will be set true if the entity being
1806/// declared is an explicit specialization, false otherwise.
1807///
Mike Stump11289f42009-09-09 15:08:12 +00001808/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001809/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001810/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001811/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001812/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001813/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001814TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1815 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001816 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001817 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1818 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001819 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001820 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001821
Douglas Gregor972fe532011-05-10 18:27:06 +00001822 // The sequence of nested types to which we will match up the template
1823 // parameter lists. We first build this list by starting with the type named
1824 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001825 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001826 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001827 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00001828 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001829 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1830 T = Context.getTypeDeclType(Record);
1831 else
1832 T = QualType(SS.getScopeRep()->getAsType(), 0);
1833 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001834
Douglas Gregor972fe532011-05-10 18:27:06 +00001835 // If we found an explicit specialization that prevents us from needing
1836 // 'template<>' headers, this will be set to the location of that
1837 // explicit specialization.
1838 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001839
Douglas Gregor972fe532011-05-10 18:27:06 +00001840 while (!T.isNull()) {
1841 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001842
Douglas Gregor972fe532011-05-10 18:27:06 +00001843 // Retrieve the parent of a record type.
1844 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1845 // If this type is an explicit specialization, we're done.
1846 if (ClassTemplateSpecializationDecl *Spec
1847 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00001848 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001849 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1850 ExplicitSpecLoc = Spec->getLocation();
1851 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001852 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001853 } else if (Record->getTemplateSpecializationKind()
1854 == TSK_ExplicitSpecialization) {
1855 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001856 break;
1857 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001858
Douglas Gregor972fe532011-05-10 18:27:06 +00001859 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1860 T = Context.getTypeDeclType(Parent);
1861 else
1862 T = QualType();
1863 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001864 }
1865
Douglas Gregor972fe532011-05-10 18:27:06 +00001866 if (const TemplateSpecializationType *TST
1867 = T->getAs<TemplateSpecializationType>()) {
1868 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1869 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1870 T = Context.getTypeDeclType(Parent);
1871 else
1872 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001873 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001874 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001875 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001876
Douglas Gregor972fe532011-05-10 18:27:06 +00001877 // Look one step prior in a dependent template specialization type.
1878 if (const DependentTemplateSpecializationType *DependentTST
1879 = T->getAs<DependentTemplateSpecializationType>()) {
1880 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1881 T = QualType(NNS->getAsType(), 0);
1882 else
1883 T = QualType();
1884 continue;
1885 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001886
Douglas Gregor972fe532011-05-10 18:27:06 +00001887 // Look one step prior in a dependent name type.
1888 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1889 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1890 T = QualType(NNS->getAsType(), 0);
1891 else
1892 T = QualType();
1893 continue;
1894 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001895
Douglas Gregor972fe532011-05-10 18:27:06 +00001896 // Retrieve the parent of an enumeration type.
1897 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1898 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1899 // check here.
1900 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001901
Douglas Gregor972fe532011-05-10 18:27:06 +00001902 // Get to the parent type.
1903 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1904 T = Context.getTypeDeclType(Parent);
1905 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00001906 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00001907 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001908 }
Mike Stump11289f42009-09-09 15:08:12 +00001909
Douglas Gregor972fe532011-05-10 18:27:06 +00001910 T = QualType();
1911 }
1912 // Reverse the nested types list, since we want to traverse from the outermost
1913 // to the innermost while checking template-parameter-lists.
1914 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001915
Douglas Gregor972fe532011-05-10 18:27:06 +00001916 // C++0x [temp.expl.spec]p17:
1917 // A member or a member template may be nested within many
1918 // enclosing class templates. In an explicit specialization for
1919 // such a member, the member declaration shall be preceded by a
1920 // template<> for each enclosing class template that is
1921 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001922 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001923
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001924 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001925 if (SawNonEmptyTemplateParameterList) {
1926 Diag(DeclLoc, diag::err_specialize_member_of_template)
1927 << !Recovery << Range;
1928 Invalid = true;
1929 IsExplicitSpecialization = false;
1930 return true;
1931 }
1932
1933 return false;
1934 };
1935
1936 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1937 // Check that we can have an explicit specialization here.
1938 if (CheckExplicitSpecialization(Range, true))
1939 return true;
1940
1941 // We don't have a template header, but we should.
1942 SourceLocation ExpectedTemplateLoc;
1943 if (!ParamLists.empty())
1944 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1945 else
1946 ExpectedTemplateLoc = DeclStartLoc;
1947
1948 Diag(DeclLoc, diag::err_template_spec_needs_header)
1949 << Range
1950 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1951 return false;
1952 };
1953
Douglas Gregor972fe532011-05-10 18:27:06 +00001954 unsigned ParamIdx = 0;
1955 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1956 ++TypeIdx) {
1957 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00001958
Douglas Gregor972fe532011-05-10 18:27:06 +00001959 // Whether we expect a 'template<>' header.
1960 bool NeedEmptyTemplateHeader = false;
1961
1962 // Whether we expect a template header with parameters.
1963 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001964
Douglas Gregor972fe532011-05-10 18:27:06 +00001965 // For a dependent type, the set of template parameters that we
1966 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001967 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001968
Douglas Gregor373af9b2011-05-11 23:26:17 +00001969 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00001970 // A member or a member template may be nested within many enclosing
1971 // class templates. In an explicit specialization for such a member, the
1972 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00001973 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001974 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1975 if (ClassTemplatePartialSpecializationDecl *Partial
1976 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1977 ExpectedTemplateParams = Partial->getTemplateParameters();
1978 NeedNonemptyTemplateHeader = true;
1979 } else if (Record->isDependentType()) {
1980 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001981 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001982 ->getTemplateParameters();
1983 NeedNonemptyTemplateHeader = true;
1984 }
1985 } else if (ClassTemplateSpecializationDecl *Spec
1986 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1987 // C++0x [temp.expl.spec]p4:
1988 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00001989 // in the same manner as members of normal classes, and not using
1990 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00001991 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1992 NeedEmptyTemplateHeader = true;
1993 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001994 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001995 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00001996 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001997 != TSK_ExplicitSpecialization &&
1998 TypeIdx == NumTypes - 1)
1999 IsExplicitSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002000
Douglas Gregor373af9b2011-05-11 23:26:17 +00002001 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002002 }
2003 } else if (const TemplateSpecializationType *TST
2004 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002005 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002006 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002007 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002008 }
2009 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2010 // FIXME: We actually could/should check the template arguments here
2011 // against the corresponding template parameter list.
2012 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002013 }
2014
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002015 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002016 // In an explicit specialization declaration for a member of a class
2017 // template or a member template that ap- pears in namespace scope, the
2018 // member template and some of its enclosing class templates may remain
2019 // unspecialized, except that the declaration shall not explicitly
2020 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002021 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002022 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002023 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002024 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2025 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002026 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002027 } else
2028 SawNonEmptyTemplateParameterList = true;
2029 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002030
Douglas Gregor972fe532011-05-10 18:27:06 +00002031 if (NeedEmptyTemplateHeader) {
2032 // If we're on the last of the types, and we need a 'template<>' header
2033 // here, then it's an explicit specialization.
2034 if (TypeIdx == NumTypes - 1)
2035 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002036
2037 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002038 if (ParamLists[ParamIdx]->size() > 0) {
2039 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002040 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002041 diag::err_template_param_list_matches_nontemplate)
2042 << T
2043 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2044 ParamLists[ParamIdx]->getRAngleLoc())
2045 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2046 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002047 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002048 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002049
Douglas Gregor972fe532011-05-10 18:27:06 +00002050 // Consume this template header.
2051 ++ParamIdx;
2052 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002053 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002054
2055 if (!IsFriend)
2056 if (DiagnoseMissingExplicitSpecialization(
2057 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002058 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002059
Douglas Gregor972fe532011-05-10 18:27:06 +00002060 continue;
2061 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002062
Douglas Gregor972fe532011-05-10 18:27:06 +00002063 if (NeedNonemptyTemplateHeader) {
2064 // In friend declarations we can have template-ids which don't
2065 // depend on the corresponding template parameter lists. But
2066 // assume that empty parameter lists are supposed to match this
2067 // template-id.
2068 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002069 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002070 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002071 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002072 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002073 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002074 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002075
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002076 if (ParamIdx < ParamLists.size()) {
2077 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002078 if (ExpectedTemplateParams &&
2079 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2080 ExpectedTemplateParams,
2081 true, TPL_TemplateMatch))
2082 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002083
Douglas Gregor972fe532011-05-10 18:27:06 +00002084 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002085 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002086 TPC_ClassTemplateMember))
2087 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002088
Douglas Gregor972fe532011-05-10 18:27:06 +00002089 ++ParamIdx;
2090 continue;
2091 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002092
Douglas Gregor972fe532011-05-10 18:27:06 +00002093 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2094 << T
2095 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2096 Invalid = true;
2097 continue;
2098 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002099 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002100
Douglas Gregord8d297c2009-07-21 23:53:31 +00002101 // If there were at least as many template-ids as there were template
2102 // parameter lists, then there are no template parameter lists remaining for
2103 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002104 if (ParamIdx >= ParamLists.size()) {
2105 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002106 // We don't have a template header for the declaration itself, but we
2107 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002108 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00002109 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2110 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002111
2112 // Fabricate an empty template parameter list for the invented header.
2113 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002114 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002115 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002116 }
2117
Craig Topperc3ec1492014-05-26 06:22:03 +00002118 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002119 }
Mike Stump11289f42009-09-09 15:08:12 +00002120
Douglas Gregord8d297c2009-07-21 23:53:31 +00002121 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002122 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002123 bool HasAnyExplicitSpecHeader = false;
2124 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002125 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002126 if (ParamLists[I]->size() == 0)
2127 HasAnyExplicitSpecHeader = true;
2128 else
2129 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002130 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002131
Douglas Gregor972fe532011-05-10 18:27:06 +00002132 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002133 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2134 : diag::err_template_spec_extra_headers)
2135 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2136 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002137
2138 // If there was a specialization somewhere, such that 'template<>' is
2139 // not required, and there were any 'template<>' headers, note where the
2140 // specialization occurred.
2141 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002142 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002143 diag::note_explicit_template_spec_does_not_need_header)
2144 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002145
Douglas Gregor972fe532011-05-10 18:27:06 +00002146 // We have a template parameter list with no corresponding scope, which
2147 // means that the resulting template declaration can't be instantiated
2148 // properly (we'll end up with dependent nodes when we shouldn't).
2149 if (!AllExplicitSpecHeaders)
2150 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002151 }
Mike Stump11289f42009-09-09 15:08:12 +00002152
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002153 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002154 // In an explicit specialization declaration for a member of a class
2155 // template or a member template that ap- pears in namespace scope, the
2156 // member template and some of its enclosing class templates may remain
2157 // unspecialized, except that the declaration shall not explicitly
2158 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002159 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002160 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002161 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2162 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002163 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002164
Douglas Gregord8d297c2009-07-21 23:53:31 +00002165 // Return the last template parameter list, which corresponds to the
2166 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002167 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002168}
2169
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002170void Sema::NoteAllFoundTemplates(TemplateName Name) {
2171 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2172 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002173 << (isa<FunctionTemplateDecl>(Template)
2174 ? 0
2175 : isa<ClassTemplateDecl>(Template)
2176 ? 1
2177 : isa<VarTemplateDecl>(Template)
2178 ? 2
2179 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2180 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002181 return;
2182 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002183
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002184 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002185 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002186 IEnd = OST->end();
2187 I != IEnd; ++I)
2188 Diag((*I)->getLocation(), diag::note_template_declared_here)
2189 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002190
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002191 return;
2192 }
2193}
2194
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002195static QualType
2196checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2197 const SmallVectorImpl<TemplateArgument> &Converted,
2198 SourceLocation TemplateLoc,
2199 TemplateArgumentListInfo &TemplateArgs) {
2200 ASTContext &Context = SemaRef.getASTContext();
2201 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002202 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002203 // Specializations of __make_integer_seq<S, T, N> are treated like
2204 // S<T, 0, ..., N-1>.
2205
2206 // C++14 [inteseq.intseq]p1:
2207 // T shall be an integer type.
2208 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2209 SemaRef.Diag(TemplateArgs[1].getLocation(),
2210 diag::err_integer_sequence_integral_element_type);
2211 return QualType();
2212 }
2213
2214 // C++14 [inteseq.make]p1:
2215 // If N is negative the program is ill-formed.
2216 TemplateArgument NumArgsArg = Converted[2];
2217 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2218 if (NumArgs < 0) {
2219 SemaRef.Diag(TemplateArgs[2].getLocation(),
2220 diag::err_integer_sequence_negative_length);
2221 return QualType();
2222 }
2223
2224 QualType ArgTy = NumArgsArg.getIntegralType();
2225 TemplateArgumentListInfo SyntheticTemplateArgs;
2226 // The type argument gets reused as the first template argument in the
2227 // synthetic template argument list.
2228 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2229 // Expand N into 0 ... N-1.
2230 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2231 I < NumArgs; ++I) {
2232 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002233 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2234 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002235 }
2236 // The first template argument will be reused as the template decl that
2237 // our synthetic template arguments will be applied to.
2238 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2239 TemplateLoc, SyntheticTemplateArgs);
2240 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002241
2242 case BTK__type_pack_element:
2243 // Specializations of
2244 // __type_pack_element<Index, T_1, ..., T_N>
2245 // are treated like T_Index.
2246 assert(Converted.size() == 2 &&
2247 "__type_pack_element should be given an index and a parameter pack");
2248
2249 // If the Index is out of bounds, the program is ill-formed.
2250 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2251 llvm::APSInt Index = IndexArg.getAsIntegral();
2252 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2253 "type std::size_t, and hence be non-negative");
2254 if (Index >= Ts.pack_size()) {
2255 SemaRef.Diag(TemplateArgs[0].getLocation(),
2256 diag::err_type_pack_element_out_of_bounds);
2257 return QualType();
2258 }
2259
2260 // We simply return the type at index `Index`.
2261 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2262 return Nth->getAsType();
2263 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002264 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2265}
2266
Douglas Gregordc572a32009-03-30 22:58:21 +00002267QualType Sema::CheckTemplateIdType(TemplateName Name,
2268 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002269 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002270 DependentTemplateName *DTN
2271 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002272 if (DTN && DTN->isIdentifier())
2273 // When building a template-id where the template-name is dependent,
2274 // assume the template is a type template. Either our assumption is
2275 // correct, or the code is ill-formed and will be diagnosed when the
2276 // dependent name is substituted.
2277 return Context.getDependentTemplateSpecializationType(ETK_None,
2278 DTN->getQualifier(),
2279 DTN->getIdentifier(),
2280 TemplateArgs);
2281
Douglas Gregordc572a32009-03-30 22:58:21 +00002282 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002283 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2284 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002285 // We might have a substituted template template parameter pack. If so,
2286 // build a template specialization type for it.
2287 if (Name.getAsSubstTemplateTemplateParmPack())
2288 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002289
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002290 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2291 << Name;
2292 NoteAllFoundTemplates(Name);
2293 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002294 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002295
Douglas Gregorc40290e2009-03-09 23:48:35 +00002296 // Check that the template argument list is well-formed for this
2297 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002298 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002299 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002300 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002301 return QualType();
2302
Douglas Gregorc40290e2009-03-09 23:48:35 +00002303 QualType CanonType;
2304
Douglas Gregor678d76c2011-07-01 01:22:09 +00002305 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002306 if (TypeAliasTemplateDecl *AliasTemplate =
2307 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002308 // Find the canonical type for this type alias template specialization.
2309 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2310 if (Pattern->isInvalidDecl())
2311 return QualType();
2312
2313 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002314 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002315
2316 // Only substitute for the innermost template argument list.
2317 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002318 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002319 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2320 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002321 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002322
Richard Smith802c4b72012-08-23 06:16:52 +00002323 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002324 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002325 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002326 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002327
Richard Smith3f1b5d02011-05-05 21:57:07 +00002328 CanonType = SubstType(Pattern->getUnderlyingType(),
2329 TemplateArgLists, AliasTemplate->getLocation(),
2330 AliasTemplate->getDeclName());
2331 if (CanonType.isNull())
2332 return QualType();
2333 } else if (Name.isDependent() ||
2334 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002335 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002336 // This class template specialization is a dependent
2337 // type. Therefore, its canonical type is another class template
2338 // specialization type that contains all of the converted
2339 // arguments in canonical form. This ensures that, e.g., A<T> and
2340 // A<T, T> have identical types when A is declared as:
2341 //
2342 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00002343 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00002344
2345 // This might work out to be a current instantiation, in which
2346 // case the canonical type needs to be the InjectedClassNameType.
2347 //
2348 // TODO: in theory this could be a simple hashtable lookup; most
2349 // changes to CurContext don't change the set of current
2350 // instantiations.
2351 if (isa<ClassTemplateDecl>(Template)) {
2352 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2353 // If we get out to a namespace, we're done.
2354 if (Ctx->isFileContext()) break;
2355
2356 // If this isn't a record, keep looking.
2357 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2358 if (!Record) continue;
2359
2360 // Look for one of the two cases with InjectedClassNameTypes
2361 // and check whether it's the same template.
2362 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2363 !Record->getDescribedClassTemplate())
2364 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002365
John McCall2408e322010-04-27 00:57:59 +00002366 // Fetch the injected class name type and check whether its
2367 // injected type is equal to the type we just built.
2368 QualType ICNT = Context.getTypeDeclType(Record);
2369 QualType Injected = cast<InjectedClassNameType>(ICNT)
2370 ->getInjectedSpecializationType();
2371
2372 if (CanonType != Injected->getCanonicalTypeInternal())
2373 continue;
2374
2375 // If so, the canonical type of this TST is the injected
2376 // class name type of the record we just found.
2377 assert(ICNT.isCanonical());
2378 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002379 break;
2380 }
2381 }
Mike Stump11289f42009-09-09 15:08:12 +00002382 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002383 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002384 // Find the class template specialization declaration that
2385 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002386 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002387 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002388 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002389 if (!Decl) {
2390 // This is the first time we have referenced this class template
2391 // specialization. Create the canonical declaration and add it to
2392 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002393 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002394 ClassTemplate->getTemplatedDecl()->getTagKind(),
2395 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002396 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002397 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002398 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00002399 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002400 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002401 if (ClassTemplate->isOutOfLine())
2402 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002403 }
2404
Chandler Carruth2acfb222013-09-27 22:14:40 +00002405 // Diagnose uses of this specialization.
2406 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2407
Douglas Gregorc40290e2009-03-09 23:48:35 +00002408 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002409 assert(isa<RecordType>(CanonType) &&
2410 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002411 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2412 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2413 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002414 }
Mike Stump11289f42009-09-09 15:08:12 +00002415
Douglas Gregorc40290e2009-03-09 23:48:35 +00002416 // Build the fully-sugared type for this class template
2417 // specialization, which refers back to the class template
2418 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002419 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002420}
2421
John McCallfaf5fb42010-08-26 23:41:50 +00002422TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002423Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002424 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002425 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002426 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002427 SourceLocation RAngleLoc,
2428 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002429 if (SS.isInvalid())
2430 return true;
2431
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002432 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002433
Douglas Gregorc40290e2009-03-09 23:48:35 +00002434 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002435 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002436 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002437
Douglas Gregor5a064722011-02-28 17:23:35 +00002438 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002439 QualType T
2440 = Context.getDependentTemplateSpecializationType(ETK_None,
2441 DTN->getQualifier(),
2442 DTN->getIdentifier(),
2443 TemplateArgs);
2444 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002445 TypeLocBuilder TLB;
2446 DependentTemplateSpecializationTypeLoc SpecTL
2447 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002448 SpecTL.setElaboratedKeywordLoc(SourceLocation());
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 Gregor5a064722011-02-28 17:23:35 +00002452 SpecTL.setLAngleLoc(LAngleLoc);
2453 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +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 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002458
John McCall6b51f282009-11-23 01:53:49 +00002459 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002460
2461 if (Result.isNull())
2462 return true;
2463
Douglas Gregore7c20652011-03-02 00:47:37 +00002464 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002465 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002466 TemplateSpecializationTypeLoc SpecTL
2467 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002468 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002469 SpecTL.setTemplateNameLoc(TemplateLoc);
2470 SpecTL.setLAngleLoc(LAngleLoc);
2471 SpecTL.setRAngleLoc(RAngleLoc);
2472 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2473 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002474
Abramo Bagnara4244b432012-01-27 08:46:19 +00002475 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2476 // constructor or destructor name (in such a case, the scope specifier
2477 // will be attached to the enclosing Decl or Expr node).
2478 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002479 // Create an elaborated-type-specifier containing the nested-name-specifier.
2480 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2481 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002482 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002483 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2484 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002485
Douglas Gregore7c20652011-03-02 00:47:37 +00002486 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002487}
John McCall06f6fe8d2009-09-04 01:14:41 +00002488
Douglas Gregore7c20652011-03-02 00:47:37 +00002489TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002490 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002491 SourceLocation TagLoc,
2492 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002493 SourceLocation TemplateKWLoc,
2494 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002495 SourceLocation TemplateLoc,
2496 SourceLocation LAngleLoc,
2497 ASTTemplateArgsPtr TemplateArgsIn,
2498 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002499 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002500
Douglas Gregore7c20652011-03-02 00:47:37 +00002501 // Translate the parser's template argument list in our AST format.
2502 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2503 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002504
Douglas Gregore7c20652011-03-02 00:47:37 +00002505 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002506 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002507 ElaboratedTypeKeyword Keyword
2508 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002509
Douglas Gregore7c20652011-03-02 00:47:37 +00002510 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2511 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00002512 DTN->getQualifier(),
2513 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00002514 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002515
2516 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00002517 TypeLocBuilder TLB;
2518 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002519 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2520 SpecTL.setElaboratedKeywordLoc(TagLoc);
2521 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002522 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002523 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002524 SpecTL.setLAngleLoc(LAngleLoc);
2525 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002526 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2527 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2528 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2529 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002530
2531 if (TypeAliasTemplateDecl *TAT =
2532 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2533 // C++0x [dcl.type.elab]p2:
2534 // If the identifier resolves to a typedef-name or the simple-template-id
2535 // resolves to an alias template specialization, the
2536 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00002537 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
2538 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002539 Diag(TAT->getLocation(), diag::note_declared_at);
2540 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002541
Douglas Gregore7c20652011-03-02 00:47:37 +00002542 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2543 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002544 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002545
Douglas Gregore7c20652011-03-02 00:47:37 +00002546 // Check the tag kind
2547 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002548 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002549
John McCalld8fe9af2009-09-08 17:47:29 +00002550 IdentifierInfo *Id = D->getIdentifier();
2551 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00002552
Richard Trieucaa33d32011-06-10 03:11:26 +00002553 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002554 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002555 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002556 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002557 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002558 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002559 }
2560 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002561
Douglas Gregore7c20652011-03-02 00:47:37 +00002562 // Provide source-location information for the template specialization.
2563 TypeLocBuilder TLB;
2564 TemplateSpecializationTypeLoc SpecTL
2565 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002566 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002567 SpecTL.setTemplateNameLoc(TemplateLoc);
2568 SpecTL.setLAngleLoc(LAngleLoc);
2569 SpecTL.setRAngleLoc(RAngleLoc);
2570 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2571 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002572
Douglas Gregore7c20652011-03-02 00:47:37 +00002573 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002574 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002575 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2576 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002577 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002578 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2579 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002580}
2581
Larisse Voufo39a1e502013-08-06 01:03:05 +00002582static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2583 NamedDecl *PrevDecl,
2584 SourceLocation Loc,
2585 bool IsPartialSpecialization);
2586
2587static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002588
Richard Smith300e0c32013-09-24 04:49:23 +00002589static bool isTemplateArgumentTemplateParameter(
2590 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2591 switch (Arg.getKind()) {
2592 case TemplateArgument::Null:
2593 case TemplateArgument::NullPtr:
2594 case TemplateArgument::Integral:
2595 case TemplateArgument::Declaration:
2596 case TemplateArgument::Pack:
2597 case TemplateArgument::TemplateExpansion:
2598 return false;
2599
2600 case TemplateArgument::Type: {
2601 QualType Type = Arg.getAsType();
2602 const TemplateTypeParmType *TPT =
2603 Arg.getAsType()->getAs<TemplateTypeParmType>();
2604 return TPT && !Type.hasQualifiers() &&
2605 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2606 }
2607
2608 case TemplateArgument::Expression: {
2609 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2610 if (!DRE || !DRE->getDecl())
2611 return false;
2612 const NonTypeTemplateParmDecl *NTTP =
2613 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2614 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2615 }
2616
2617 case TemplateArgument::Template:
2618 const TemplateTemplateParmDecl *TTP =
2619 dyn_cast_or_null<TemplateTemplateParmDecl>(
2620 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2621 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2622 }
2623 llvm_unreachable("unexpected kind of template argument");
2624}
2625
2626static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2627 ArrayRef<TemplateArgument> Args) {
2628 if (Params->size() != Args.size())
2629 return false;
2630
2631 unsigned Depth = Params->getDepth();
2632
2633 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2634 TemplateArgument Arg = Args[I];
2635
2636 // If the parameter is a pack expansion, the argument must be a pack
2637 // whose only element is a pack expansion.
2638 if (Params->getParam(I)->isParameterPack()) {
2639 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2640 !Arg.pack_begin()->isPackExpansion())
2641 return false;
2642 Arg = Arg.pack_begin()->getPackExpansionPattern();
2643 }
2644
2645 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2646 return false;
2647 }
2648
2649 return true;
2650}
2651
Richard Smith4b55a9c2014-04-17 03:29:33 +00002652/// Convert the parser's template argument list representation into our form.
2653static TemplateArgumentListInfo
2654makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2655 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2656 TemplateId.RAngleLoc);
2657 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2658 TemplateId.NumArgs);
2659 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2660 return TemplateArgs;
2661}
2662
Richard Smith0e617ec2016-12-27 07:56:27 +00002663template<typename PartialSpecDecl>
2664static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
2665 if (Partial->getDeclContext()->isDependentContext())
2666 return;
2667
2668 // FIXME: Get the TDK from deduction in order to provide better diagnostics
2669 // for non-substitution-failure issues?
2670 TemplateDeductionInfo Info(Partial->getLocation());
2671 if (S.isMoreSpecializedThanPrimary(Partial, Info))
2672 return;
2673
2674 auto *Template = Partial->getSpecializedTemplate();
2675 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00002676 diag::ext_partial_spec_not_more_specialized_than_primary)
2677 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00002678
2679 if (Info.hasSFINAEDiagnostic()) {
2680 PartialDiagnosticAt Diag = {SourceLocation(),
2681 PartialDiagnostic::NullDiagnostic()};
2682 Info.takeSFINAEDiagnostic(Diag);
2683 SmallString<128> SFINAEArgString;
2684 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
2685 S.Diag(Diag.first,
2686 diag::note_partial_spec_not_more_specialized_than_primary)
2687 << SFINAEArgString;
2688 }
2689
2690 S.Diag(Template->getLocation(), diag::note_template_decl_here);
2691}
2692
Richard Smith57aae072016-12-28 02:37:25 +00002693template<typename PartialSpecDecl>
2694static void checkTemplatePartialSpecialization(Sema &S,
2695 PartialSpecDecl *Partial) {
2696 // C++1z [temp.class.spec]p8: (DR1495)
2697 // - The specialization shall be more specialized than the primary
2698 // template (14.5.5.2).
2699 checkMoreSpecializedThanPrimary(S, Partial);
2700
2701 // C++ [temp.class.spec]p8: (DR1315)
2702 // - Each template-parameter shall appear at least once in the
2703 // template-id outside a non-deduced context.
2704 // C++1z [temp.class.spec.match]p3 (P0127R2)
2705 // If the template arguments of a partial specialization cannot be
2706 // deduced because of the structure of its template-parameter-list
2707 // and the template-id, the program is ill-formed.
2708 auto *TemplateParams = Partial->getTemplateParameters();
2709 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2710 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2711 TemplateParams->getDepth(), DeducibleParams);
2712
2713 if (!DeducibleParams.all()) {
2714 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
2715 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
2716 << isa<VarTemplatePartialSpecializationDecl>(Partial)
2717 << (NumNonDeducible > 1)
2718 << SourceRange(Partial->getLocation(),
2719 Partial->getTemplateArgsAsWritten()->RAngleLoc);
2720 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2721 if (!DeducibleParams[I]) {
2722 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2723 if (Param->getDeclName())
2724 S.Diag(Param->getLocation(),
2725 diag::note_partial_spec_unused_parameter)
2726 << Param->getDeclName();
2727 else
2728 S.Diag(Param->getLocation(),
2729 diag::note_partial_spec_unused_parameter)
2730 << "(anonymous)";
2731 }
2732 }
2733 }
2734}
2735
2736void Sema::CheckTemplatePartialSpecialization(
2737 ClassTemplatePartialSpecializationDecl *Partial) {
2738 checkTemplatePartialSpecialization(*this, Partial);
2739}
2740
2741void Sema::CheckTemplatePartialSpecialization(
2742 VarTemplatePartialSpecializationDecl *Partial) {
2743 checkTemplatePartialSpecialization(*this, Partial);
2744}
2745
Larisse Voufo39a1e502013-08-06 01:03:05 +00002746DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002747 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002748 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002749 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002750 // D must be variable template id.
2751 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2752 "Variable template specialization is declared with a template it.");
2753
2754 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002755 TemplateArgumentListInfo TemplateArgs =
2756 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002757 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2758 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2759 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002760
Richard Smithbeef3452014-01-16 23:39:20 +00002761 TemplateName Name = TemplateId->Template.get();
2762
2763 // The template-id must name a variable template.
2764 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002765 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2766 if (!VarTemplate) {
2767 NamedDecl *FnTemplate;
2768 if (auto *OTS = Name.getAsOverloadedTemplate())
2769 FnTemplate = *OTS->begin();
2770 else
2771 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2772 if (FnTemplate)
2773 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2774 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002775 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2776 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002777 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002778
2779 // Check for unexpanded parameter packs in any of the template arguments.
2780 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2781 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2782 UPPC_PartialSpecialization))
2783 return true;
2784
2785 // Check that the template argument list is well-formed for this
2786 // template.
2787 SmallVector<TemplateArgument, 4> Converted;
2788 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2789 false, Converted))
2790 return true;
2791
Larisse Voufo39a1e502013-08-06 01:03:05 +00002792 // Find the variable template (partial) specialization declaration that
2793 // corresponds to these arguments.
2794 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00002795 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
2796 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002797 return true;
2798
Richard Smith57aae072016-12-28 02:37:25 +00002799 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
2800 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002801 bool InstantiationDependent;
2802 if (!Name.isDependent() &&
2803 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00002804 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00002805 InstantiationDependent)) {
2806 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2807 << VarTemplate->getDeclName();
2808 IsPartialSpecialization = false;
2809 }
Richard Smith300e0c32013-09-24 04:49:23 +00002810
2811 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2812 Converted)) {
2813 // C++ [temp.class.spec]p9b3:
2814 //
2815 // -- The argument list of the specialization shall not be identical
2816 // to the implicit argument list of the primary template.
2817 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2818 << /*variable template*/ 1
2819 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2820 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2821 // FIXME: Recover from this by treating the declaration as a redeclaration
2822 // of the primary template.
2823 return true;
2824 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002825 }
2826
Craig Topperc3ec1492014-05-26 06:22:03 +00002827 void *InsertPos = nullptr;
2828 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002829
2830 if (IsPartialSpecialization)
2831 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002832 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002833 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002834 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002835
Craig Topperc3ec1492014-05-26 06:22:03 +00002836 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002837
2838 // Check whether we can declare a variable template specialization in
2839 // the current scope.
2840 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2841 TemplateNameLoc,
2842 IsPartialSpecialization))
2843 return true;
2844
2845 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2846 // Since the only prior variable template specialization with these
2847 // arguments was referenced but not declared, reuse that
2848 // declaration node as our own, updating its source location and
2849 // the list of outer template parameters to reflect our new declaration.
2850 Specialization = PrevDecl;
2851 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002852 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002853 } else if (IsPartialSpecialization) {
2854 // Create a new class template partial specialization declaration node.
2855 VarTemplatePartialSpecializationDecl *PrevPartial =
2856 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002857 VarTemplatePartialSpecializationDecl *Partial =
2858 VarTemplatePartialSpecializationDecl::Create(
2859 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2860 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00002861 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002862
2863 if (!PrevPartial)
2864 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2865 Specialization = Partial;
2866
2867 // If we are providing an explicit specialization of a member variable
2868 // template specialization, make a note of that.
2869 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002870 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002871
Richard Smith57aae072016-12-28 02:37:25 +00002872 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002873 } else {
2874 // Create a new class template specialization declaration node for
2875 // this explicit specialization or friend declaration.
2876 Specialization = VarTemplateSpecializationDecl::Create(
2877 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00002878 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002879 Specialization->setTemplateArgsInfo(TemplateArgs);
2880
2881 if (!PrevDecl)
2882 VarTemplate->AddSpecialization(Specialization, InsertPos);
2883 }
2884
2885 // C++ [temp.expl.spec]p6:
2886 // If a template, a member template or the member of a class template is
2887 // explicitly specialized then that specialization shall be declared
2888 // before the first use of that specialization that would cause an implicit
2889 // instantiation to take place, in every translation unit in which such a
2890 // use occurs; no diagnostic is required.
2891 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2892 bool Okay = false;
2893 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2894 // Is there any previous explicit specialization declaration?
2895 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2896 Okay = true;
2897 break;
2898 }
2899 }
2900
2901 if (!Okay) {
2902 SourceRange Range(TemplateNameLoc, RAngleLoc);
2903 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2904 << Name << Range;
2905
2906 Diag(PrevDecl->getPointOfInstantiation(),
2907 diag::note_instantiation_required_here)
2908 << (PrevDecl->getTemplateSpecializationKind() !=
2909 TSK_ImplicitInstantiation);
2910 return true;
2911 }
2912 }
2913
2914 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2915 Specialization->setLexicalDeclContext(CurContext);
2916
2917 // Add the specialization into its lexical context, so that it can
2918 // be seen when iterating through the list of declarations in that
2919 // context. However, specializations are not found by name lookup.
2920 CurContext->addDecl(Specialization);
2921
2922 // Note that this is an explicit specialization.
2923 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2924
2925 if (PrevDecl) {
2926 // Check that this isn't a redefinition of this specialization,
2927 // merging with previous declarations.
2928 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2929 ForRedeclaration);
2930 PrevSpec.addDecl(PrevDecl);
2931 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002932 } else if (Specialization->isStaticDataMember() &&
2933 Specialization->isOutOfLine()) {
2934 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002935 }
2936
2937 // Link instantiations of static data members back to the template from
2938 // which they were instantiated.
2939 if (Specialization->isStaticDataMember())
2940 Specialization->setInstantiationOfStaticDataMember(
2941 VarTemplate->getTemplatedDecl(),
2942 Specialization->getSpecializationKind());
2943
2944 return Specialization;
2945}
2946
2947namespace {
2948/// \brief A partial specialization whose template arguments have matched
2949/// a given template-id.
2950struct PartialSpecMatchResult {
2951 VarTemplatePartialSpecializationDecl *Partial;
2952 TemplateArgumentList *Args;
2953};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002954} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00002955
2956DeclResult
2957Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2958 SourceLocation TemplateNameLoc,
2959 const TemplateArgumentListInfo &TemplateArgs) {
2960 assert(Template && "A variable template id without template?");
2961
2962 // Check that the template argument list is well-formed for this template.
2963 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002964 if (CheckTemplateArgumentList(
2965 Template, TemplateNameLoc,
2966 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002967 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002968 return true;
2969
2970 // Find the variable template specialization declaration that
2971 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002972 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002973 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00002974 Converted, InsertPos)) {
2975 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002976 // If we already have a variable template specialization, return it.
2977 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00002978 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002979
2980 // This is the first time we have referenced this variable template
2981 // specialization. Create the canonical declaration and add it to
2982 // the set of specializations, based on the closest partial specialization
2983 // that it represents. That is,
2984 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2985 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002986 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002987 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2988 bool AmbiguousPartialSpec = false;
2989 typedef PartialSpecMatchResult MatchResult;
2990 SmallVector<MatchResult, 4> Matched;
2991 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002992 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2993 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002994
2995 // 1. Attempt to find the closest partial specialization that this
2996 // specializes, if any.
2997 // If any of the template arguments is dependent, then this is probably
2998 // a placeholder for an incomplete declarative context; which must be
2999 // complete by instantiation time. Thus, do not search through the partial
3000 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003001 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3002 // Perhaps better after unification of DeduceTemplateArguments() and
3003 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003004 bool InstantiationDependent = false;
3005 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3006 TemplateArgs, InstantiationDependent)) {
3007
3008 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3009 Template->getPartialSpecializations(PartialSpecs);
3010
3011 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3012 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3013 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3014
3015 if (TemplateDeductionResult Result =
3016 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3017 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003018 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003019 FailedCandidates.addCandidate().set(
3020 DeclAccessPair::make(Template, AS_public), Partial,
3021 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003022 (void)Result;
3023 } else {
3024 Matched.push_back(PartialSpecMatchResult());
3025 Matched.back().Partial = Partial;
3026 Matched.back().Args = Info.take();
3027 }
3028 }
3029
Larisse Voufo39a1e502013-08-06 01:03:05 +00003030 if (Matched.size() >= 1) {
3031 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3032 if (Matched.size() == 1) {
3033 // -- If exactly one matching specialization is found, the
3034 // instantiation is generated from that specialization.
3035 // We don't need to do anything for this.
3036 } else {
3037 // -- If more than one matching specialization is found, the
3038 // partial order rules (14.5.4.2) are used to determine
3039 // whether one of the specializations is more specialized
3040 // than the others. If none of the specializations is more
3041 // specialized than all of the other matching
3042 // specializations, then the use of the variable template is
3043 // ambiguous and the program is ill-formed.
3044 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3045 PEnd = Matched.end();
3046 P != PEnd; ++P) {
3047 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3048 PointOfInstantiation) ==
3049 P->Partial)
3050 Best = P;
3051 }
3052
3053 // Determine if the best partial specialization is more specialized than
3054 // the others.
3055 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3056 PEnd = Matched.end();
3057 P != PEnd; ++P) {
3058 if (P != Best && getMoreSpecializedPartialSpecialization(
3059 P->Partial, Best->Partial,
3060 PointOfInstantiation) != Best->Partial) {
3061 AmbiguousPartialSpec = true;
3062 break;
3063 }
3064 }
3065 }
3066
3067 // Instantiate using the best variable template partial specialization.
3068 InstantiationPattern = Best->Partial;
3069 InstantiationArgs = Best->Args;
3070 } else {
3071 // -- If no match is found, the instantiation is generated
3072 // from the primary template.
3073 // InstantiationPattern = Template->getTemplatedDecl();
3074 }
3075 }
3076
Larisse Voufo39a1e502013-08-06 01:03:05 +00003077 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00003078 // Note that we do not instantiate a definition until we see an odr-use
3079 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003080 // FIXME: LateAttrs et al.?
3081 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3082 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3083 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3084 if (!Decl)
3085 return true;
3086
3087 if (AmbiguousPartialSpec) {
3088 // Partial ordering did not produce a clear winner. Complain.
3089 Decl->setInvalidDecl();
3090 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3091 << Decl;
3092
3093 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00003094 for (MatchResult P : Matched)
3095 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3096 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3097 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003098 return true;
3099 }
3100
3101 if (VarTemplatePartialSpecializationDecl *D =
3102 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3103 Decl->setInstantiationOf(D, InstantiationArgs);
3104
Richard Smith6739a102016-05-05 00:56:12 +00003105 checkSpecializationVisibility(TemplateNameLoc, Decl);
3106
Larisse Voufo39a1e502013-08-06 01:03:05 +00003107 assert(Decl && "No variable template specialization?");
3108 return Decl;
3109}
3110
3111ExprResult
3112Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3113 const DeclarationNameInfo &NameInfo,
3114 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3115 const TemplateArgumentListInfo *TemplateArgs) {
3116
3117 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3118 *TemplateArgs);
3119 if (Decl.isInvalid())
3120 return ExprError();
3121
3122 VarDecl *Var = cast<VarDecl>(Decl.get());
3123 if (!Var->getTemplateSpecializationKind())
3124 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3125 NameInfo.getLoc());
3126
3127 // Build an ordinary singleton decl ref.
3128 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003129 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003130}
3131
John McCalldadc5752010-08-24 06:29:42 +00003132ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003133 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003134 LookupResult &R,
3135 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003136 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003137 // FIXME: Can we do any checking at this point? I guess we could check the
3138 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003139 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003140 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003141 // foo<int> could identify a single function unambiguously
3142 // This approach does NOT work, since f<int>(1);
3143 // gets resolved prior to resorting to overload resolution
3144 // i.e., template<class T> void f(double);
3145 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003146
3147 // These should be filtered out by our callers.
3148 assert(!R.empty() && "empty lookup results when building templateid");
3149 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3150
Larisse Voufo39a1e502013-08-06 01:03:05 +00003151 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003152 bool InstantiationDependent;
3153 if (R.getAsSingle<VarTemplateDecl>() &&
3154 !TemplateSpecializationType::anyDependentTemplateArguments(
3155 *TemplateArgs, InstantiationDependent)) {
3156 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3157 R.getAsSingle<VarTemplateDecl>(),
3158 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003159 }
3160
John McCall58cc69d2010-01-27 01:50:18 +00003161 // We don't want lookup warnings at this point.
3162 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003163
John McCalle66edc12009-11-24 19:00:30 +00003164 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003165 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003166 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003167 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003168 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003169 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003170 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003171
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003172 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003173}
3174
John McCalle66edc12009-11-24 19:00:30 +00003175// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003176ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003177Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003178 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003179 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003180 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003181
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003182 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003183 DeclContext *DC;
3184 if (!(DC = computeDeclContext(SS, false)) ||
3185 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003186 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003187 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003188
Douglas Gregor786123d2010-05-21 23:18:07 +00003189 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003190 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003191 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003192 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003193
John McCalle66edc12009-11-24 19:00:30 +00003194 if (R.isAmbiguous())
3195 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003196
John McCalle66edc12009-11-24 19:00:30 +00003197 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003198 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3199 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003200 return ExprError();
3201 }
3202
3203 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003204 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003205 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003206 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003207 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3208 return ExprError();
3209 }
3210
Abramo Bagnara7945c982012-01-27 09:46:47 +00003211 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003212}
3213
Douglas Gregorb67535d2009-03-31 00:43:58 +00003214/// \brief Form a dependent template name.
3215///
3216/// This action forms a dependent template name given the template
3217/// name and its (presumably dependent) scope specifier. For
3218/// example, given "MetaFun::template apply", the scope specifier \p
3219/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3220/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003221TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003222 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003223 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003224 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003225 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003226 bool EnteringContext,
3227 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003228 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3229 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003230 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003231 diag::warn_cxx98_compat_template_outside_of_template :
3232 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003233 << FixItHint::CreateRemoval(TemplateKWLoc);
3234
Craig Topperc3ec1492014-05-26 06:22:03 +00003235 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003236 if (SS.isSet())
3237 LookupCtx = computeDeclContext(SS, EnteringContext);
3238 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003239 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003240 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003241 // C++0x [temp.names]p5:
3242 // If a name prefixed by the keyword template is not the name of
3243 // a template, the program is ill-formed. [Note: the keyword
3244 // template may not be applied to non-template members of class
3245 // templates. -end note ] [ Note: as is the case with the
3246 // typename prefix, the template prefix is allowed in cases
3247 // where it is not strictly necessary; i.e., when the
3248 // nested-name-specifier or the expression on the left of the ->
3249 // or . is not dependent on a template-parameter, or the use
3250 // does not appear in the scope of a template. -end note]
3251 //
3252 // Note: C++03 was more strict here, because it banned the use of
3253 // the "template" keyword prior to a template-name that was not a
3254 // dependent name. C++ DR468 relaxed this requirement (the
3255 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003256 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003257 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003258 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003259 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003260 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003261 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3262 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003263 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3264 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003265 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003266 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003267 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003268 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003269 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003270 << Name.getSourceRange()
3271 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003272 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003273 } else {
3274 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003275 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003276 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003277 }
3278
Aaron Ballman4a979672014-01-03 13:56:08 +00003279 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003280
Douglas Gregor3cf81312009-11-03 23:16:33 +00003281 switch (Name.getKind()) {
3282 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003283 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003284 Name.Identifier));
3285 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003286
Douglas Gregor71395fa2009-11-04 00:56:37 +00003287 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003288 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003289 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003290 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003291
3292 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003293 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003294
Douglas Gregor3cf81312009-11-03 23:16:33 +00003295 default:
3296 break;
3297 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003298
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003299 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003300 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003301 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003302 << Name.getSourceRange()
3303 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003304 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003305}
3306
Mike Stump11289f42009-09-09 15:08:12 +00003307bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003308 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003309 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003310 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003311 QualType ArgType;
3312 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003313
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003314 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003315 switch(Arg.getKind()) {
3316 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003317 // C++ [temp.arg.type]p1:
3318 // A template-argument for a template-parameter which is a
3319 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003320 ArgType = Arg.getAsType();
3321 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003322 break;
3323 case TemplateArgument::Template: {
3324 // We have a template type parameter but the template argument
3325 // is a template without any arguments.
3326 SourceRange SR = AL.getSourceRange();
3327 TemplateName Name = Arg.getAsTemplate();
3328 Diag(SR.getBegin(), diag::err_template_missing_args)
Richard Smith0c062b42017-01-14 02:19:59 +00003329 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003330 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3331 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003332
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003333 return true;
3334 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003335 case TemplateArgument::Expression: {
3336 // We have a template type parameter but the template argument is an
3337 // expression; see if maybe it is missing the "typename" keyword.
3338 CXXScopeSpec SS;
3339 DeclarationNameInfo NameInfo;
3340
3341 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3342 SS.Adopt(ArgExpr->getQualifierLoc());
3343 NameInfo = ArgExpr->getNameInfo();
3344 } else if (DependentScopeDeclRefExpr *ArgExpr =
3345 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3346 SS.Adopt(ArgExpr->getQualifierLoc());
3347 NameInfo = ArgExpr->getNameInfo();
3348 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3349 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003350 if (ArgExpr->isImplicitAccess()) {
3351 SS.Adopt(ArgExpr->getQualifierLoc());
3352 NameInfo = ArgExpr->getMemberNameInfo();
3353 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003354 }
3355
Reid Kleckner377c1592014-06-10 23:29:48 +00003356 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003357 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3358 LookupParsedName(Result, CurScope, &SS);
3359
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003360 if (Result.getAsSingle<TypeDecl>() ||
3361 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003362 LookupResult::NotFoundInCurrentInstantiation) {
3363 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003364 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003365 Diag(Loc, getLangOpts().MSVCCompat
3366 ? diag::ext_ms_template_type_arg_missing_typename
3367 : diag::err_template_arg_must_be_type_suggest)
3368 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003369 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003370
3371 // Recover by synthesizing a type using the location information that we
3372 // already have.
3373 ArgType =
3374 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3375 TypeLocBuilder TLB;
3376 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3377 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3378 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3379 TL.setNameLoc(NameInfo.getLoc());
3380 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3381
3382 // Overwrite our input TemplateArgumentLoc so that we can recover
3383 // properly.
3384 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3385 TemplateArgumentLocInfo(TSI));
3386
3387 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003388 }
3389 }
3390 // fallthrough
3391 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003392 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003393 // We have a template type parameter but the template argument
3394 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003395 SourceRange SR = AL.getSourceRange();
3396 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003397 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003398
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003399 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003400 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003401 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003402
Reid Kleckner377c1592014-06-10 23:29:48 +00003403 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003404 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003405
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003406 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003407 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003408
Douglas Gregore46db902011-06-17 22:11:49 +00003409 // Objective-C ARC:
3410 // If an explicitly-specified template argument type is a lifetime type
3411 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003412 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003413 ArgType->isObjCLifetimeType() &&
3414 !ArgType.getObjCLifetime()) {
3415 Qualifiers Qs;
3416 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3417 ArgType = Context.getQualifiedType(ArgType, Qs);
3418 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003419
Douglas Gregore46db902011-06-17 22:11:49 +00003420 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003421 return false;
3422}
3423
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003424/// \brief Substitute template arguments into the default template argument for
3425/// the given template type parameter.
3426///
3427/// \param SemaRef the semantic analysis object for which we are performing
3428/// the substitution.
3429///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003430/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003431/// for.
3432///
3433/// \param TemplateLoc the location of the template name that started the
3434/// template-id we are checking.
3435///
3436/// \param RAngleLoc the location of the right angle bracket ('>') that
3437/// terminates the template-id.
3438///
3439/// \param Param the template template parameter whose default we are
3440/// substituting into.
3441///
3442/// \param Converted the list of template arguments provided for template
3443/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003444/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003445static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003446SubstDefaultTemplateArgument(Sema &SemaRef,
3447 TemplateDecl *Template,
3448 SourceLocation TemplateLoc,
3449 SourceLocation RAngleLoc,
3450 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003451 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003452 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003453
3454 // If the argument type is dependent, instantiate it now based
3455 // on the previously-computed template arguments.
3456 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003457 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003458 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003459 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003460 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003461 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003462
David Majnemer8b622692016-07-03 21:17:51 +00003463 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003464
3465 // Only substitute for the innermost template argument list.
3466 MultiLevelTemplateArgumentList TemplateArgLists;
3467 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3468 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3469 TemplateArgLists.addOuterTemplateArguments(None);
3470
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003471 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003472 ArgType =
3473 SemaRef.SubstType(ArgType, TemplateArgLists,
3474 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003475 }
3476
3477 return ArgType;
3478}
3479
3480/// \brief Substitute template arguments into the default template argument for
3481/// the given non-type template parameter.
3482///
3483/// \param SemaRef the semantic analysis object for which we are performing
3484/// the substitution.
3485///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003486/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003487/// for.
3488///
3489/// \param TemplateLoc the location of the template name that started the
3490/// template-id we are checking.
3491///
3492/// \param RAngleLoc the location of the right angle bracket ('>') that
3493/// terminates the template-id.
3494///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003495/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003496/// substituting into.
3497///
3498/// \param Converted the list of template arguments provided for template
3499/// parameters that precede \p Param in the template parameter list.
3500///
3501/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003502static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003503SubstDefaultTemplateArgument(Sema &SemaRef,
3504 TemplateDecl *Template,
3505 SourceLocation TemplateLoc,
3506 SourceLocation RAngleLoc,
3507 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003508 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003509 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003510 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003511 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003512 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003513 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003514
David Majnemer8b622692016-07-03 21:17:51 +00003515 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003516
3517 // Only substitute for the innermost template argument list.
3518 MultiLevelTemplateArgumentList TemplateArgLists;
3519 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3520 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3521 TemplateArgLists.addOuterTemplateArguments(None);
3522
Faisal Vali48401eb2015-11-19 19:20:17 +00003523 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3524 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003525 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003526}
3527
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003528/// \brief Substitute template arguments into the default template argument for
3529/// the given template template parameter.
3530///
3531/// \param SemaRef the semantic analysis object for which we are performing
3532/// the substitution.
3533///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003535/// for.
3536///
3537/// \param TemplateLoc the location of the template name that started the
3538/// template-id we are checking.
3539///
3540/// \param RAngleLoc the location of the right angle bracket ('>') that
3541/// terminates the template-id.
3542///
3543/// \param Param the template template parameter whose default we are
3544/// substituting into.
3545///
3546/// \param Converted the list of template arguments provided for template
3547/// parameters that precede \p Param in the template parameter list.
3548///
Simon Pilgrim6905d222016-12-30 22:55:33 +00003549/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00003550/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003551///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003552/// \returns the substituted template argument, or NULL if an error occurred.
3553static TemplateName
3554SubstDefaultTemplateArgument(Sema &SemaRef,
3555 TemplateDecl *Template,
3556 SourceLocation TemplateLoc,
3557 SourceLocation RAngleLoc,
3558 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003559 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003560 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00003561 Sema::InstantiatingTemplate Inst(
3562 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
3563 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003564 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003565 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566
David Majnemer8b622692016-07-03 21:17:51 +00003567 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003568
3569 // Only substitute for the innermost template argument list.
3570 MultiLevelTemplateArgumentList TemplateArgLists;
3571 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3572 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3573 TemplateArgLists.addOuterTemplateArguments(None);
3574
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003575 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003576 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003577 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003578 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003579 QualifierLoc =
3580 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003581 if (!QualifierLoc)
3582 return TemplateName();
3583 }
David Majnemer89189202013-08-28 23:48:32 +00003584
3585 return SemaRef.SubstTemplateName(
3586 QualifierLoc,
3587 Param->getDefaultArgument().getArgument().getAsTemplate(),
3588 Param->getDefaultArgument().getTemplateNameLoc(),
3589 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003590}
3591
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003592/// \brief If the given template parameter has a default template
3593/// argument, substitute into that default template argument and
3594/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003595TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003596Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3597 SourceLocation TemplateLoc,
3598 SourceLocation RAngleLoc,
3599 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003600 SmallVectorImpl<TemplateArgument>
3601 &Converted,
3602 bool &HasDefaultArg) {
3603 HasDefaultArg = false;
3604
3605 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003606 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003607 return TemplateArgumentLoc();
3608
Richard Smithc87b9382013-07-04 01:01:24 +00003609 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003610 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003611 TemplateLoc,
3612 RAngleLoc,
3613 TypeParm,
3614 Converted);
3615 if (DI)
3616 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3617
3618 return TemplateArgumentLoc();
3619 }
3620
3621 if (NonTypeTemplateParmDecl *NonTypeParm
3622 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003623 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003624 return TemplateArgumentLoc();
3625
Richard Smithc87b9382013-07-04 01:01:24 +00003626 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003627 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003628 TemplateLoc,
3629 RAngleLoc,
3630 NonTypeParm,
3631 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003632 if (Arg.isInvalid())
3633 return TemplateArgumentLoc();
3634
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003635 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003636 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3637 }
3638
3639 TemplateTemplateParmDecl *TempTempParm
3640 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003641 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003642 return TemplateArgumentLoc();
3643
Richard Smithc87b9382013-07-04 01:01:24 +00003644 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003645 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003646 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003647 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003648 RAngleLoc,
3649 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003650 Converted,
3651 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003652 if (TName.isNull())
3653 return TemplateArgumentLoc();
3654
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003656 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003657 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3658}
3659
Richard Smith11255ec2017-01-18 19:19:22 +00003660/// Convert a template-argument that we parsed as a type into a template, if
3661/// possible. C++ permits injected-class-names to perform dual service as
3662/// template template arguments and as template type arguments.
3663static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
3664 // Extract and step over any surrounding nested-name-specifier.
3665 NestedNameSpecifierLoc QualLoc;
3666 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
3667 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
3668 return TemplateArgumentLoc();
3669
3670 QualLoc = ETLoc.getQualifierLoc();
3671 TLoc = ETLoc.getNamedTypeLoc();
3672 }
3673
3674 // If this type was written as an injected-class-name, it can be used as a
3675 // template template argument.
3676 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
3677 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
3678 QualLoc, InjLoc.getNameLoc());
3679
3680 // If this type was written as an injected-class-name, it may have been
3681 // converted to a RecordType during instantiation. If the RecordType is
3682 // *not* wrapped in a TemplateSpecializationType and denotes a class
3683 // template specialization, it must have come from an injected-class-name.
3684 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
3685 if (auto *CTSD =
3686 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
3687 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
3688 QualLoc, RecLoc.getNameLoc());
3689
3690 return TemplateArgumentLoc();
3691}
3692
Douglas Gregorda0fb532009-11-11 19:31:23 +00003693/// \brief Check that the given template argument corresponds to the given
3694/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003695///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003696/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003697/// checked.
3698///
Richard Trieu15b66532015-01-24 02:48:32 +00003699/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003700///
3701/// \param Template The template in which the template argument resides.
3702///
3703/// \param TemplateLoc The location of the template name for the template
3704/// whose argument list we're matching.
3705///
3706/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3707/// the template argument list.
3708///
3709/// \param ArgumentPackIndex The index into the argument pack where this
3710/// argument will be placed. Only valid if the parameter is a parameter pack.
3711///
3712/// \param Converted The checked, converted argument will be added to the
3713/// end of this small vector.
3714///
3715/// \param CTAK Describes how we arrived at this particular template argument:
3716/// explicitly written, deduced, etc.
3717///
3718/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003719bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003720 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003721 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003722 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003723 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003724 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003725 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003726 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003727 // Check template type parameters.
3728 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003729 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003730
Douglas Gregoreebed722009-11-11 19:41:09 +00003731 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003733 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003734 // with the template arguments we've seen thus far. But if the
3735 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003736 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003737 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3738 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
Peter Collingbourne01687632010-12-10 17:08:53 +00003740 if (NTTPType->isDependentType() &&
3741 !isa<TemplateTemplateParmDecl>(Template) &&
3742 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003743 // Do substitution on the type of the non-type template parameter.
3744 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003745 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003746 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003747 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003748 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749
3750 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003751 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003752 NTTPType = SubstType(NTTPType,
3753 MultiLevelTemplateArgumentList(TemplateArgs),
3754 NTTP->getLocation(),
3755 NTTP->getDeclName());
3756 // If that worked, check the non-type template parameter type
3757 // for validity.
3758 if (!NTTPType.isNull())
3759 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3760 NTTP->getLocation());
3761 if (NTTPType.isNull())
3762 return true;
3763 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764
Douglas Gregorda0fb532009-11-11 19:31:23 +00003765 switch (Arg.getArgument().getKind()) {
3766 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003767 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003768
Douglas Gregorda0fb532009-11-11 19:31:23 +00003769 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003770 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003771 ExprResult Res =
3772 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3773 Result, CTAK);
3774 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003775 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003776
Richard Trieu15b66532015-01-24 02:48:32 +00003777 // If the resulting expression is new, then use it in place of the
3778 // old expression in the template argument.
3779 if (Res.get() != Arg.getArgument().getAsExpr()) {
3780 TemplateArgument TA(Res.get());
3781 Arg = TemplateArgumentLoc(TA, Res.get());
3782 }
3783
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003784 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003785 break;
3786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787
Douglas Gregorda0fb532009-11-11 19:31:23 +00003788 case TemplateArgument::Declaration:
3789 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003790 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003791 // We've already checked this template argument, so just copy
3792 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003793 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003794 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795
Douglas Gregorda0fb532009-11-11 19:31:23 +00003796 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003797 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003798 // We were given a template template argument. It may not be ill-formed;
3799 // see below.
3800 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003801 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3802 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003803 // We have a template argument such as \c T::template X, which we
3804 // parsed as a template template argument. However, since we now
3805 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003806 // template name into an expression.
3807
3808 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3809 Arg.getTemplateNameLoc());
3810
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003811 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003812 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003813 // FIXME: the template-template arg was a DependentTemplateName,
3814 // so it was provided with a template keyword. However, its source
3815 // location is not stored in the template argument structure.
3816 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003817 ExprResult E = DependentScopeDeclRefExpr::Create(
3818 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3819 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003820
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003821 // If we parsed the template argument as a pack expansion, create a
3822 // pack expansion expression.
3823 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003824 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003825 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003826 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003827 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003828
Douglas Gregorda0fb532009-11-11 19:31:23 +00003829 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003830 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003831 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003832 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003833
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003834 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003835 break;
3836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003837
Douglas Gregorda0fb532009-11-11 19:31:23 +00003838 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003839 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003840 // therefore cannot be a non-type template argument.
3841 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3842 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003843
Douglas Gregorda0fb532009-11-11 19:31:23 +00003844 Diag(Param->getLocation(), diag::note_template_param_here);
3845 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846
Douglas Gregorda0fb532009-11-11 19:31:23 +00003847 case TemplateArgument::Type: {
3848 // We have a non-type template parameter but the template
3849 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003850
Douglas Gregorda0fb532009-11-11 19:31:23 +00003851 // C++ [temp.arg]p2:
3852 // In a template-argument, an ambiguity between a type-id and
3853 // an expression is resolved to a type-id, regardless of the
3854 // form of the corresponding template-parameter.
3855 //
3856 // We warn specifically about this case, since it can be rather
3857 // confusing for users.
3858 QualType T = Arg.getArgument().getAsType();
3859 SourceRange SR = Arg.getSourceRange();
3860 if (T->isFunctionType())
3861 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3862 else
3863 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3864 Diag(Param->getLocation(), diag::note_template_param_here);
3865 return true;
3866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003867
Douglas Gregorda0fb532009-11-11 19:31:23 +00003868 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003869 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003870 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003871
Douglas Gregorda0fb532009-11-11 19:31:23 +00003872 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003873 }
3874
3875
Douglas Gregorda0fb532009-11-11 19:31:23 +00003876 // Check template template parameters.
3877 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003878
Douglas Gregorda0fb532009-11-11 19:31:23 +00003879 // Substitute into the template parameter list of the template
3880 // template parameter, since previously-supplied template arguments
3881 // may appear within the template template parameter.
3882 {
3883 // Set up a template instantiation context.
3884 LocalInstantiationScope Scope(*this);
3885 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003886 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003887 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003888 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003889 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003890
David Majnemer8b622692016-07-03 21:17:51 +00003891 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003892 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003894 MultiLevelTemplateArgumentList(TemplateArgs)));
3895 if (!TempParm)
3896 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003898
Richard Smith11255ec2017-01-18 19:19:22 +00003899 // C++1z [temp.local]p1: (DR1004)
3900 // When [the injected-class-name] is used [...] as a template-argument for
3901 // a template template-parameter [...] it refers to the class template
3902 // itself.
3903 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
3904 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
3905 Arg.getTypeSourceInfo()->getTypeLoc());
3906 if (!ConvertedArg.getArgument().isNull())
3907 Arg = ConvertedArg;
3908 }
3909
Douglas Gregorda0fb532009-11-11 19:31:23 +00003910 switch (Arg.getArgument().getKind()) {
3911 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003912 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003913
Douglas Gregorda0fb532009-11-11 19:31:23 +00003914 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003915 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003916 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003917 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003918
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003919 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003920 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003921
Douglas Gregorda0fb532009-11-11 19:31:23 +00003922 case TemplateArgument::Expression:
3923 case TemplateArgument::Type:
3924 // We have a template template parameter but the template
3925 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003926 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003927 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003928 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003929
Douglas Gregorda0fb532009-11-11 19:31:23 +00003930 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003931 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003932 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003933 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003934 case TemplateArgument::NullPtr:
3935 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003936
Douglas Gregorda0fb532009-11-11 19:31:23 +00003937 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003938 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003939 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003940
Douglas Gregorda0fb532009-11-11 19:31:23 +00003941 return false;
3942}
3943
Simon Pilgrim6905d222016-12-30 22:55:33 +00003944/// \brief Diagnose an arity mismatch in the
Douglas Gregor8e072612012-02-03 07:34:46 +00003945static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3946 SourceLocation TemplateLoc,
3947 TemplateArgumentListInfo &TemplateArgs) {
3948 TemplateParameterList *Params = Template->getTemplateParameters();
3949 unsigned NumParams = Params->size();
3950 unsigned NumArgs = TemplateArgs.size();
3951
3952 SourceRange Range;
3953 if (NumArgs > NumParams)
Simon Pilgrim6905d222016-12-30 22:55:33 +00003954 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
Douglas Gregor8e072612012-02-03 07:34:46 +00003955 TemplateArgs.getRAngleLoc());
3956 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3957 << (NumArgs > NumParams)
Richard Smith0c062b42017-01-14 02:19:59 +00003958 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
Douglas Gregor8e072612012-02-03 07:34:46 +00003959 << Template << Range;
3960 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3961 << Params->getSourceRange();
3962 return true;
3963}
3964
Richard Smith1fde8ec2012-09-07 02:06:42 +00003965/// \brief Check whether the template parameter is a pack expansion, and if so,
3966/// determine the number of parameters produced by that expansion. For instance:
3967///
3968/// \code
3969/// template<typename ...Ts> struct A {
3970/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3971/// };
3972/// \endcode
3973///
3974/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3975/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003976static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003977 if (NonTypeTemplateParmDecl *NTTP
3978 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3979 if (NTTP->isExpandedParameterPack())
3980 return NTTP->getNumExpansionTypes();
3981 }
3982
3983 if (TemplateTemplateParmDecl *TTP
3984 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3985 if (TTP->isExpandedParameterPack())
3986 return TTP->getNumExpansionTemplateParameters();
3987 }
3988
David Blaikie7a30dc52013-02-21 01:47:18 +00003989 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003990}
3991
Richard Smith35c1df52015-06-17 20:16:32 +00003992/// Diagnose a missing template argument.
3993template<typename TemplateParmDecl>
3994static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3995 TemplateDecl *TD,
3996 const TemplateParmDecl *D,
3997 TemplateArgumentListInfo &Args) {
3998 // Dig out the most recent declaration of the template parameter; there may be
3999 // declarations of the template that are more recent than TD.
4000 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4001 ->getTemplateParameters()
4002 ->getParam(D->getIndex()));
4003
4004 // If there's a default argument that's not visible, diagnose that we're
4005 // missing a module import.
4006 llvm::SmallVector<Module*, 8> Modules;
4007 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4008 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4009 D->getDefaultArgumentLoc(), Modules,
4010 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00004011 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00004012 return true;
4013 }
4014
4015 // FIXME: If there's a more recent default argument that *is* visible,
4016 // diagnose that it was declared too late.
4017
4018 return diagnoseArityMismatch(S, TD, Loc, Args);
4019}
4020
Douglas Gregord32e0282009-02-09 23:23:08 +00004021/// \brief Check that the given template argument list is well-formed
4022/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00004023bool Sema::CheckTemplateArgumentList(
4024 TemplateDecl *Template, SourceLocation TemplateLoc,
4025 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4026 SmallVectorImpl<TemplateArgument> &Converted,
4027 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00004028 // Make a copy of the template arguments for processing. Only make the
4029 // changes at the end when successful in matching the arguments to the
4030 // template.
4031 TemplateArgumentListInfo NewArgs = TemplateArgs;
4032
Douglas Gregord32e0282009-02-09 23:23:08 +00004033 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00004034
Richard Trieu15b66532015-01-24 02:48:32 +00004035 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00004036
Mike Stump11289f42009-09-09 15:08:12 +00004037 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00004038 // [...] The type and form of each template-argument specified in
4039 // a template-id shall match the type and form specified for the
4040 // corresponding parameter declared by the template in its
4041 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00004042 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004043 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00004044 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00004045 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00004046 for (TemplateParameterList::iterator Param = Params->begin(),
4047 ParamEnd = Params->end();
4048 Param != ParamEnd; /* increment in loop */) {
4049 // If we have an expanded parameter pack, make sure we don't have too
4050 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00004051 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004052 if (*Expansions == ArgumentPack.size()) {
4053 // We're done with this parameter pack. Pack up its arguments and add
4054 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00004055 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00004056 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004057 ArgumentPack.clear();
4058
Richard Smith1fde8ec2012-09-07 02:06:42 +00004059 // This argument is assigned to the next parameter.
4060 ++Param;
4061 continue;
4062 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4063 // Not enough arguments for this parameter pack.
4064 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4065 << false
Richard Smith0c062b42017-01-14 02:19:59 +00004066 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00004067 << Template;
4068 Diag(Template->getLocation(), diag::note_template_decl_here)
4069 << Params->getSourceRange();
4070 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004071 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004072 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004073
Richard Smith1fde8ec2012-09-07 02:06:42 +00004074 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00004075 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00004076 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004077 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004078 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00004079 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004080
Richard Smith96d71c32014-11-12 23:38:38 +00004081 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00004082 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00004083 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4084 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00004085 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00004086 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00004087 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00004088 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00004089 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00004090 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00004091 Diag((*Param)->getLocation(), diag::note_template_param_here);
4092 return true;
4093 }
4094
Richard Smith1fde8ec2012-09-07 02:06:42 +00004095 // We're now done with this argument.
4096 ++ArgIdx;
4097
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004098 if ((*Param)->isTemplateParameterPack()) {
4099 // The template parameter was a template parameter pack, so take the
4100 // deduced argument and place it on the argument pack. Note that we
4101 // stay on the same template parameter so that we can deduce more
4102 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004103 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004104 } else {
4105 // Move to the next template parameter.
4106 ++Param;
4107 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004108
Richard Smith96d71c32014-11-12 23:38:38 +00004109 // If we just saw a pack expansion into a non-pack, then directly convert
4110 // the remaining arguments, because we don't know what parameters they'll
4111 // match up with.
4112 if (PackExpansionIntoNonPack) {
4113 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004114 // If we were part way through filling in an expanded parameter pack,
4115 // fall back to just producing individual arguments.
4116 Converted.insert(Converted.end(),
4117 ArgumentPack.begin(), ArgumentPack.end());
4118 ArgumentPack.clear();
4119 }
4120
4121 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00004122 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00004123 ++ArgIdx;
4124 }
4125
Richard Smith1fde8ec2012-09-07 02:06:42 +00004126 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00004127 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004128
Douglas Gregor84d49a22009-11-11 21:54:23 +00004129 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004130 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004131
Douglas Gregor2f157c92011-06-03 02:59:40 +00004132 // If we're checking a partial template argument list, we're done.
4133 if (PartialTemplateArgs) {
4134 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00004135 Converted.push_back(
4136 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4137
Richard Smith1fde8ec2012-09-07 02:06:42 +00004138 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00004139 }
4140
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004141 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004142 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00004143 if ((*Param)->isTemplateParameterPack()) {
4144 assert(!getExpandedPackSize(*Param) &&
4145 "Should have dealt with this already");
4146
4147 // A non-expanded parameter pack before the end of the parameter list
4148 // only occurs for an ill-formed template parameter list, unless we've
4149 // got a partial argument list for a function template, so just bail out.
4150 if (Param + 1 != ParamEnd)
4151 return true;
4152
Benjamin Kramercce63472015-08-05 09:40:22 +00004153 Converted.push_back(
4154 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004155 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00004156
4157 ++Param;
4158 continue;
4159 }
4160
Douglas Gregor8e072612012-02-03 07:34:46 +00004161 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00004162 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004163
Douglas Gregor84d49a22009-11-11 21:54:23 +00004164 // Retrieve the default template argument from the template
4165 // parameter. For each kind of template parameter, we substitute the
4166 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004167 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004168 // the default argument.
4169 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004170 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004171 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4172 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004173
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004174 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004175 Template,
4176 TemplateLoc,
4177 RAngleLoc,
4178 TTP,
4179 Converted);
4180 if (!ArgType)
4181 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004182
Douglas Gregor84d49a22009-11-11 21:54:23 +00004183 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4184 ArgType);
4185 } else if (NonTypeTemplateParmDecl *NTTP
4186 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004187 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004188 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4189 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004190
John McCalldadc5752010-08-24 06:29:42 +00004191 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192 TemplateLoc,
4193 RAngleLoc,
4194 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004195 Converted);
4196 if (E.isInvalid())
4197 return true;
4198
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004199 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004200 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4201 } else {
4202 TemplateTemplateParmDecl *TempParm
4203 = cast<TemplateTemplateParmDecl>(*Param);
4204
Richard Smith95d83952015-06-10 20:36:34 +00004205 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004206 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4207 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004208
Douglas Gregordf846d12011-03-02 18:46:51 +00004209 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004210 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211 TemplateLoc,
4212 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004213 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004214 Converted,
4215 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004216 if (Name.isNull())
4217 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004218
Douglas Gregor9d802122011-03-02 17:09:35 +00004219 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4220 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004221 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004222
Douglas Gregor84d49a22009-11-11 21:54:23 +00004223 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00004224 // the default template argument. We're not actually instantiating a
4225 // template here, we just create this object to put a note into the
4226 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004227 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4228 SourceRange(TemplateLoc, RAngleLoc));
4229 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004230 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004231
Douglas Gregor84d49a22009-11-11 21:54:23 +00004232 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004233 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004234 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004235 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004236
Richard Trieu15b66532015-01-24 02:48:32 +00004237 // Core issue 150 (assumed resolution): if this is a template template
4238 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004239 // template definition.
4240 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004241 NewArgs.addArgument(Arg);
4242
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004243 // Move to the next template parameter and argument.
4244 ++Param;
4245 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247
Richard Smith07f79912014-06-06 16:00:50 +00004248 // If we're performing a partial argument substitution, allow any trailing
4249 // pack expansions; they might be empty. This can happen even if
4250 // PartialTemplateArgs is false (the list of arguments is complete but
4251 // still dependent).
4252 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4253 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004254 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4255 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004256 }
4257
Douglas Gregor8e072612012-02-03 07:34:46 +00004258 // If we have any leftover arguments, then there were too many arguments.
4259 // Complain and fail.
4260 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004261 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4262
4263 // No problems found with the new argument list, propagate changes back
4264 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00004265 if (UpdateArgsWithConversions)
4266 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004267
Richard Smith1fde8ec2012-09-07 02:06:42 +00004268 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004269}
4270
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004271namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004272 class UnnamedLocalNoLinkageFinder
4273 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004274 {
4275 Sema &S;
4276 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004277
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004278 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004279
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004280 public:
4281 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4282
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004283 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00004284 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004285 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004286
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004287#define TYPE(Class, Parent) \
4288 bool Visit##Class##Type(const Class##Type *);
4289#define ABSTRACT_TYPE(Class, Parent) \
4290 bool Visit##Class##Type(const Class##Type *) { return false; }
4291#define NON_CANONICAL_TYPE(Class, Parent) \
4292 bool Visit##Class##Type(const Class##Type *) { return false; }
4293#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004295 bool VisitTagDecl(const TagDecl *Tag);
4296 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4297 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004298} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004299
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004300bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004301 return false;
4302}
4303
4304bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4305 return Visit(T->getElementType());
4306}
4307
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004308bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004309 return Visit(T->getPointeeType());
4310}
4311
4312bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004314 return Visit(T->getPointeeType());
4315}
4316
4317bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004319 return Visit(T->getPointeeType());
4320}
4321
4322bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004324 return Visit(T->getPointeeType());
4325}
4326
4327bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004328 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004329 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4330}
4331
4332bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004333 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004334 return Visit(T->getElementType());
4335}
4336
4337bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004338 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004339 return Visit(T->getElementType());
4340}
4341
4342bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004343 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004344 return Visit(T->getElementType());
4345}
4346
4347bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004349 return Visit(T->getElementType());
4350}
4351
4352bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004353 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004354 return Visit(T->getElementType());
4355}
4356
4357bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4358 return Visit(T->getElementType());
4359}
4360
4361bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4362 return Visit(T->getElementType());
4363}
4364
4365bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4366 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004367 for (const auto &A : T->param_types()) {
4368 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004369 return true;
4370 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371
Alp Toker314cc812014-01-25 16:55:45 +00004372 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004373}
4374
4375bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4376 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004377 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004378}
4379
4380bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4381 const UnresolvedUsingType*) {
4382 return false;
4383}
4384
4385bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4386 return false;
4387}
4388
4389bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4390 return Visit(T->getUnderlyingType());
4391}
4392
4393bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4394 return false;
4395}
4396
Alexis Hunte852b102011-05-24 22:41:36 +00004397bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4398 const UnaryTransformType*) {
4399 return false;
4400}
4401
Richard Smith30482bc2011-02-20 03:19:35 +00004402bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4403 return Visit(T->getDeducedType());
4404}
4405
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004406bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4407 return VisitTagDecl(T->getDecl());
4408}
4409
4410bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4411 return VisitTagDecl(T->getDecl());
4412}
4413
4414bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4415 const TemplateTypeParmType*) {
4416 return false;
4417}
4418
Douglas Gregorada4b792011-01-14 02:55:32 +00004419bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4420 const SubstTemplateTypeParmPackType *) {
4421 return false;
4422}
4423
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004424bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4425 const TemplateSpecializationType*) {
4426 return false;
4427}
4428
4429bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4430 const InjectedClassNameType* T) {
4431 return VisitTagDecl(T->getDecl());
4432}
4433
4434bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4435 const DependentNameType* T) {
4436 return VisitNestedNameSpecifier(T->getQualifier());
4437}
4438
4439bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4440 const DependentTemplateSpecializationType* T) {
4441 return VisitNestedNameSpecifier(T->getQualifier());
4442}
4443
Douglas Gregord2fa7662010-12-20 02:24:11 +00004444bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4445 const PackExpansionType* T) {
4446 return Visit(T->getPattern());
4447}
4448
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004449bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4450 return false;
4451}
4452
4453bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4454 const ObjCInterfaceType *) {
4455 return false;
4456}
4457
4458bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4459 const ObjCObjectPointerType *) {
4460 return false;
4461}
4462
Eli Friedman0dfb8892011-10-06 23:00:33 +00004463bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4464 return Visit(T->getValueType());
4465}
4466
Xiuli Pan9c14e282016-01-09 12:53:17 +00004467bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4468 return false;
4469}
4470
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004471bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4472 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004473 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004474 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004475 diag::warn_cxx98_compat_template_arg_local_type :
4476 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004477 << S.Context.getTypeDeclType(Tag) << SR;
4478 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004479 }
4480
John McCall5ea95772013-03-09 00:54:27 +00004481 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004482 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004483 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004484 diag::warn_cxx98_compat_template_arg_unnamed_type :
4485 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004486 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4487 return true;
4488 }
4489
4490 return false;
4491}
4492
4493bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4494 NestedNameSpecifier *NNS) {
4495 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4496 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004497
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004498 switch (NNS->getKind()) {
4499 case NestedNameSpecifier::Identifier:
4500 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004501 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004502 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004503 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004504 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004505
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004506 case NestedNameSpecifier::TypeSpec:
4507 case NestedNameSpecifier::TypeSpecWithTemplate:
4508 return Visit(QualType(NNS->getAsType(), 0));
4509 }
David Blaikie8a40f702012-01-17 06:56:22 +00004510 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004511}
4512
Douglas Gregord32e0282009-02-09 23:23:08 +00004513/// \brief Check a template argument against its corresponding
4514/// template type parameter.
4515///
4516/// This routine implements the semantics of C++ [temp.arg.type]. It
4517/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004518bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004519 TypeSourceInfo *ArgInfo) {
4520 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004521 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004522 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004523
4524 if (Arg->isVariablyModifiedType()) {
4525 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004526 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004527 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004528 }
4529
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004530 // C++03 [temp.arg.type]p2:
4531 // A local type, a type with no linkage, an unnamed type or a type
4532 // compounded from any of these types shall not be used as a
4533 // template-argument for a template type-parameter.
4534 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004535 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004536 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00004537 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004538 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4539 (void)Finder.Visit(Context.getCanonicalType(Arg));
4540 }
4541
Douglas Gregord32e0282009-02-09 23:23:08 +00004542 return false;
4543}
4544
Douglas Gregor20fdef32012-04-10 17:08:25 +00004545enum NullPointerValueKind {
4546 NPV_NotNullPointer,
4547 NPV_NullPointer,
4548 NPV_Error
4549};
4550
4551/// \brief Determine whether the given template argument is a null pointer
4552/// value of the appropriate type.
4553static NullPointerValueKind
4554isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4555 QualType ParamType, Expr *Arg) {
4556 if (Arg->isValueDependent() || Arg->isTypeDependent())
4557 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004558
Richard Smithdb0ac552015-12-18 22:40:25 +00004559 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004560 llvm_unreachable(
4561 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004562
David Majnemer5c734ad2014-08-14 00:49:23 +00004563 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004564 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00004565
Douglas Gregor20fdef32012-04-10 17:08:25 +00004566 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004567 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4568 if (ArgRV.isInvalid())
4569 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004570 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00004571
Douglas Gregor20fdef32012-04-10 17:08:25 +00004572 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004573 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004574 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004575 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004576 EvalResult.HasSideEffects) {
4577 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00004578
Douglas Gregor350880c2012-04-10 19:03:30 +00004579 // If our only note is the usual "invalid subexpression" note, just point
4580 // the caret at its location rather than producing an essentially
4581 // redundant note.
4582 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4583 diag::note_invalid_subexpr_in_const_expr) {
4584 DiagLoc = Notes[0].first;
4585 Notes.clear();
4586 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004587
Douglas Gregor350880c2012-04-10 19:03:30 +00004588 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4589 << Arg->getType() << Arg->getSourceRange();
4590 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4591 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004592
Douglas Gregor350880c2012-04-10 19:03:30 +00004593 S.Diag(Param->getLocation(), diag::note_template_param_here);
4594 return NPV_Error;
4595 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004596
Douglas Gregor20fdef32012-04-10 17:08:25 +00004597 // C++11 [temp.arg.nontype]p1:
4598 // - an address constant expression of type std::nullptr_t
4599 if (Arg->getType()->isNullPtrType())
4600 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00004601
Douglas Gregor20fdef32012-04-10 17:08:25 +00004602 // - a constant expression that evaluates to a null pointer value (4.10); or
4603 // - a constant expression that evaluates to a null member pointer value
4604 // (4.11); or
4605 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4606 (EvalResult.Val.isMemberPointer() &&
4607 !EvalResult.Val.getMemberPointerDecl())) {
4608 // If our expression has an appropriate type, we've succeeded.
4609 bool ObjCLifetimeConversion;
4610 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4611 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4612 ObjCLifetimeConversion))
4613 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00004614
Douglas Gregor20fdef32012-04-10 17:08:25 +00004615 // The types didn't match, but we know we got a null pointer; complain,
4616 // then recover as if the types were correct.
4617 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4618 << Arg->getType() << ParamType << Arg->getSourceRange();
4619 S.Diag(Param->getLocation(), diag::note_template_param_here);
4620 return NPV_NullPointer;
4621 }
4622
4623 // If we don't have a null pointer value, but we do have a NULL pointer
4624 // constant, suggest a cast to the appropriate type.
4625 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4626 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4627 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004628 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4629 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4630 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004631 S.Diag(Param->getLocation(), diag::note_template_param_here);
4632 return NPV_NullPointer;
4633 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004634
Douglas Gregor20fdef32012-04-10 17:08:25 +00004635 // FIXME: If we ever want to support general, address-constant expressions
4636 // as non-type template arguments, we should return the ExprResult here to
4637 // be interpreted by the caller.
4638 return NPV_NotNullPointer;
4639}
4640
David Majnemer61c39a12013-08-23 05:39:39 +00004641/// \brief Checks whether the given template argument is compatible with its
4642/// template parameter.
4643static bool CheckTemplateArgumentIsCompatibleWithParameter(
4644 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4645 Expr *Arg, QualType ArgType) {
4646 bool ObjCLifetimeConversion;
4647 if (ParamType->isPointerType() &&
4648 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4649 S.IsQualificationConversion(ArgType, ParamType, false,
4650 ObjCLifetimeConversion)) {
4651 // For pointer-to-object types, qualification conversions are
4652 // permitted.
4653 } else {
4654 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4655 if (!ParamRef->getPointeeType()->isFunctionType()) {
4656 // C++ [temp.arg.nontype]p5b3:
4657 // For a non-type template-parameter of type reference to
4658 // object, no conversions apply. The type referred to by the
4659 // reference may be more cv-qualified than the (otherwise
4660 // identical) type of the template- argument. The
4661 // template-parameter is bound directly to the
4662 // template-argument, which shall be an lvalue.
4663
4664 // FIXME: Other qualifiers?
4665 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4666 unsigned ArgQuals = ArgType.getCVRQualifiers();
4667
4668 if ((ParamQuals | ArgQuals) != ParamQuals) {
4669 S.Diag(Arg->getLocStart(),
4670 diag::err_template_arg_ref_bind_ignores_quals)
4671 << ParamType << Arg->getType() << Arg->getSourceRange();
4672 S.Diag(Param->getLocation(), diag::note_template_param_here);
4673 return true;
4674 }
4675 }
4676 }
4677
4678 // At this point, the template argument refers to an object or
4679 // function with external linkage. We now need to check whether the
4680 // argument and parameter types are compatible.
4681 if (!S.Context.hasSameUnqualifiedType(ArgType,
4682 ParamType.getNonReferenceType())) {
4683 // We can't perform this conversion or binding.
4684 if (ParamType->isReferenceType())
4685 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4686 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4687 else
4688 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4689 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4690 S.Diag(Param->getLocation(), diag::note_template_param_here);
4691 return true;
4692 }
4693 }
4694
4695 return false;
4696}
4697
Douglas Gregorccb07762009-02-11 19:52:55 +00004698/// \brief Checks whether the given template argument is the address
4699/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004700static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004701CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4702 NonTypeTemplateParmDecl *Param,
4703 QualType ParamType,
4704 Expr *ArgIn,
4705 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004706 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004707 Expr *Arg = ArgIn;
4708 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004709
Douglas Gregorb242683d2010-04-01 18:32:35 +00004710 bool AddressTaken = false;
4711 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004712 if (S.getLangOpts().MicrosoftExt) {
4713 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4714 // dereference and address-of operators.
4715 Arg = Arg->IgnoreParenCasts();
4716
4717 bool ExtWarnMSTemplateArg = false;
4718 UnaryOperatorKind FirstOpKind;
4719 SourceLocation FirstOpLoc;
4720 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4721 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4722 if (UnOpKind == UO_Deref)
4723 ExtWarnMSTemplateArg = true;
4724 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4725 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4726 if (!AddrOpLoc.isValid()) {
4727 FirstOpKind = UnOpKind;
4728 FirstOpLoc = UnOp->getOperatorLoc();
4729 }
4730 } else
4731 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004732 }
David Majnemer61c39a12013-08-23 05:39:39 +00004733 if (FirstOpLoc.isValid()) {
4734 if (ExtWarnMSTemplateArg)
4735 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4736 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004737
David Majnemer61c39a12013-08-23 05:39:39 +00004738 if (FirstOpKind == UO_AddrOf)
4739 AddressTaken = true;
4740 else if (Arg->getType()->isPointerType()) {
4741 // We cannot let pointers get dereferenced here, that is obviously not a
4742 // constant expression.
4743 assert(FirstOpKind == UO_Deref);
4744 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4745 << Arg->getSourceRange();
4746 }
4747 }
4748 } else {
4749 // See through any implicit casts we added to fix the type.
4750 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004751
David Majnemer61c39a12013-08-23 05:39:39 +00004752 // C++ [temp.arg.nontype]p1:
4753 //
4754 // A template-argument for a non-type, non-template
4755 // template-parameter shall be one of: [...]
4756 //
4757 // -- the address of an object or function with external
4758 // linkage, including function templates and function
4759 // template-ids but excluding non-static class members,
4760 // expressed as & id-expression where the & is optional if
4761 // the name refers to a function or array, or if the
4762 // corresponding template-parameter is a reference; or
4763
4764 // In C++98/03 mode, give an extension warning on any extra parentheses.
4765 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4766 bool ExtraParens = false;
4767 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4768 if (!Invalid && !ExtraParens) {
4769 S.Diag(Arg->getLocStart(),
4770 S.getLangOpts().CPlusPlus11
4771 ? diag::warn_cxx98_compat_template_arg_extra_parens
4772 : diag::ext_template_arg_extra_parens)
4773 << Arg->getSourceRange();
4774 ExtraParens = true;
4775 }
4776
4777 Arg = Parens->getSubExpr();
4778 }
4779
4780 while (SubstNonTypeTemplateParmExpr *subst =
4781 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4782 Arg = subst->getReplacement()->IgnoreImpCasts();
4783
4784 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4785 if (UnOp->getOpcode() == UO_AddrOf) {
4786 Arg = UnOp->getSubExpr();
4787 AddressTaken = true;
4788 AddrOpLoc = UnOp->getOperatorLoc();
4789 }
4790 }
4791
4792 while (SubstNonTypeTemplateParmExpr *subst =
4793 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4794 Arg = subst->getReplacement()->IgnoreImpCasts();
4795 }
John McCall7c454bb2011-07-15 05:09:51 +00004796
David Majnemer07910d62014-06-26 07:48:46 +00004797 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4798 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4799
4800 // If our parameter has pointer type, check for a null template value.
4801 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4802 NullPointerValueKind NPV;
4803 // dllimport'd entities aren't constant but are available inside of template
4804 // arguments.
4805 if (Entity && Entity->hasAttr<DLLImportAttr>())
4806 NPV = NPV_NotNullPointer;
4807 else
4808 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4809 switch (NPV) {
4810 case NPV_NullPointer:
4811 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004812 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4813 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004814 return false;
4815
4816 case NPV_Error:
4817 return true;
4818
4819 case NPV_NotNullPointer:
4820 break;
4821 }
4822 }
4823
Chandler Carruth724a8a12010-01-31 10:01:20 +00004824 // Stop checking the precise nature of the argument if it is value dependent,
4825 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004826 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004827 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004828 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004829 }
David Majnemer61c39a12013-08-23 05:39:39 +00004830
4831 if (isa<CXXUuidofExpr>(Arg)) {
4832 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4833 ArgIn, Arg, ArgType))
4834 return true;
4835
4836 Converted = TemplateArgument(ArgIn);
4837 return false;
4838 }
4839
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004840 if (!DRE) {
4841 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4842 << Arg->getSourceRange();
4843 S.Diag(Param->getLocation(), diag::note_template_param_here);
4844 return true;
4845 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004846
Douglas Gregorccb07762009-02-11 19:52:55 +00004847 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004848 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004849 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004850 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004851 S.Diag(Param->getLocation(), diag::note_template_param_here);
4852 return true;
4853 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004854
4855 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004856 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004857 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004858 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004859 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004860 S.Diag(Param->getLocation(), diag::note_template_param_here);
4861 return true;
4862 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004863 }
Mike Stump11289f42009-09-09 15:08:12 +00004864
Richard Smith9380e0e2012-04-04 21:11:30 +00004865 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4866 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004867
Richard Smith9380e0e2012-04-04 21:11:30 +00004868 // A non-type template argument must refer to an object or function.
4869 if (!Func && !Var) {
4870 // We found something, but we don't know specifically what it is.
4871 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4872 << Arg->getSourceRange();
4873 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4874 return true;
4875 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004876
Richard Smith9380e0e2012-04-04 21:11:30 +00004877 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004878 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004879 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004880 diag::warn_cxx98_compat_template_arg_object_internal :
4881 diag::ext_template_arg_object_internal)
4882 << !Func << Entity << Arg->getSourceRange();
4883 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4884 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004885 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004886 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4887 << !Func << Entity << Arg->getSourceRange();
4888 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4889 << !Func;
4890 return true;
4891 }
4892
4893 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004894 // If the template parameter has pointer type, the function decays.
4895 if (ParamType->isPointerType() && !AddressTaken)
4896 ArgType = S.Context.getPointerType(Func->getType());
4897 else if (AddressTaken && ParamType->isReferenceType()) {
4898 // If we originally had an address-of operator, but the
4899 // parameter has reference type, complain and (if things look
4900 // like they will work) drop the address-of operator.
4901 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4902 ParamType.getNonReferenceType())) {
4903 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4904 << ParamType;
4905 S.Diag(Param->getLocation(), diag::note_template_param_here);
4906 return true;
4907 }
4908
4909 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4910 << ParamType
4911 << FixItHint::CreateRemoval(AddrOpLoc);
4912 S.Diag(Param->getLocation(), diag::note_template_param_here);
4913
4914 ArgType = Func->getType();
4915 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004916 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004917 // A value of reference type is not an object.
4918 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004919 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004920 diag::err_template_arg_reference_var)
4921 << Var->getType() << Arg->getSourceRange();
4922 S.Diag(Param->getLocation(), diag::note_template_param_here);
4923 return true;
4924 }
4925
Richard Smith9380e0e2012-04-04 21:11:30 +00004926 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004927 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004928 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4929 << Arg->getSourceRange();
4930 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4931 return true;
4932 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004933
4934 // If the template parameter has pointer type, we must have taken
4935 // the address of this object.
4936 if (ParamType->isReferenceType()) {
4937 if (AddressTaken) {
4938 // If we originally had an address-of operator, but the
4939 // parameter has reference type, complain and (if things look
4940 // like they will work) drop the address-of operator.
4941 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4942 ParamType.getNonReferenceType())) {
4943 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4944 << ParamType;
4945 S.Diag(Param->getLocation(), diag::note_template_param_here);
4946 return true;
4947 }
4948
4949 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4950 << ParamType
4951 << FixItHint::CreateRemoval(AddrOpLoc);
4952 S.Diag(Param->getLocation(), diag::note_template_param_here);
4953
4954 ArgType = Var->getType();
4955 }
4956 } else if (!AddressTaken && ParamType->isPointerType()) {
4957 if (Var->getType()->isArrayType()) {
4958 // Array-to-pointer decay.
4959 ArgType = S.Context.getArrayDecayedType(Var->getType());
4960 } else {
4961 // If the template parameter has pointer type but the address of
4962 // this object was not taken, complain and (possibly) recover by
4963 // taking the address of the entity.
4964 ArgType = S.Context.getPointerType(Var->getType());
4965 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4966 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4967 << ParamType;
4968 S.Diag(Param->getLocation(), diag::note_template_param_here);
4969 return true;
4970 }
4971
4972 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4973 << ParamType
4974 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4975
4976 S.Diag(Param->getLocation(), diag::note_template_param_here);
4977 }
4978 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004979 }
Mike Stump11289f42009-09-09 15:08:12 +00004980
David Majnemer61c39a12013-08-23 05:39:39 +00004981 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4982 Arg, ArgType))
4983 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004984
4985 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004986 Converted =
4987 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004988 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004989 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004990}
4991
4992/// \brief Checks whether the given template argument is a pointer to
4993/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004994static bool CheckTemplateArgumentPointerToMember(Sema &S,
4995 NonTypeTemplateParmDecl *Param,
4996 QualType ParamType,
4997 Expr *&ResultArg,
4998 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004999 bool Invalid = false;
5000
Douglas Gregor20fdef32012-04-10 17:08:25 +00005001 // Check for a null pointer value.
5002 Expr *Arg = ResultArg;
5003 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
5004 case NPV_Error:
5005 return true;
5006 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005007 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005008 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5009 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00005010 return false;
5011 case NPV_NotNullPointer:
5012 break;
5013 }
5014
5015 bool ObjCLifetimeConversion;
5016 if (S.IsQualificationConversion(Arg->getType(),
5017 ParamType.getNonReferenceType(),
5018 false, ObjCLifetimeConversion)) {
5019 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005020 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00005021 ResultArg = Arg;
5022 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
5023 ParamType.getNonReferenceType())) {
5024 // We can't perform this conversion.
5025 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5026 << Arg->getType() << ParamType << Arg->getSourceRange();
5027 S.Diag(Param->getLocation(), diag::note_template_param_here);
5028 return true;
5029 }
5030
Douglas Gregorccb07762009-02-11 19:52:55 +00005031 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00005032 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00005033 Arg = Cast->getSubExpr();
5034
5035 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005036 //
Douglas Gregorccb07762009-02-11 19:52:55 +00005037 // A template-argument for a non-type, non-template
5038 // template-parameter shall be one of: [...]
5039 //
5040 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00005041 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00005042
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005043 // In C++98/03 mode, give an extension warning on any extra parentheses.
5044 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5045 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005046 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005047 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005048 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005049 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00005050 diag::warn_cxx98_compat_template_arg_extra_parens :
5051 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00005052 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005053 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00005054 }
5055
5056 Arg = Parens->getSubExpr();
5057 }
5058
John McCall7c454bb2011-07-15 05:09:51 +00005059 while (SubstNonTypeTemplateParmExpr *subst =
5060 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5061 Arg = subst->getReplacement()->IgnoreImpCasts();
5062
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005063 // A pointer-to-member constant written &Class::member.
5064 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00005065 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005066 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5067 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005068 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005070 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005071 // A constant of pointer-to-member type.
5072 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5073 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5074 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00005075 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005076 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005077 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005078 } else {
5079 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005080 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005081 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005082 return Invalid;
5083 }
5084 }
5085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005086
Craig Topperc3ec1492014-05-26 06:22:03 +00005087 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005089
Douglas Gregorccb07762009-02-11 19:52:55 +00005090 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005091 return S.Diag(Arg->getLocStart(),
5092 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00005093 << Arg->getSourceRange();
5094
David Majnemer3ac84e62013-10-22 21:56:38 +00005095 if (isa<FieldDecl>(DRE->getDecl()) ||
5096 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5097 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005098 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00005099 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00005100 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5101 "Only non-static member pointers can make it here");
5102
5103 // Okay: this is the address of a non-static member, and therefore
5104 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00005105 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005106 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005107 } else {
5108 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005109 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005110 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005111 return Invalid;
5112 }
5113
5114 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005115 S.Diag(Arg->getLocStart(),
5116 diag::err_template_arg_not_pointer_to_member_form)
5117 << Arg->getSourceRange();
5118 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00005119 return true;
5120}
5121
Douglas Gregord32e0282009-02-09 23:23:08 +00005122/// \brief Check a template argument against its corresponding
5123/// non-type template parameter.
5124///
Douglas Gregor463421d2009-03-03 04:44:36 +00005125/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00005126/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00005127/// returns the converted template argument. \p ParamType is the
5128/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00005129ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00005130 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00005131 TemplateArgument &Converted,
5132 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005133 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00005134
Richard Smith5f274382016-09-28 23:55:27 +00005135 // If the parameter type somehow involves auto, deduce the type now.
5136 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
Richard Smith87d263e2016-12-25 08:05:23 +00005137 // When checking a deduced template argument, deduce from its type even if
5138 // the type is dependent, in order to check the types of non-type template
5139 // arguments line up properly in partial ordering.
5140 Optional<unsigned> Depth;
5141 if (CTAK != CTAK_Specified)
5142 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00005143 if (DeduceAutoType(
5144 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00005145 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00005146 Diag(Arg->getExprLoc(),
5147 diag::err_non_type_template_parm_type_deduction_failure)
5148 << Param->getDeclName() << Param->getType() << Arg->getType()
5149 << Arg->getSourceRange();
5150 Diag(Param->getLocation(), diag::note_template_param_here);
5151 return ExprError();
5152 }
5153 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5154 // an error. The error message normally references the parameter
5155 // declaration, but here we'll pass the argument location because that's
5156 // where the parameter type is deduced.
5157 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5158 if (ParamType.isNull()) {
5159 Diag(Param->getLocation(), diag::note_template_param_here);
5160 return ExprError();
5161 }
5162 }
5163
Richard Smithd663fdd2014-12-17 20:42:37 +00005164 // We should have already dropped all cv-qualifiers by now.
5165 assert(!ParamType.hasQualifiers() &&
5166 "non-type template parameter type cannot be qualified");
5167
5168 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00005169 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00005170 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00005171 // FIXME: If either type is dependent, we skip the check. This isn't
5172 // correct, since during deduction we're supposed to have replaced each
5173 // template parameter with some unique (non-dependent) placeholder.
5174 // FIXME: If the argument type contains 'auto', we carry on and fail the
5175 // type check in order to force specific types to be more specialized than
5176 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5177 // work.
5178 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5179 !Arg->getType()->getContainedAutoType()) {
5180 Converted = TemplateArgument(Arg);
5181 return Arg;
5182 }
5183 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5184 // we should actually be checking the type of the template argument in P,
5185 // not the type of the template argument deduced from A, against the
5186 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00005187 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00005188 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00005189 << ParamType.getUnqualifiedType();
5190 Diag(Param->getLocation(), diag::note_template_param_here);
5191 return ExprError();
5192 }
5193
Richard Smith87d263e2016-12-25 08:05:23 +00005194 // If either the parameter has a dependent type or the argument is
5195 // type-dependent, there's nothing we can check now.
5196 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5197 // FIXME: Produce a cloned, canonical expression?
5198 Converted = TemplateArgument(Arg);
5199 return Arg;
5200 }
5201
Richard Smithe5945872017-01-06 22:52:53 +00005202 // The initialization of the parameter from the argument is
5203 // a constant-evaluated context.
5204 EnterExpressionEvaluationContext ConstantEvaluated(*this,
5205 Sema::ConstantEvaluated);
5206
Richard Smith410cc892014-11-26 03:26:53 +00005207 if (getLangOpts().CPlusPlus1z) {
Richard Smith410cc892014-11-26 03:26:53 +00005208 // C++1z [temp.arg.nontype]p1:
5209 // A template-argument for a non-type template parameter shall be
5210 // a converted constant expression of the type of the template-parameter.
5211 APValue Value;
5212 ExprResult ArgResult = CheckConvertedConstantExpression(
5213 Arg, ParamType, Value, CCEK_TemplateArg);
5214 if (ArgResult.isInvalid())
5215 return ExprError();
5216
Richard Smith52e624f2016-12-21 21:42:57 +00005217 // For a value-dependent argument, CheckConvertedConstantExpression is
5218 // permitted (and expected) to be unable to determine a value.
5219 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00005220 Converted = TemplateArgument(ArgResult.get());
5221 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00005222 }
5223
Richard Smithd663fdd2014-12-17 20:42:37 +00005224 QualType CanonParamType = Context.getCanonicalType(ParamType);
5225
Richard Smith410cc892014-11-26 03:26:53 +00005226 // Convert the APValue to a TemplateArgument.
5227 switch (Value.getKind()) {
5228 case APValue::Uninitialized:
5229 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005230 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005231 break;
5232 case APValue::Int:
5233 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005234 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005235 break;
5236 case APValue::MemberPointer: {
5237 assert(ParamType->isMemberPointerType());
5238
5239 // FIXME: We need TemplateArgument representation and mangling for these.
5240 if (!Value.getMemberPointerPath().empty()) {
5241 Diag(Arg->getLocStart(),
5242 diag::err_template_arg_member_ptr_base_derived_not_supported)
5243 << Value.getMemberPointerDecl() << ParamType
5244 << Arg->getSourceRange();
5245 return ExprError();
5246 }
5247
5248 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005249 Converted = VD ? TemplateArgument(VD, CanonParamType)
5250 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005251 break;
5252 }
5253 case APValue::LValue: {
5254 // For a non-type template-parameter of pointer or reference type,
5255 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00005256 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5257 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00005258 // -- a temporary object
5259 // -- a string literal
5260 // -- the result of a typeid expression, or
5261 // -- a predefind __func__ variable
5262 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5263 if (isa<CXXUuidofExpr>(E)) {
5264 Converted = TemplateArgument(const_cast<Expr*>(E));
5265 break;
5266 }
5267 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5268 << Arg->getSourceRange();
5269 return ExprError();
5270 }
5271 auto *VD = const_cast<ValueDecl *>(
5272 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5273 // -- a subobject
5274 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5275 VD && VD->getType()->isArrayType() &&
5276 Value.getLValuePath()[0].ArrayIndex == 0 &&
5277 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5278 // Per defect report (no number yet):
5279 // ... other than a pointer to the first element of a complete array
5280 // object.
5281 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5282 Value.isLValueOnePastTheEnd()) {
5283 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5284 << Value.getAsString(Context, ParamType);
5285 return ExprError();
5286 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005287 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005288 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005289 assert((!VD || !ParamType->isNullPtrType()) &&
5290 "non-null value of type nullptr_t?");
5291 Converted = VD ? TemplateArgument(VD, CanonParamType)
5292 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005293 break;
5294 }
5295 case APValue::AddrLabelDiff:
5296 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5297 case APValue::Float:
5298 case APValue::ComplexInt:
5299 case APValue::ComplexFloat:
5300 case APValue::Vector:
5301 case APValue::Array:
5302 case APValue::Struct:
5303 case APValue::Union:
5304 llvm_unreachable("invalid kind for template argument");
5305 }
5306
5307 return ArgResult.get();
5308 }
5309
Douglas Gregor86560402009-02-10 23:36:10 +00005310 // C++ [temp.arg.nontype]p5:
5311 // The following conversions are performed on each expression used
5312 // as a non-type template-argument. If a non-type
5313 // template-argument cannot be converted to the type of the
5314 // corresponding template-parameter then the program is
5315 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005316 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005317 // C++11:
5318 // -- for a non-type template-parameter of integral or
5319 // enumeration type, conversions permitted in a converted
5320 // constant expression are applied.
5321 //
5322 // C++98:
5323 // -- for a non-type template-parameter of integral or
5324 // enumeration type, integral promotions (4.5) and integral
5325 // conversions (4.7) are applied.
5326
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005327 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005328 // C++ [temp.arg.nontype]p1:
5329 // A template-argument for a non-type, non-template template-parameter
5330 // shall be one of:
5331 //
5332 // -- for a non-type template-parameter of integral or enumeration
5333 // type, a converted constant expression of the type of the
5334 // template-parameter; or
5335 llvm::APSInt Value;
5336 ExprResult ArgResult =
5337 CheckConvertedConstantExpression(Arg, ParamType, Value,
5338 CCEK_TemplateArg);
5339 if (ArgResult.isInvalid())
5340 return ExprError();
5341
Richard Smith01bfa682016-12-27 02:02:09 +00005342 // We can't check arbitrary value-dependent arguments.
5343 if (ArgResult.get()->isValueDependent()) {
5344 Converted = TemplateArgument(ArgResult.get());
5345 return ArgResult;
5346 }
5347
Richard Smithf8379a02012-01-18 23:55:52 +00005348 // Widen the argument value to sizeof(parameter type). This is almost
5349 // always a no-op, except when the parameter type is bool. In
5350 // that case, this may extend the argument from 1 bit to 8 bits.
5351 QualType IntegerType = ParamType;
5352 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5353 IntegerType = Enum->getDecl()->getIntegerType();
5354 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5355
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005356 Converted = TemplateArgument(Context, Value,
5357 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005358 return ArgResult;
5359 }
5360
Richard Smith08b12f12011-10-27 22:11:44 +00005361 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5362 if (ArgResult.isInvalid())
5363 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005364 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005365
5366 QualType ArgType = Arg->getType();
5367
Douglas Gregor86560402009-02-10 23:36:10 +00005368 // C++ [temp.arg.nontype]p1:
5369 // A template-argument for a non-type, non-template
5370 // template-parameter shall be one of:
5371 //
5372 // -- an integral constant-expression of integral or enumeration
5373 // type; or
5374 // -- the name of a non-type template-parameter; or
5375 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005376 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005377 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005378 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005379 diag::err_template_arg_not_integral_or_enumeral)
5380 << ArgType << Arg->getSourceRange();
5381 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005382 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005383 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005384 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5385 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005386
Douglas Gregore2b37442012-05-04 22:38:52 +00005387 public:
5388 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005389
5390 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5391 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005392 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5393 }
5394 } Diagnoser(ArgType);
5395
5396 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005397 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005398 if (!Arg)
5399 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005400 }
5401
Richard Smithd663fdd2014-12-17 20:42:37 +00005402 // From here on out, all we care about is the unqualified form
5403 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005404 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005405
5406 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005407 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005408 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005409 } else if (ParamType->isBooleanType()) {
5410 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005411 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005412 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5413 !ParamType->isEnumeralType()) {
5414 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005415 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005416 } else {
5417 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005418 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005419 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005420 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005421 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005422 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005423 }
5424
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005425 // Add the value of this argument to the list of converted
5426 // arguments. We use the bitwidth and signedness of the template
5427 // parameter.
5428 if (Arg->isValueDependent()) {
5429 // The argument is value-dependent. Create a new
5430 // TemplateArgument with the converted expression.
5431 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005432 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005433 }
5434
Douglas Gregor52aba872009-03-14 00:20:21 +00005435 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005436 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005437 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005438
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005439 if (ParamType->isBooleanType()) {
5440 // Value must be zero or one.
5441 Value = Value != 0;
5442 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5443 if (Value.getBitWidth() != AllowedBits)
5444 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005445 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005446 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005447 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005448
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005449 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005450 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005451 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005452 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005453 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005454 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00005455
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005456 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005457 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005458 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005459 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005460 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5461 << Arg->getSourceRange();
5462 Diag(Param->getLocation(), diag::note_template_param_here);
5463 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005464
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005465 // Complain if we overflowed the template parameter's type.
5466 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005467 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005468 RequiredBits = OldValue.getActiveBits();
5469 else if (OldValue.isUnsigned())
5470 RequiredBits = OldValue.getActiveBits() + 1;
5471 else
5472 RequiredBits = OldValue.getMinSignedBits();
5473 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005474 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005475 diag::warn_template_arg_too_large)
5476 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5477 << Arg->getSourceRange();
5478 Diag(Param->getLocation(), diag::note_template_param_here);
5479 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005480 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005481
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005482 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00005483 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005484 ? Context.getCanonicalType(ParamType)
5485 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005486 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005487 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005488
Richard Smith08b12f12011-10-27 22:11:44 +00005489 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005490 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5491
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005492 // Handle pointer-to-function, reference-to-function, and
5493 // pointer-to-member-function all in (roughly) the same way.
5494 if (// -- For a non-type template-parameter of type pointer to
5495 // function, only the function-to-pointer conversion (4.3) is
5496 // applied. If the template-argument represents a set of
5497 // overloaded functions (or a pointer to such), the matching
5498 // function is selected from the set (13.4).
5499 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005500 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005501 // -- For a non-type template-parameter of type reference to
5502 // function, no conversions apply. If the template-argument
5503 // represents a set of overloaded functions, the matching
5504 // function is selected from the set (13.4).
5505 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005506 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005507 // -- For a non-type template-parameter of type pointer to
5508 // member function, no conversions apply. If the
5509 // template-argument represents a set of overloaded member
5510 // functions, the matching member function is selected from
5511 // the set (13.4).
5512 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005513 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005514 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005515
Douglas Gregor064fdb22010-04-14 23:11:21 +00005516 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005517 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005518 true,
5519 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005520 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005521 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005522
5523 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5524 ArgType = Arg->getType();
5525 } else
John Wiegley01296292011-04-08 18:41:53 +00005526 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005527 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005528
John Wiegley01296292011-04-08 18:41:53 +00005529 if (!ParamType->isMemberPointerType()) {
5530 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5531 ParamType,
5532 Arg, Converted))
5533 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005534 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005535 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005536
Douglas Gregor20fdef32012-04-10 17:08:25 +00005537 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5538 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005539 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005540 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005541 }
5542
Chris Lattner696197c2009-02-20 21:37:53 +00005543 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005544 // -- for a non-type template-parameter of type pointer to
5545 // object, qualification conversions (4.4) and the
5546 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005547 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005548 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005549 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005550
John Wiegley01296292011-04-08 18:41:53 +00005551 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5552 ParamType,
5553 Arg, Converted))
5554 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005555 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005556 }
Mike Stump11289f42009-09-09 15:08:12 +00005557
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005558 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005559 // -- For a non-type template-parameter of type reference to
5560 // object, no conversions apply. The type referred to by the
5561 // reference may be more cv-qualified than the (otherwise
5562 // identical) type of the template-argument. The
5563 // template-parameter is bound directly to the
5564 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005565 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005566 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005567
Douglas Gregor064fdb22010-04-14 23:11:21 +00005568 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005569 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5570 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005571 true,
5572 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005573 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005574 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005575
5576 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5577 ArgType = Arg->getType();
5578 } else
John Wiegley01296292011-04-08 18:41:53 +00005579 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005580 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005581
John Wiegley01296292011-04-08 18:41:53 +00005582 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5583 ParamType,
5584 Arg, Converted))
5585 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005586 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005587 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005588
Douglas Gregor20fdef32012-04-10 17:08:25 +00005589 // Deal with parameters of type std::nullptr_t.
5590 if (ParamType->isNullPtrType()) {
5591 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5592 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005593 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005594 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005595
Douglas Gregor20fdef32012-04-10 17:08:25 +00005596 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5597 case NPV_NotNullPointer:
5598 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5599 << Arg->getType() << ParamType;
5600 Diag(Param->getLocation(), diag::note_template_param_here);
5601 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005602
Douglas Gregor20fdef32012-04-10 17:08:25 +00005603 case NPV_Error:
5604 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005605
Douglas Gregor20fdef32012-04-10 17:08:25 +00005606 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005607 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005608 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5609 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005610 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005611 }
5612 }
5613
Douglas Gregor0e558532009-02-11 16:16:59 +00005614 // -- For a non-type template-parameter of type pointer to data
5615 // member, qualification conversions (4.4) are applied.
5616 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5617
Douglas Gregor20fdef32012-04-10 17:08:25 +00005618 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5619 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005620 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005621 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005622}
5623
Richard Smith26b86ea2016-12-31 21:41:23 +00005624static void DiagnoseTemplateParameterListArityMismatch(
5625 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
5626 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
5627
Douglas Gregord32e0282009-02-09 23:23:08 +00005628/// \brief Check a template argument against its corresponding
5629/// template template parameter.
5630///
5631/// This routine implements the semantics of C++ [temp.arg.template].
5632/// It returns true if an error occurred, and false otherwise.
5633bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005634 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005635 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005636 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005637 TemplateDecl *Template = Name.getAsTemplateDecl();
5638 if (!Template) {
5639 // Any dependent template name is fine.
5640 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5641 return false;
5642 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005643
Richard Smith26b86ea2016-12-31 21:41:23 +00005644 if (Template->isInvalidDecl())
5645 return true;
5646
Richard Smith3f1b5d02011-05-05 21:57:07 +00005647 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005648 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005649 // the name of a class template or an alias template, expressed as an
5650 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005651 // primary class templates are considered when matching the
5652 // template template argument with the corresponding parameter;
5653 // partial specializations are not considered even if their
5654 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005655 //
5656 // Note that we also allow template template parameters here, which
5657 // will happen when we are dealing with, e.g., class template
5658 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005659 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005660 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00005661 !isa<TypeAliasTemplateDecl>(Template) &&
5662 !isa<BuiltinTemplateDecl>(Template)) {
5663 assert(isa<FunctionTemplateDecl>(Template) &&
5664 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00005665 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00005666 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5667 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00005668 }
5669
Richard Smith1fde8ec2012-09-07 02:06:42 +00005670 TemplateParameterList *Params = Param->getTemplateParameters();
5671 if (Param->isExpandedParameterPack())
5672 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5673
Richard Smith26b86ea2016-12-31 21:41:23 +00005674 // C++1z [temp.arg.template]p3: (DR 150)
5675 // A template-argument matches a template template-parameter P when P
5676 // is at least as specialized as the template-argument A.
5677 if (getLangOpts().RelaxedTemplateTemplateArgs) {
5678 // Quick check for the common case:
5679 // If P contains a parameter pack, then A [...] matches P if each of A's
5680 // template parameters matches the corresponding template parameter in
5681 // the template-parameter-list of P.
5682 if (TemplateParameterListsAreEqual(
5683 Template->getTemplateParameters(), Params, false,
5684 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
5685 return false;
5686
5687 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
5688 Arg.getLocation()))
5689 return false;
5690 // FIXME: Produce better diagnostics for deduction failures.
5691 }
5692
Douglas Gregor85e0f662009-02-10 00:24:35 +00005693 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005694 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005695 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005696 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005697 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005698}
5699
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005700/// \brief Given a non-type template argument that refers to a
5701/// declaration and the type of its corresponding non-type template
5702/// parameter, produce an expression that properly refers to that
5703/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005704ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005705Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5706 QualType ParamType,
5707 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005708 // C++ [temp.param]p8:
5709 //
5710 // A non-type template-parameter of type "array of T" or
5711 // "function returning T" is adjusted to be of type "pointer to
5712 // T" or "pointer to function returning T", respectively.
5713 if (ParamType->isArrayType())
5714 ParamType = Context.getArrayDecayedType(ParamType);
5715 else if (ParamType->isFunctionType())
5716 ParamType = Context.getPointerType(ParamType);
5717
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005718 // For a NULL non-type template argument, return nullptr casted to the
5719 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005720 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005721 return ImpCastExprToType(
5722 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5723 ParamType,
5724 ParamType->getAs<MemberPointerType>()
5725 ? CK_NullToMemberPointer
5726 : CK_NullToPointer);
5727 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005728 assert(Arg.getKind() == TemplateArgument::Declaration &&
5729 "Only declaration template arguments permitted here");
5730
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005731 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5732
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005733 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005734 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5735 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005736 // If the value is a class member, we might have a pointer-to-member.
5737 // Determine whether the non-type template template parameter is of
5738 // pointer-to-member type. If so, we need to build an appropriate
5739 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5740 // would refer to the member itself.
5741 if (ParamType->isMemberPointerType()) {
5742 QualType ClassType
5743 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5744 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005745 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005746 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005747 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005748 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005749
5750 // The actual value-ness of this is unimportant, but for
5751 // internal consistency's sake, references to instance methods
5752 // are r-values.
5753 ExprValueKind VK = VK_LValue;
5754 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5755 VK = VK_RValue;
5756
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005757 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005758 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005759 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005760 Loc,
5761 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005762 if (RefExpr.isInvalid())
5763 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005764
John McCalle3027922010-08-25 11:45:40 +00005765 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005766
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005767 // We might need to perform a trailing qualification conversion, since
5768 // the element type on the parameter could be more qualified than the
5769 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005770 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005771 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005772 ParamType.getUnqualifiedType(), false,
5773 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005774 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005775
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005776 assert(!RefExpr.isInvalid() &&
5777 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005778 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005779 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005780 }
5781 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005782
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005783 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005784
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005785 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005786 // When the non-type template parameter is a pointer, take the
5787 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005788 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005789 if (RefExpr.isInvalid())
5790 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005791
5792 if (T->isFunctionType() || T->isArrayType()) {
5793 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005794 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005795 if (RefExpr.isInvalid())
5796 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005797
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005798 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005800
Douglas Gregorb242683d2010-04-01 18:32:35 +00005801 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005802 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005803 }
5804
John McCall7decc9e2010-11-18 06:31:45 +00005805 ExprValueKind VK = VK_RValue;
5806
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005807 // If the non-type template parameter has reference type, qualify the
5808 // resulting declaration reference with the extra qualifiers on the
5809 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005810 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5811 VK = VK_LValue;
5812 T = Context.getQualifiedType(T,
5813 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005814 } else if (isa<FunctionDecl>(VD)) {
5815 // References to functions are always lvalues.
5816 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005818
John McCall7decc9e2010-11-18 06:31:45 +00005819 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005820}
5821
5822/// \brief Construct a new expression that refers to the given
5823/// integral template argument with the given source-location
5824/// information.
5825///
5826/// This routine takes care of the mapping from an integral template
5827/// argument (which may have any integral type) to the appropriate
5828/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005829ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005830Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5831 SourceLocation Loc) {
5832 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005833 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005834 QualType OrigT = Arg.getIntegralType();
5835
5836 // If this is an enum type that we're instantiating, we need to use an integer
5837 // type the same size as the enumerator. We don't want to build an
5838 // IntegerLiteral with enum type. The integer type of an enum type can be of
5839 // any integral type with C++11 enum classes, make sure we create the right
5840 // type of literal for it.
5841 QualType T = OrigT;
5842 if (const EnumType *ET = OrigT->getAs<EnumType>())
5843 T = ET->getDecl()->getIntegerType();
5844
5845 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005846 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005847 // This does not need to handle u8 character literals because those are
5848 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005849 CharacterLiteral::CharacterKind Kind;
5850 if (T->isWideCharType())
5851 Kind = CharacterLiteral::Wide;
5852 else if (T->isChar16Type())
5853 Kind = CharacterLiteral::UTF16;
5854 else if (T->isChar32Type())
5855 Kind = CharacterLiteral::UTF32;
5856 else
5857 Kind = CharacterLiteral::Ascii;
5858
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005859 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5860 Kind, T, Loc);
5861 } else if (T->isBooleanType()) {
5862 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5863 T, Loc);
5864 } else if (T->isNullPtrType()) {
5865 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5866 } else {
5867 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005868 }
5869
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005870 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005871 // FIXME: This is a hack. We need a better way to handle substituted
5872 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005873 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5874 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005875 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005876 Loc, Loc);
5877 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005878
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005879 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005880}
5881
Richard Smith43a833b2017-01-09 23:54:33 +00005882static bool isDependentOnOuter(NonTypeTemplateParmDecl *NTTP) {
5883 if (NTTP->getDepth() == 0 || !NTTP->getType()->isDependentType())
5884 return false;
5885 DependencyChecker Checker(NTTP->getDepth(), /*IgnoreNonTypeDependent*/ false,
5886 /*FindLessThanDepth*/ true);
5887 Checker.TraverseType(NTTP->getType());
5888 return Checker.Match;
5889}
5890
Douglas Gregor641040a2011-01-12 23:45:44 +00005891/// \brief Match two template parameters within template parameter lists.
5892static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5893 bool Complain,
5894 Sema::TemplateParameterListEqualKind Kind,
5895 SourceLocation TemplateArgLoc) {
5896 // Check the actual kind (type, non-type, template).
5897 if (Old->getKind() != New->getKind()) {
5898 if (Complain) {
5899 unsigned NextDiag = diag::err_template_param_different_kind;
5900 if (TemplateArgLoc.isValid()) {
5901 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5902 NextDiag = diag::note_template_param_different_kind;
5903 }
5904 S.Diag(New->getLocation(), NextDiag)
5905 << (Kind != Sema::TPL_TemplateMatch);
5906 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5907 << (Kind != Sema::TPL_TemplateMatch);
5908 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005909
Douglas Gregor641040a2011-01-12 23:45:44 +00005910 return false;
5911 }
5912
Richard Smith26b86ea2016-12-31 21:41:23 +00005913 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005914 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005915 // template template parameter, the template template parameter can have
5916 // a parameter pack where the template template argument does not.
5917 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5918 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5919 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005920 if (Complain) {
5921 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5922 if (TemplateArgLoc.isValid()) {
5923 S.Diag(TemplateArgLoc,
5924 diag::err_template_arg_template_params_mismatch);
5925 NextDiag = diag::note_template_parameter_pack_non_pack;
5926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005927
Douglas Gregor641040a2011-01-12 23:45:44 +00005928 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5929 : isa<NonTypeTemplateParmDecl>(New)? 1
5930 : 2;
5931 S.Diag(New->getLocation(), NextDiag)
5932 << ParamKind << New->isParameterPack();
5933 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5934 << ParamKind << Old->isParameterPack();
5935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005936
Douglas Gregor641040a2011-01-12 23:45:44 +00005937 return false;
5938 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005939
Douglas Gregor641040a2011-01-12 23:45:44 +00005940 // For non-type template parameters, check the type of the parameter.
5941 if (NonTypeTemplateParmDecl *OldNTTP
5942 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5943 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005944
Douglas Gregor641040a2011-01-12 23:45:44 +00005945 // If we are matching a template template argument to a template
5946 // template parameter and one of the non-type template parameter types
Richard Smith43a833b2017-01-09 23:54:33 +00005947 // is dependent on an outer template's parameter, then we must wait until
5948 // template instantiation time to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00005949 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith43a833b2017-01-09 23:54:33 +00005950 (isDependentOnOuter(OldNTTP) || isDependentOnOuter(NewNTTP)))
Douglas Gregor641040a2011-01-12 23:45:44 +00005951 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005952
Douglas Gregor641040a2011-01-12 23:45:44 +00005953 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5954 if (Complain) {
5955 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5956 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005957 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005958 diag::err_template_arg_template_params_mismatch);
5959 NextDiag = diag::note_template_nontype_parm_different_type;
5960 }
5961 S.Diag(NewNTTP->getLocation(), NextDiag)
5962 << NewNTTP->getType()
5963 << (Kind != Sema::TPL_TemplateMatch);
5964 S.Diag(OldNTTP->getLocation(),
5965 diag::note_template_nontype_parm_prev_declaration)
5966 << OldNTTP->getType();
5967 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005968
Douglas Gregor641040a2011-01-12 23:45:44 +00005969 return false;
5970 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005971
Douglas Gregor641040a2011-01-12 23:45:44 +00005972 return true;
5973 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005974
Douglas Gregor641040a2011-01-12 23:45:44 +00005975 // For template template parameters, check the template parameter types.
5976 // The template parameter lists of template template
5977 // parameters must agree.
5978 if (TemplateTemplateParmDecl *OldTTP
5979 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005980 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005981 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5982 OldTTP->getTemplateParameters(),
5983 Complain,
5984 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005985 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005986 : Kind),
5987 TemplateArgLoc);
5988 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005989
Douglas Gregor641040a2011-01-12 23:45:44 +00005990 return true;
5991}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005992
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005993/// \brief Diagnose a known arity mismatch when comparing template argument
5994/// lists.
5995static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005996void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005997 TemplateParameterList *New,
5998 TemplateParameterList *Old,
5999 Sema::TemplateParameterListEqualKind Kind,
6000 SourceLocation TemplateArgLoc) {
6001 unsigned NextDiag = diag::err_template_param_list_different_arity;
6002 if (TemplateArgLoc.isValid()) {
6003 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6004 NextDiag = diag::note_template_param_list_different_arity;
6005 }
6006 S.Diag(New->getTemplateLoc(), NextDiag)
6007 << (New->size() > Old->size())
6008 << (Kind != Sema::TPL_TemplateMatch)
6009 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6010 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6011 << (Kind != Sema::TPL_TemplateMatch)
6012 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6013}
6014
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006015/// \brief Determine whether the given template parameter lists are
6016/// equivalent.
6017///
Mike Stump11289f42009-09-09 15:08:12 +00006018/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006019/// source code as part of a new template declaration.
6020///
6021/// \param Old The old template parameter list, typically found via
6022/// name lookup of the template declared with this template parameter
6023/// list.
6024///
6025/// \param Complain If true, this routine will produce a diagnostic if
6026/// the template parameter lists are not equivalent.
6027///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006028/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00006029///
6030/// \param TemplateArgLoc If this source location is valid, then we
6031/// are actually checking the template parameter list of a template
6032/// argument (New) against the template parameter list of its
6033/// corresponding template template parameter (Old). We produce
6034/// slightly different diagnostics in this scenario.
6035///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006036/// \returns True if the template parameter lists are equal, false
6037/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00006038bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006039Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6040 TemplateParameterList *Old,
6041 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006042 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00006043 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006044 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6045 if (Complain)
6046 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6047 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006048
6049 return false;
6050 }
6051
Douglas Gregor641040a2011-01-12 23:45:44 +00006052 // C++0x [temp.arg.template]p3:
6053 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006054 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00006055 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006056 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006057 // template-parameter-list of P. [...]
6058 TemplateParameterList::iterator NewParm = New->begin();
6059 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006060 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006061 OldParmEnd = Old->end();
6062 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00006063 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6064 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006065 if (NewParm == NewParmEnd) {
6066 if (Complain)
6067 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6068 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006069
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006070 return false;
6071 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006072
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006073 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6074 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006075 return false;
6076
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006077 ++NewParm;
6078 continue;
6079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006080
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006081 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006082 // [...] When P's template- parameter-list contains a template parameter
6083 // pack (14.5.3), the template parameter pack will match zero or more
6084 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006085 // template-parameter-list of A with the same type and form as the
6086 // template parameter pack in P (ignoring whether those template
6087 // parameters are template parameter packs).
6088 for (; NewParm != NewParmEnd; ++NewParm) {
6089 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6090 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006091 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006092 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006094
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006095 // Make sure we exhausted all of the arguments.
6096 if (NewParm != NewParmEnd) {
6097 if (Complain)
6098 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6099 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006100
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006101 return false;
6102 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006103
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006104 return true;
6105}
6106
6107/// \brief Check whether a template can be declared within this scope.
6108///
6109/// If the template declaration is valid in this scope, returns
6110/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00006111bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006112Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00006113 if (!S)
6114 return false;
6115
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006116 // Find the nearest enclosing declaration scope.
6117 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6118 (S->getFlags() & Scope::TemplateParamScope) != 0)
6119 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006120
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006121 // C++ [temp]p4:
6122 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00006123 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00006124 if (Ctx && Ctx->isExternCContext()) {
6125 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6126 << TemplateParams->getSourceRange();
6127 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6128 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6129 return true;
6130 }
Richard Smith8df390f2016-09-08 23:14:54 +00006131 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006132
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006133 // C++ [temp]p2:
6134 // A template-declaration can appear only as a namespace scope or
6135 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00006136 if (Ctx) {
6137 if (Ctx->isFileContext())
6138 return false;
6139 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6140 // C++ [temp.mem]p2:
6141 // A local class shall not have member templates.
6142 if (RD->isLocalClass())
6143 return Diag(TemplateParams->getTemplateLoc(),
6144 diag::err_template_inside_local_class)
6145 << TemplateParams->getSourceRange();
6146 else
6147 return false;
6148 }
6149 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006150
Mike Stump11289f42009-09-09 15:08:12 +00006151 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006152 diag::err_template_outside_namespace_or_class_scope)
6153 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006154}
Douglas Gregor67a65642009-02-17 23:15:12 +00006155
Douglas Gregor54888652009-10-07 00:13:32 +00006156/// \brief Determine what kind of template specialization the given declaration
6157/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006158static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00006159 if (!D)
6160 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006161
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006162 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6163 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00006164 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6165 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006166 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6167 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006168
Douglas Gregor54888652009-10-07 00:13:32 +00006169 return TSK_Undeclared;
6170}
6171
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006172/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006173/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00006174///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006175/// This routine determines whether a template specialization can be declared
6176/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00006177///
6178/// \param S the semantic analysis object for which this check is being
6179/// performed.
6180///
6181/// \param Specialized the entity being specialized or instantiated, which
6182/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006183/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00006184/// member class).
6185///
6186/// \param PrevDecl the previous declaration of this entity, if any.
6187///
6188/// \param Loc the location of the explicit specialization or instantiation of
6189/// this entity.
6190///
6191/// \param IsPartialSpecialization whether this is a partial specialization of
6192/// a class template.
6193///
Douglas Gregor54888652009-10-07 00:13:32 +00006194/// \returns true if there was an error that we cannot recover from, false
6195/// otherwise.
6196static bool CheckTemplateSpecializationScope(Sema &S,
6197 NamedDecl *Specialized,
6198 NamedDecl *PrevDecl,
6199 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006200 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00006201 // Keep these "kind" numbers in sync with the %select statements in the
6202 // various diagnostics emitted by this routine.
6203 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006204 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006205 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006206 else if (isa<VarTemplateDecl>(Specialized))
6207 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006208 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006209 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006210 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006211 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006212 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00006213 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006214 else if (isa<RecordDecl>(Specialized))
6215 EntityKind = 7;
6216 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6217 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00006218 else {
Richard Smith7d137e32012-03-23 03:33:32 +00006219 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006220 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006221 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00006222 return true;
6223 }
6224
Douglas Gregorf47b9112009-02-25 22:02:03 +00006225 // C++ [temp.expl.spec]p2:
6226 // An explicit specialization shall be declared in the namespace
6227 // of which the template is a member, or, for member templates, in
6228 // the namespace of which the enclosing class or enclosing class
6229 // template is a member. An explicit specialization of a member
6230 // function, member class or static data member of a class
6231 // template shall be declared in the namespace of which the class
6232 // template is a member. Such a declaration may also be a
6233 // definition. If the declaration is not a definition, the
6234 // specialization may be defined later in the name- space in which
6235 // the explicit specialization was declared, or in a namespace
6236 // that encloses the one in which the explicit specialization was
6237 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00006238 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00006239 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006240 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006241 return true;
6242 }
Douglas Gregore4b05162009-10-07 17:21:34 +00006243
Douglas Gregor40fb7442009-10-07 17:30:37 +00006244 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006245 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006246 // Do not warn for class scope explicit specialization during
6247 // instantiation, warning was already emitted during pattern
6248 // semantic analysis.
6249 if (!S.ActiveTemplateInstantiations.size())
6250 S.Diag(Loc, diag::ext_function_specialization_in_class)
6251 << Specialized;
6252 } else {
6253 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6254 << Specialized;
6255 return true;
6256 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006257 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006258
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006259 if (S.CurContext->isRecord() &&
6260 !S.CurContext->Equals(Specialized->getDeclContext())) {
6261 // Make sure that we're specializing in the right record context.
6262 // Otherwise, things can go horribly wrong.
6263 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6264 << Specialized;
6265 return true;
6266 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006267
Douglas Gregore4b05162009-10-07 17:21:34 +00006268 // C++ [temp.class.spec]p6:
6269 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006270 // in any namespace scope in which its definition may be defined (14.5.1
6271 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00006272 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00006273 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00006274 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00006275
6276 // Make sure that this redeclaration (or definition) occurs in an enclosing
6277 // namespace.
6278 // Note that HandleDeclarator() performs this check for explicit
6279 // specializations of function templates, static data members, and member
6280 // functions, so we skip the check here for those kinds of entities.
6281 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6282 // Should we refactor that check, so that it occurs later?
6283 if (!DC->Encloses(SpecializedContext) &&
6284 !(isa<FunctionTemplateDecl>(Specialized) ||
6285 isa<FunctionDecl>(Specialized) ||
6286 isa<VarTemplateDecl>(Specialized) ||
6287 isa<VarDecl>(Specialized))) {
6288 if (isa<TranslationUnitDecl>(SpecializedContext))
6289 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6290 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00006291 else if (isa<NamespaceDecl>(SpecializedContext)) {
6292 int Diag = diag::err_template_spec_redecl_out_of_scope;
6293 if (S.getLangOpts().MicrosoftExt)
6294 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6295 S.Diag(Loc, Diag) << EntityKind << Specialized
6296 << cast<NamedDecl>(SpecializedContext);
6297 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00006298 llvm_unreachable("unexpected namespace context for specialization");
6299
6300 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6301 } else if ((!PrevDecl ||
6302 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6303 getTemplateSpecializationKind(PrevDecl) ==
6304 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006305 // C++ [temp.exp.spec]p2:
6306 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006307 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006308 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006309 // An explicit specialization of a member function, member class or
6310 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006311 // namespace of which the class template is a member.
6312 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006313 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006314 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006315 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006316 // C++11 [temp.explicit]p3:
6317 // An explicit instantiation shall appear in an enclosing namespace of its
6318 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006319 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006320 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006321 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006322 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006323 "DC encloses TU but isn't in enclosing namespace set");
6324 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006325 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006326 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6327 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006328 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006329 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006330 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006331 Diag = diag::ext_template_spec_decl_out_of_scope;
6332 else
6333 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6334 S.Diag(Loc, Diag)
6335 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6336 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006337
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006338 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006339 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006341
Douglas Gregorf47b9112009-02-25 22:02:03 +00006342 return false;
6343}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006344
Richard Smith57aae072016-12-28 02:37:25 +00006345static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
6346 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00006347 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006348 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006349 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00006350 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006351 return E->getSourceRange();
6352 return Checker.MatchLoc;
6353}
6354
6355static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6356 if (!TL.getType()->isDependentType())
6357 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006358 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006359 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00006360 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006361 return TL.getSourceRange();
6362 return Checker.MatchLoc;
6363}
6364
Larisse Voufo39a1e502013-08-06 01:03:05 +00006365/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006366/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006367static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006368 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6369 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006370 for (unsigned I = 0; I != NumArgs; ++I) {
6371 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006372 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006373 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6374 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006375 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006376
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006377 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006379
Eli Friedmanb826a002012-09-26 02:36:12 +00006380 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006381 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006382
6383 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006384
Douglas Gregor98318c22011-01-03 21:37:45 +00006385 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006386 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6387 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006388
6389 // Strip off any implicit casts we added as part of type checking.
6390 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6391 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006392
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006393 // C++ [temp.class.spec]p8:
6394 // A non-type argument is non-specialized if it is the name of a
6395 // non-type parameter. All other non-type arguments are
6396 // specialized.
6397 //
6398 // Below, we check the two conditions that only apply to
6399 // specialized non-type arguments, so skip any non-specialized
6400 // arguments.
6401 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006402 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006403 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006404
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006405 // C++ [temp.class.spec]p9:
6406 // Within the argument list of a class template partial
6407 // specialization, the following restrictions apply:
6408 // -- A partially specialized non-type argument expression
6409 // shall not involve a template parameter of the partial
6410 // specialization except when the argument expression is a
6411 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00006412 // -- The type of a template parameter corresponding to a
6413 // specialized non-type argument shall not be dependent on a
6414 // parameter of the specialization.
6415 // DR1315 removes the first bullet, leaving an incoherent set of rules.
6416 // We implement a compromise between the original rules and DR1315:
6417 // -- A specialized non-type template argument shall not be
6418 // type-dependent and the corresponding template parameter
6419 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00006420 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00006421 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00006422 if (ParamUseRange.isValid()) {
6423 if (IsDefaultArgument) {
6424 S.Diag(TemplateNameLoc,
6425 diag::err_dependent_non_type_arg_in_partial_spec);
6426 S.Diag(ParamUseRange.getBegin(),
6427 diag::note_dependent_non_type_default_arg_in_partial_spec)
6428 << ParamUseRange;
6429 } else {
6430 S.Diag(ParamUseRange.getBegin(),
6431 diag::err_dependent_non_type_arg_in_partial_spec)
6432 << ParamUseRange;
6433 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006434 return true;
6435 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006436
Richard Smith6056d5e2014-02-09 00:54:43 +00006437 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00006438 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00006439 if (ParamUseRange.isValid()) {
6440 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6441 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Richard Smith57aae072016-12-28 02:37:25 +00006442 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00006443 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00006444 << (IsDefaultArgument ? ParamUseRange : SourceRange())
6445 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006446 return true;
6447 }
6448 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006449
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006450 return false;
6451}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006452
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006453/// \brief Check the non-type template arguments of a class template
6454/// partial specialization according to C++ [temp.class.spec]p9.
6455///
Richard Smith6056d5e2014-02-09 00:54:43 +00006456/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00006457/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006458/// template.
6459/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006460/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006461/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006462///
Richard Smith6056d5e2014-02-09 00:54:43 +00006463/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00006464bool Sema::CheckTemplatePartialSpecializationArgs(
6465 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
6466 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
6467 // We have to be conservative when checking a template in a dependent
6468 // context.
6469 if (PrimaryTemplate->getDeclContext()->isDependentContext())
6470 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006471
Richard Smith57aae072016-12-28 02:37:25 +00006472 TemplateParameterList *TemplateParams =
6473 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006474 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6475 NonTypeTemplateParmDecl *Param
6476 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6477 if (!Param)
6478 continue;
6479
Richard Smith57aae072016-12-28 02:37:25 +00006480 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
6481 Param, &TemplateArgs[I],
6482 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006483 return true;
6484 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006485
6486 return false;
6487}
6488
John McCall48871652010-08-21 09:40:31 +00006489DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006490Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6491 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006492 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006493 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006494 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006495 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006496 MultiTemplateParamsArg
6497 TemplateParameterLists,
6498 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006499 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006500
Richard Smith4b55a9c2014-04-17 03:29:33 +00006501 CXXScopeSpec &SS = TemplateId.SS;
6502
Abramo Bagnara60804e12011-03-18 15:16:37 +00006503 // NOTE: KWLoc is the location of the tag keyword. This will instead
6504 // store the location of the outermost template keyword in the declaration.
6505 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006506 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6507 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6508 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6509 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006510
Douglas Gregor67a65642009-02-17 23:15:12 +00006511 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006512 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006513 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006514 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6515
6516 if (!ClassTemplate) {
6517 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006518 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006519 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6520 return true;
6521 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006522
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006523 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006524 bool isPartialSpecialization = false;
6525
Douglas Gregorf47b9112009-02-25 22:02:03 +00006526 // Check the validity of the template headers that introduce this
6527 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006528 // FIXME: We probably shouldn't complain about these headers for
6529 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006530 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006531 TemplateParameterList *TemplateParams =
6532 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006533 KWLoc, TemplateNameLoc, SS, &TemplateId,
6534 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6535 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006536 if (Invalid)
6537 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006538
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006539 if (TemplateParams && TemplateParams->size() > 0) {
6540 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006541
Douglas Gregorec9518b2010-12-21 08:14:57 +00006542 if (TUK == TUK_Friend) {
6543 Diag(KWLoc, diag::err_partial_specialization_friend)
6544 << SourceRange(LAngleLoc, RAngleLoc);
6545 return true;
6546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006547
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006548 // C++ [temp.class.spec]p10:
6549 // The template parameter list of a specialization shall not
6550 // contain default template argument values.
6551 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6552 Decl *Param = TemplateParams->getParam(I);
6553 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6554 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006555 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006556 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006557 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006558 }
6559 } else if (NonTypeTemplateParmDecl *NTTP
6560 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6561 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006562 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006563 diag::err_default_arg_in_partial_spec)
6564 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006565 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006566 }
6567 } else {
6568 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006569 if (TTP->hasDefaultArgument()) {
6570 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006571 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006572 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006573 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006574 }
6575 }
6576 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006577 } else if (TemplateParams) {
6578 if (TUK == TUK_Friend)
6579 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006580 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006581 SourceRange(TemplateParams->getTemplateLoc(),
6582 TemplateParams->getRAngleLoc()))
6583 << SourceRange(LAngleLoc, RAngleLoc);
6584 else
6585 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006586 } else {
6587 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006588 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006589
Douglas Gregor67a65642009-02-17 23:15:12 +00006590 // Check that the specialization uses the same tag kind as the
6591 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006592 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6593 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006594 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006595 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006596 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006597 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006598 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006599 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006600 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006601 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006602 diag::note_previous_use);
6603 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6604 }
6605
Douglas Gregorc40290e2009-03-09 23:48:35 +00006606 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006607 TemplateArgumentListInfo TemplateArgs =
6608 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006609
Douglas Gregor14406932011-01-03 20:35:03 +00006610 // Check for unexpanded parameter packs in any of the template arguments.
6611 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006612 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006613 UPPC_PartialSpecialization))
6614 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006615
Douglas Gregor67a65642009-02-17 23:15:12 +00006616 // Check that the template argument list is well-formed for this
6617 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006618 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006619 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6620 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006621 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006622
Douglas Gregor2373c592009-05-31 09:31:02 +00006623 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006624 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006625 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00006626 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
6627 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006628 return true;
6629
Richard Smith57aae072016-12-28 02:37:25 +00006630 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
6631 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00006632 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006633 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006634 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00006635 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006636 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6637 << ClassTemplate->getDeclName();
6638 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006639 }
6640 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006641
Craig Topperc3ec1492014-05-26 06:22:03 +00006642 void *InsertPos = nullptr;
6643 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006644
6645 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006646 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006647 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006648 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006649 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006650
Craig Topperc3ec1492014-05-26 06:22:03 +00006651 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006652
Douglas Gregorf47b9112009-02-25 22:02:03 +00006653 // Check whether we can declare a class template specialization in
6654 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006655 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006656 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6657 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006658 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006659 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006660
Douglas Gregor15301382009-07-30 17:40:51 +00006661 // The canonical type
6662 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006663 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006664 // Build the canonical type that describes the converted template
6665 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006666 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6667 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00006668 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006669
6670 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006671 ClassTemplate->getInjectedClassNameSpecialization())) {
6672 // C++ [temp.class.spec]p9b3:
6673 //
6674 // -- The argument list of the specialization shall not be identical
6675 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00006676 //
6677 // This rule has since been removed, because it's redundant given DR1495,
6678 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006679 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006680 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006681 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006682 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6683 ClassTemplate->getIdentifier(),
6684 TemplateNameLoc,
6685 Attr,
6686 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006687 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006688 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006689 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006690 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006691 }
Douglas Gregor15301382009-07-30 17:40:51 +00006692
Douglas Gregor2373c592009-05-31 09:31:02 +00006693 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006694 ClassTemplatePartialSpecializationDecl *PrevPartial
6695 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006696 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006697 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006698 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006699 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006700 TemplateParams,
6701 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006702 Converted,
John McCall6b51f282009-11-23 01:53:49 +00006703 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006704 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006705 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006706 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006707 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006708 Partial->setTemplateParameterListsInfo(
6709 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006710 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006711
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006712 if (!PrevPartial)
6713 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006714 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006715
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006716 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006717 // template specialization, make a note of that.
6718 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6719 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006720
Richard Smith57aae072016-12-28 02:37:25 +00006721 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00006722 } else {
6723 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006724 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006725 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006726 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006727 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006728 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006729 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006730 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00006731 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006732 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006733 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006734 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006735 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006736 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006737
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006738 if (!PrevDecl)
6739 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006740
David Majnemer678f50b2015-11-18 19:49:19 +00006741 if (CurContext->isDependentContext()) {
6742 // -fms-extensions permits specialization of nested classes without
6743 // fully specializing the outer class(es).
6744 assert(getLangOpts().MicrosoftExt &&
6745 "Only possible with -fms-extensions!");
6746 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6747 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00006748 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00006749 } else {
6750 CanonType = Context.getTypeDeclType(Specialization);
6751 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006752 }
6753
Douglas Gregor06db9f52009-10-12 20:18:28 +00006754 // C++ [temp.expl.spec]p6:
6755 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006756 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006757 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006758 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006759 // use occurs; no diagnostic is required.
6760 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006761 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006762 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006763 // Is there any previous explicit specialization declaration?
6764 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6765 Okay = true;
6766 break;
6767 }
6768 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006769
Douglas Gregorc854c662010-02-26 06:03:23 +00006770 if (!Okay) {
6771 SourceRange Range(TemplateNameLoc, RAngleLoc);
6772 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6773 << Context.getTypeDeclType(Specialization) << Range;
6774
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006775 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006776 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006777 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006778 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006779 return true;
6780 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006781 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006782
Douglas Gregor2208a292009-09-26 20:57:03 +00006783 // If this is not a friend, note that this is an explicit specialization.
6784 if (TUK != TUK_Friend)
6785 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006786
6787 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006788 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006789 RecordDecl *Def = Specialization->getDefinition();
6790 NamedDecl *Hidden = nullptr;
6791 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6792 SkipBody->ShouldSkip = true;
6793 makeMergedDefinitionVisible(Hidden, KWLoc);
6794 // From here on out, treat this as just a redeclaration.
6795 TUK = TUK_Declaration;
6796 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006797 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00006798 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006799 Diag(Def->getLocation(), diag::note_previous_definition);
6800 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006801 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006802 }
6803 }
6804
John McCall659a3372010-12-18 03:30:47 +00006805 if (Attr)
6806 ProcessDeclAttributeList(S, Specialization, Attr);
6807
Richard Smith034b94a2012-08-17 03:20:55 +00006808 // Add alignment attributes if necessary; these attributes are checked when
6809 // the ASTContext lays out the structure.
6810 if (TUK == TUK_Definition) {
6811 AddAlignmentAttributesForRecord(Specialization);
6812 AddMsStructLayoutForRecord(Specialization);
6813 }
6814
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006815 if (ModulePrivateLoc.isValid())
6816 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6817 << (isPartialSpecialization? 1 : 0)
6818 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00006819
Douglas Gregord56a91e2009-02-26 22:19:44 +00006820 // Build the fully-sugared type for this class template
6821 // specialization as the user wrote in the specialization
6822 // itself. This means that we'll pretty-print the type retrieved
6823 // from the specialization's declaration the way that the user
6824 // actually wrote the specialization, rather than formatting the
6825 // name based on the "canonical" representation used to store the
6826 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006827 TypeSourceInfo *WrittenTy
6828 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6829 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006830 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006831 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006832 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006833 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006834
Douglas Gregor1e249f82009-02-25 22:18:32 +00006835 // C++ [temp.expl.spec]p9:
6836 // A template explicit specialization is in the scope of the
6837 // namespace in which the template was defined.
6838 //
6839 // We actually implement this paragraph where we set the semantic
6840 // context (in the creation of the ClassTemplateSpecializationDecl),
6841 // but we also maintain the lexical context where the actual
6842 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006843 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006844
Douglas Gregor67a65642009-02-17 23:15:12 +00006845 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006846 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006847 Specialization->startDefinition();
6848
Douglas Gregor2208a292009-09-26 20:57:03 +00006849 if (TUK == TUK_Friend) {
6850 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6851 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006852 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006853 /*FIXME:*/KWLoc);
6854 Friend->setAccess(AS_public);
6855 CurContext->addDecl(Friend);
6856 } else {
6857 // Add the specialization into its lexical context, so that it can
6858 // be seen when iterating through the list of declarations in that
6859 // context. However, specializations are not found by name lookup.
6860 CurContext->addDecl(Specialization);
6861 }
John McCall48871652010-08-21 09:40:31 +00006862 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006863}
Douglas Gregor333489b2009-03-27 23:10:48 +00006864
John McCall48871652010-08-21 09:40:31 +00006865Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006866 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006867 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006868 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006869 ActOnDocumentableDecl(NewDecl);
6870 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006871}
6872
John McCall4f7ced62010-02-11 01:33:53 +00006873/// \brief Strips various properties off an implicit instantiation
6874/// that has just been explicitly specialized.
6875static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006876 D->dropAttr<DLLImportAttr>();
6877 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006878
Nico Webere4974382014-12-19 23:52:45 +00006879 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006880 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006881}
6882
Nico Webera8f80b32012-01-09 19:52:25 +00006883/// \brief Compute the diagnostic location for an explicit instantiation
6884// declaration or definition.
6885static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006886 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006887 // Explicit instantiations following a specialization have no effect and
6888 // hence no PointOfInstantiation. In that case, walk decl backwards
6889 // until a valid name loc is found.
6890 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006891 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6892 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006893 PrevDiagLoc = Prev->getLocation();
6894 }
6895 assert(PrevDiagLoc.isValid() &&
6896 "Explicit instantiation without point of instantiation?");
6897 return PrevDiagLoc;
6898}
6899
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006900/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006901/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006902/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006903/// new specialization/instantiation will have any effect.
6904///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006905/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006906/// instantiation.
6907///
6908/// \param NewTSK the kind of the new explicit specialization or instantiation.
6909///
6910/// \param PrevDecl the previous declaration of the entity.
6911///
6912/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6913///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006914/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006915/// declaration was instantiated (either implicitly or explicitly).
6916///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006917/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006918/// specialization or instantiation has no effect and should be ignored.
6919///
6920/// \returns true if there was an error that should prevent the introduction of
6921/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006922bool
6923Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6924 TemplateSpecializationKind NewTSK,
6925 NamedDecl *PrevDecl,
6926 TemplateSpecializationKind PrevTSK,
6927 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006928 bool &HasNoEffect) {
6929 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006930
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006931 switch (NewTSK) {
6932 case TSK_Undeclared:
6933 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006934 assert(
6935 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6936 "previous declaration must be implicit!");
6937 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006938
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006939 case TSK_ExplicitSpecialization:
6940 switch (PrevTSK) {
6941 case TSK_Undeclared:
6942 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006943 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006944 // explicitly specialized or has merely been mentioned without any
6945 // instantiation.
6946 return false;
6947
6948 case TSK_ImplicitInstantiation:
6949 if (PrevPointOfInstantiation.isInvalid()) {
6950 // The declaration itself has not actually been instantiated, so it is
6951 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006952 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006953 return false;
6954 }
6955 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006956
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006957 case TSK_ExplicitInstantiationDeclaration:
6958 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006959 assert((PrevTSK == TSK_ImplicitInstantiation ||
6960 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006961 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006962
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006963 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006964 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006965 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006966 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006967 // implicit instantiation to take place, in every translation unit in
6968 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006969 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006970 // Is there any previous explicit specialization declaration?
6971 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6972 return false;
6973 }
6974
Douglas Gregor1d957a32009-10-27 18:42:08 +00006975 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006976 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006977 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006978 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006979
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006980 return true;
6981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006982
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006983 case TSK_ExplicitInstantiationDeclaration:
6984 switch (PrevTSK) {
6985 case TSK_ExplicitInstantiationDeclaration:
6986 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006987 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006988 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006989
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006990 case TSK_Undeclared:
6991 case TSK_ImplicitInstantiation:
6992 // We're explicitly instantiating something that may have already been
6993 // implicitly instantiated; that's fine.
6994 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006995
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006996 case TSK_ExplicitSpecialization:
6997 // C++0x [temp.explicit]p4:
6998 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006999 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007000 // specialization for that template, the explicit instantiation has no
7001 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007002 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007003 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007004
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007005 case TSK_ExplicitInstantiationDefinition:
7006 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007007 // If an entity is the subject of both an explicit instantiation
7008 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007009 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007010 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007011 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007012
7013 // Explicit instantiations following a specialization have no effect and
7014 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7015 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007016 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7017 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007018 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007019 return false;
7020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007021
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007022 case TSK_ExplicitInstantiationDefinition:
7023 switch (PrevTSK) {
7024 case TSK_Undeclared:
7025 case TSK_ImplicitInstantiation:
7026 // We're explicitly instantiating something that may have already been
7027 // implicitly instantiated; that's fine.
7028 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007029
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007030 case TSK_ExplicitSpecialization:
7031 // C++ DR 259, C++0x [temp.explicit]p4:
7032 // For a given set of template parameters, if an explicit
7033 // instantiation of a template appears after a declaration of
7034 // an explicit specialization for that template, the explicit
7035 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00007036 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007037 << PrevDecl;
7038 Diag(PrevDecl->getLocation(),
7039 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007040 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007041 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007042
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007043 case TSK_ExplicitInstantiationDeclaration:
7044 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007045 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00007046
7047 // C++0x [temp.explicit]p4:
7048 // For a given set of template parameters, if an explicit instantiation
7049 // of a template appears after a declaration of an explicit
7050 // specialization for that template, the explicit instantiation has no
7051 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007052 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00007053 // Is there any previous explicit specialization declaration?
7054 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7055 HasNoEffect = true;
7056 break;
7057 }
7058 }
7059
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007060 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007061
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007062 case TSK_ExplicitInstantiationDefinition:
7063 // C++0x [temp.spec]p5:
7064 // For a given template and a given set of template-arguments,
7065 // - an explicit instantiation definition shall appear at most once
7066 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007067
7068 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7069 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00007070 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007071 : diag::err_explicit_instantiation_duplicate)
7072 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00007073 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00007074 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007075 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007076 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007077 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007079
David Blaikie83d382b2011-09-23 05:06:16 +00007080 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007081}
7082
John McCallb9c78482010-04-08 09:05:18 +00007083/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00007084/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00007085///
James Dennettf14a6e52012-06-15 22:23:43 +00007086/// The only possible way to get a dependent function template specialization
7087/// is with a friend declaration, like so:
7088///
7089/// \code
7090/// template \<class T> void foo(T);
7091/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00007092/// friend void foo<>(T);
7093/// };
James Dennettf14a6e52012-06-15 22:23:43 +00007094/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00007095///
7096/// There really isn't any useful analysis we can do here, so we
7097/// just store the information.
7098bool
7099Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7100 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7101 LookupResult &Previous) {
7102 // Remove anything from Previous that isn't a function template in
7103 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00007104 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00007105 LookupResult::Filter F = Previous.makeFilter();
7106 while (F.hasNext()) {
7107 NamedDecl *D = F.next()->getUnderlyingDecl();
7108 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00007109 !FDLookupContext->InEnclosingNamespaceSetOf(
7110 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00007111 F.erase();
7112 }
7113 F.done();
7114
7115 // Should this be diagnosed here?
7116 if (Previous.empty()) return true;
7117
7118 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7119 ExplicitTemplateArgs);
7120 return false;
7121}
7122
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007123/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007124/// specialization.
7125///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007126/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007127/// explicit function template specialization. On successful completion,
7128/// the function declaration \p FD will become a function template
7129/// specialization.
7130///
7131/// \param FD the function declaration, which will be updated to become a
7132/// function template specialization.
7133///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007134/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7135/// if any. Note that this may be valid info even when 0 arguments are
7136/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7137/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007138///
Francois Pichet3a44e432011-07-08 06:21:47 +00007139/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007140/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007141bool Sema::CheckFunctionTemplateSpecialization(
7142 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7143 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007144 // The set of function template specializations that could match this
7145 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00007146 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007147 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7148 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007149
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007150 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7151 ConvertedTemplateArgs;
7152
Sebastian Redl50c68252010-08-31 00:36:30 +00007153 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00007154 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7155 I != E; ++I) {
7156 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7157 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007158 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007159 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007160 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7161 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007162 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007163
Richard Smith574f4f62013-01-14 05:37:29 +00007164 // When matching a constexpr member function template specialization
7165 // against the primary template, we don't yet know whether the
7166 // specialization has an implicit 'const' (because we don't know whether
7167 // it will be a static member function until we know which template it
7168 // specializes), so adjust it now assuming it specializes this template.
7169 QualType FT = FD->getType();
7170 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007171 CXXMethodDecl *OldMD =
7172 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00007173 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007174 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00007175 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7176 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007177 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007178 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00007179 }
7180 }
7181
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007182 TemplateArgumentListInfo Args;
7183 if (ExplicitTemplateArgs)
7184 Args = *ExplicitTemplateArgs;
7185
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007186 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007187 // A trailing template-argument can be left unspecified in the
7188 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007189 // provided it can be deduced from the function argument type.
7190 // Perform template argument deduction to determine whether we may be
7191 // specializing this template.
7192 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00007193 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007194 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00007195 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7196 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00007197 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7198 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007199 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007200 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00007201 FailedCandidates.addCandidate().set(
7202 I.getPair(), FunTmpl->getTemplatedDecl(),
7203 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007204 (void)TDK;
7205 continue;
7206 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007207
Artem Belevich64135c32016-12-08 19:38:13 +00007208 // Target attributes are part of the cuda function signature, so
7209 // the deduced template's cuda target must match that of the
7210 // specialization. Given that C++ template deduction does not
7211 // take target attributes into account, we reject candidates
7212 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007213 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00007214 IdentifyCUDATarget(Specialization,
7215 /* IgnoreImplicitHDAttributes = */ true) !=
7216 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007217 FailedCandidates.addCandidate().set(
7218 I.getPair(), FunTmpl->getTemplatedDecl(),
7219 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7220 continue;
7221 }
7222
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007223 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007224 if (ExplicitTemplateArgs)
7225 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00007226 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007227 }
7228 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007229
Douglas Gregor5de279c2009-09-26 03:41:46 +00007230 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007231 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007232 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007233 FD->getLocation(),
7234 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7235 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00007236 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007237 PDiag(diag::note_function_template_spec_matched));
7238
John McCall58cc69d2010-01-27 01:50:18 +00007239 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007240 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007241
7242 // Ignore access information; it doesn't figure into redeclaration checking.
7243 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007244
Nathan Wilson83839122016-04-09 02:55:27 +00007245 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7246 // an explicit specialization (14.8.3) [...] of a concept definition.
7247 if (Specialization->getPrimaryTemplate()->isConcept()) {
7248 Diag(FD->getLocation(), diag::err_concept_specialized)
7249 << 0 /*function*/ << 1 /*explicitly specialized*/;
7250 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7251 return true;
7252 }
7253
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007254 FunctionTemplateSpecializationInfo *SpecInfo
7255 = Specialization->getTemplateSpecializationInfo();
7256 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007257
7258 // Note: do not overwrite location info if previous template
7259 // specialization kind was explicit.
7260 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00007261 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00007262 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00007263 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7264 // function can differ from the template declaration with respect to
7265 // the constexpr specifier.
7266 Specialization->setConstexpr(FD->isConstexpr());
7267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007268
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007269 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00007270 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00007271
7272 // If this is a friend declaration, then we're not really declaring
7273 // an explicit specialization.
7274 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007275
Douglas Gregor54888652009-10-07 00:13:32 +00007276 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00007277 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007278 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00007279 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007280 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007281 false))
Douglas Gregor54888652009-10-07 00:13:32 +00007282 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007283
7284 // C++ [temp.expl.spec]p6:
7285 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007286 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007287 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007288 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007289 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007290 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007291 if (!isFriend &&
7292 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007293 TSK_ExplicitSpecialization,
7294 Specialization,
7295 SpecInfo->getTemplateSpecializationKind(),
7296 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007297 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007298 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00007299
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007300 // Mark the prior declaration as an explicit specialization, so that later
7301 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007302 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007303 // Since explicit specializations do not inherit '=delete' from their
7304 // primary function template - check if the 'specialization' that was
7305 // implicitly generated (during template argument deduction for partial
7306 // ordering) from the most specialized of all the function templates that
7307 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7308 // first check that it was implicitly generated during template argument
7309 // deduction by making sure it wasn't referenced, and then reset the deleted
7310 // flag to not-deleted, so that we can inherit that information from 'FD'.
7311 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7312 !Specialization->getCanonicalDecl()->isReferenced()) {
7313 assert(
7314 Specialization->getCanonicalDecl() == Specialization &&
7315 "This must be the only existing declaration of this specialization");
7316 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007317 }
John McCall816d75b2010-03-24 07:46:06 +00007318 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007319 MarkUnusedFileScopedDecl(Specialization);
7320 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007321
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007322 // Turn the given function declaration into a function template
7323 // specialization, with the template arguments from the previous
7324 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007325 // Take copies of (semantic and syntactic) template argument lists.
7326 const TemplateArgumentList* TemplArgs = new (Context)
7327 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007328 FD->setFunctionTemplateSpecialization(
7329 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7330 SpecInfo->getTemplateSpecializationKind(),
7331 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007332
Artem Belevich64135c32016-12-08 19:38:13 +00007333 // A function template specialization inherits the target attributes
7334 // of its template. (We require the attributes explicitly in the
7335 // code to match, but a template may have implicit attributes by
7336 // virtue e.g. of being constexpr, and it passes these implicit
7337 // attributes on to its specializations.)
7338 if (LangOpts.CUDA)
7339 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
7340
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007341 // The "previous declaration" for this function template specialization is
7342 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007343 Previous.clear();
7344 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007345 return false;
7346}
7347
Douglas Gregor86d142a2009-10-08 07:24:58 +00007348/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007349/// specialization.
7350///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007351/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007352/// explicit member function specialization. On successful completion,
7353/// the function declaration \p FD will become a member function
7354/// specialization.
7355///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007356/// \param Member the member declaration, which will be updated to become a
7357/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007358///
John McCall1f82f242009-11-18 22:49:29 +00007359/// \param Previous the set of declarations, one of which may be specialized
7360/// by this function specialization; the set will be modified to contain the
7361/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007362bool
John McCall1f82f242009-11-18 22:49:29 +00007363Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007364 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007365
Douglas Gregor86d142a2009-10-08 07:24:58 +00007366 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007367 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007368 NamedDecl *Instantiation = nullptr;
7369 NamedDecl *InstantiatedFrom = nullptr;
7370 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007371
John McCall1f82f242009-11-18 22:49:29 +00007372 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007373 // Nowhere to look anyway.
7374 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007375 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7376 I != E; ++I) {
7377 NamedDecl *D = (*I)->getUnderlyingDecl();
7378 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007379 QualType Adjusted = Function->getType();
7380 if (!hasExplicitCallingConv(Adjusted))
7381 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7382 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007383 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007384 Instantiation = Method;
7385 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007386 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007387 break;
7388 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007389 }
7390 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007391 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007392 VarDecl *PrevVar;
7393 if (Previous.isSingleResult() &&
7394 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007395 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007396 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007397 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007398 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007399 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007400 }
7401 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007402 CXXRecordDecl *PrevRecord;
7403 if (Previous.isSingleResult() &&
7404 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007405 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007406 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007407 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007408 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007409 }
Richard Smith7d137e32012-03-23 03:33:32 +00007410 } else if (isa<EnumDecl>(Member)) {
7411 EnumDecl *PrevEnum;
7412 if (Previous.isSingleResult() &&
7413 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007414 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007415 Instantiation = PrevEnum;
7416 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7417 MSInfo = PrevEnum->getMemberSpecializationInfo();
7418 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007420
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007421 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007422 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007423 // specializations are always out-of-line, the caller will complain about
7424 // this mismatch later.
7425 return false;
7426 }
John McCalle820e5e2010-04-13 20:37:33 +00007427
7428 // If this is a friend, just bail out here before we start turning
7429 // things into explicit specializations.
7430 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7431 // Preserve instantiation information.
7432 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7433 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7434 cast<CXXMethodDecl>(InstantiatedFrom),
7435 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7436 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7437 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7438 cast<CXXRecordDecl>(InstantiatedFrom),
7439 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7440 }
7441
7442 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007443 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007444 return false;
7445 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007446
Douglas Gregor86d142a2009-10-08 07:24:58 +00007447 // Make sure that this is a specialization of a member.
7448 if (!InstantiatedFrom) {
7449 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7450 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007451 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7452 return true;
7453 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007454
Douglas Gregor06db9f52009-10-12 20:18:28 +00007455 // C++ [temp.expl.spec]p6:
7456 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007457 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007458 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007459 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007460 // use occurs; no diagnostic is required.
7461 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007462
Abramo Bagnara8075c852010-06-12 07:44:57 +00007463 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007464 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7465 TSK_ExplicitSpecialization,
7466 Instantiation,
7467 MSInfo->getTemplateSpecializationKind(),
7468 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007469 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007470 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007471
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007472 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007473 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007474 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007475 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007476 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007477 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007478
Douglas Gregor86d142a2009-10-08 07:24:58 +00007479 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007480 // the original declaration to note that it is an explicit specialization
7481 // (if it was previously an implicit instantiation). This latter step
7482 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007483 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007484 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7485 if (InstantiationFunction->getTemplateSpecializationKind() ==
7486 TSK_ImplicitInstantiation) {
7487 InstantiationFunction->setTemplateSpecializationKind(
7488 TSK_ExplicitSpecialization);
7489 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007490 // Explicit specializations of member functions of class templates do not
7491 // inherit '=delete' from the member function they are specializing.
7492 if (InstantiationFunction->isDeleted()) {
7493 assert(InstantiationFunction->getCanonicalDecl() ==
7494 InstantiationFunction);
Richard Smith5f274382016-09-28 23:55:27 +00007495 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007496 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007498
Douglas Gregor86d142a2009-10-08 07:24:58 +00007499 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7500 cast<CXXMethodDecl>(InstantiatedFrom),
7501 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007502 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007503 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007504 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7505 if (InstantiationVar->getTemplateSpecializationKind() ==
7506 TSK_ImplicitInstantiation) {
7507 InstantiationVar->setTemplateSpecializationKind(
7508 TSK_ExplicitSpecialization);
7509 InstantiationVar->setLocation(Member->getLocation());
7510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007511
Larisse Voufo39a1e502013-08-06 01:03:05 +00007512 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7513 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007514 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007515 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007516 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7517 if (InstantiationClass->getTemplateSpecializationKind() ==
7518 TSK_ImplicitInstantiation) {
7519 InstantiationClass->setTemplateSpecializationKind(
7520 TSK_ExplicitSpecialization);
7521 InstantiationClass->setLocation(Member->getLocation());
7522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007523
Douglas Gregor86d142a2009-10-08 07:24:58 +00007524 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007525 cast<CXXRecordDecl>(InstantiatedFrom),
7526 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007527 } else {
7528 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7529 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7530 if (InstantiationEnum->getTemplateSpecializationKind() ==
7531 TSK_ImplicitInstantiation) {
7532 InstantiationEnum->setTemplateSpecializationKind(
7533 TSK_ExplicitSpecialization);
7534 InstantiationEnum->setLocation(Member->getLocation());
7535 }
7536
7537 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7538 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007539 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007540
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007541 // Save the caller the trouble of having to figure out which declaration
7542 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007543 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007544 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007545 return false;
7546}
7547
Douglas Gregore47f5a72009-10-14 23:41:34 +00007548/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007549///
7550/// \returns true if a serious error occurs, false otherwise.
7551static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007552 SourceLocation InstLoc,
7553 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007554 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7555 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007556
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007557 if (CurContext->isRecord()) {
7558 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7559 << D;
7560 return true;
7561 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007562
Richard Smith050d2612011-10-18 02:28:33 +00007563 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007564 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007565 // template. If the name declared in the explicit instantiation is an
7566 // unqualified name, the explicit instantiation shall appear in the
7567 // namespace where its template is declared or, if that namespace is inline
7568 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007569 //
7570 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007571 if (WasQualifiedName) {
7572 if (CurContext->Encloses(OrigContext))
7573 return false;
7574 } else {
7575 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7576 return false;
7577 }
7578
7579 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7580 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007581 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007582 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007583 diag::err_explicit_instantiation_out_of_scope :
7584 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007585 << D << NS;
7586 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007587 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007588 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007589 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7590 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7591 << D << NS;
7592 } else
7593 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007594 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007595 diag::err_explicit_instantiation_must_be_global :
7596 diag::warn_explicit_instantiation_must_be_global_0x)
7597 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007598 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007599 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007600}
7601
7602/// \brief Determine whether the given scope specifier has a template-id in it.
7603static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7604 if (!SS.isSet())
7605 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007606
Richard Smith050d2612011-10-18 02:28:33 +00007607 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007608 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007609 // or a static data member of a class template specialization, the name of
7610 // the class template specialization in the qualified-id for the member
7611 // name shall be a simple-template-id.
7612 //
7613 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007614 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7615 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007616 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007617 if (isa<TemplateSpecializationType>(T))
7618 return true;
7619
7620 return false;
7621}
7622
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007623/// Make a dllexport or dllimport attr on a class template specialization take
7624/// effect.
7625static void dllExportImportClassTemplateSpecialization(
7626 Sema &S, ClassTemplateSpecializationDecl *Def) {
7627 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
7628 assert(A && "dllExportImportClassTemplateSpecialization called "
7629 "on Def without dllexport or dllimport");
7630
7631 // We reject explicit instantiations in class scope, so there should
7632 // never be any delayed exported classes to worry about.
7633 assert(S.DelayedDllExportClasses.empty() &&
7634 "delayed exports present at explicit instantiation");
7635 S.checkClassLevelDLLAttribute(Def);
7636
7637 // Propagate attribute to base class templates.
7638 for (auto &B : Def->bases()) {
7639 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7640 B.getType()->getAsCXXRecordDecl()))
7641 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7642 }
7643
7644 S.referenceDLLExportedClassMethods();
7645}
7646
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007647// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007648DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007649Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007650 SourceLocation ExternLoc,
7651 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007652 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007653 SourceLocation KWLoc,
7654 const CXXScopeSpec &SS,
7655 TemplateTy TemplateD,
7656 SourceLocation TemplateNameLoc,
7657 SourceLocation LAngleLoc,
7658 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007659 SourceLocation RAngleLoc,
7660 AttributeList *Attr) {
7661 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007662 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007663 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007664 // Check that the specialization uses the same tag kind as the
7665 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007666 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7667 assert(Kind != TTK_Enum &&
7668 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007669
Richard Trieu265c3442016-04-05 21:13:54 +00007670 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7671
7672 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00007673 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
7674 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00007675 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00007676 return true;
7677 }
7678
Douglas Gregord9034f02009-05-14 16:41:31 +00007679 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007680 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007681 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007682 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007683 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007684 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007685 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007686 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007687 diag::note_previous_use);
7688 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7689 }
7690
Douglas Gregore47f5a72009-10-14 23:41:34 +00007691 // C++0x [temp.explicit]p2:
7692 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007693 // definition and an explicit instantiation declaration. An explicit
7694 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007695 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7696 ? TSK_ExplicitInstantiationDefinition
7697 : TSK_ExplicitInstantiationDeclaration;
7698
7699 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7700 // Check for dllexport class template instantiation declarations.
7701 for (AttributeList *A = Attr; A; A = A->getNext()) {
7702 if (A->getKind() == AttributeList::AT_DLLExport) {
7703 Diag(ExternLoc,
7704 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7705 Diag(A->getLoc(), diag::note_attribute);
7706 break;
7707 }
7708 }
7709
7710 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7711 Diag(ExternLoc,
7712 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7713 Diag(A->getLocation(), diag::note_attribute);
7714 }
7715 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007716
Hans Wennborga86a83b2016-05-26 19:42:56 +00007717 // In MSVC mode, dllimported explicit instantiation definitions are treated as
7718 // instantiation declarations for most purposes.
7719 bool DLLImportExplicitInstantiationDef = false;
7720 if (TSK == TSK_ExplicitInstantiationDefinition &&
7721 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7722 // Check for dllimport class template instantiation definitions.
7723 bool DLLImport =
7724 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7725 for (AttributeList *A = Attr; A; A = A->getNext()) {
7726 if (A->getKind() == AttributeList::AT_DLLImport)
7727 DLLImport = true;
7728 if (A->getKind() == AttributeList::AT_DLLExport) {
7729 // dllexport trumps dllimport here.
7730 DLLImport = false;
7731 break;
7732 }
7733 }
7734 if (DLLImport) {
7735 TSK = TSK_ExplicitInstantiationDeclaration;
7736 DLLImportExplicitInstantiationDef = true;
7737 }
7738 }
7739
Douglas Gregora1f49972009-05-13 00:25:59 +00007740 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007741 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007742 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007743
7744 // Check that the template argument list is well-formed for this
7745 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007746 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007747 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7748 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007749 return true;
7750
Douglas Gregora1f49972009-05-13 00:25:59 +00007751 // Find the class template specialization declaration that
7752 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007753 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007754 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007755 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007756
Abramo Bagnara8075c852010-06-12 07:44:57 +00007757 TemplateSpecializationKind PrevDecl_TSK
7758 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7759
Douglas Gregor54888652009-10-07 00:13:32 +00007760 // C++0x [temp.explicit]p2:
7761 // [...] An explicit instantiation shall appear in an enclosing
7762 // namespace of its template. [...]
7763 //
7764 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007765 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7766 SS.isSet()))
7767 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007768
Craig Topperc3ec1492014-05-26 06:22:03 +00007769 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007770
Abramo Bagnara8075c852010-06-12 07:44:57 +00007771 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007772 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007773 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007774 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007775 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007776 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007777 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007778
Abramo Bagnara8075c852010-06-12 07:44:57 +00007779 // Even though HasNoEffect == true means that this explicit instantiation
7780 // has no effect on semantics, we go on to put its syntax in the AST.
7781
7782 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7783 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007784 // Since the only prior class template specialization with these
7785 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007786 // declaration node as our own, updating the source location
7787 // for the template name to reflect our new declaration.
7788 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007789 Specialization = PrevDecl;
7790 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007791 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007792 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00007793
7794 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7795 DLLImportExplicitInstantiationDef) {
7796 // The new specialization might add a dllimport attribute.
7797 HasNoEffect = false;
7798 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007799 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007800
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007801 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007802 // Create a new class template specialization declaration node for
7803 // this explicit specialization.
7804 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007805 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007806 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007807 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007808 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007809 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007810 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007811 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007812
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007813 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007814 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007815 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007816 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007817 }
7818
7819 // Build the fully-sugared type for this explicit instantiation as
7820 // the user wrote in the explicit instantiation itself. This means
7821 // that we'll pretty-print the type retrieved from the
7822 // specialization's declaration the way that the user actually wrote
7823 // the explicit instantiation, rather than formatting the name based
7824 // on the "canonical" representation used to store the template
7825 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007826 TypeSourceInfo *WrittenTy
7827 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7828 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007829 Context.getTypeDeclType(Specialization));
7830 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007831
Abramo Bagnara8075c852010-06-12 07:44:57 +00007832 // Set source locations for keywords.
7833 Specialization->setExternLoc(ExternLoc);
7834 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00007835 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007836
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00007837 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Rafael Espindola0b062072012-01-03 06:04:21 +00007838 if (Attr)
7839 ProcessDeclAttributeList(S, Specialization, Attr);
7840
Abramo Bagnara8075c852010-06-12 07:44:57 +00007841 // Add the explicit instantiation into its lexical context. However,
7842 // since explicit instantiations are never found by name lookup, we
7843 // just put it into the declaration context directly.
7844 Specialization->setLexicalDeclContext(CurContext);
7845 CurContext->addDecl(Specialization);
7846
7847 // Syntax is now OK, so return if it has no other effect on semantics.
7848 if (HasNoEffect) {
7849 // Set the template specialization kind.
7850 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007851 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007852 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007853
7854 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007855 // A definition of a class template or class member template
7856 // shall be in scope at the point of the explicit instantiation of
7857 // the class template or class member template.
7858 //
7859 // This check comes when we actually try to perform the
7860 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007861 ClassTemplateSpecializationDecl *Def
7862 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007863 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007864 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007865 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007866 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007867 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007868 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7869 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007870
Douglas Gregor1d957a32009-10-27 18:42:08 +00007871 // Instantiate the members of this class template specialization.
7872 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007873 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007874 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007875 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007876 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7877 // TSK_ExplicitInstantiationDefinition
7878 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00007879 (TSK == TSK_ExplicitInstantiationDefinition ||
7880 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007881 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007882 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007883
Hans Wennborgc0875502015-06-09 00:39:05 +00007884 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00007885 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
7886 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00007887 // In the MS ABI, an explicit instantiation definition can add a dll
7888 // attribute to a template with a previous instantiation declaration.
7889 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007890 auto *A = cast<InheritableAttr>(
7891 getDLLAttr(Specialization)->clone(getASTContext()));
7892 A->setInherited(true);
7893 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007894 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00007895 }
7896 }
7897
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007898 // Fix a TSK_ImplicitInstantiation followed by a
7899 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00007900 bool NewlyDLLExported =
7901 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
7902 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007903 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
7904 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
7905 // In the MS ABI, an explicit instantiation definition can add a dll
7906 // attribute to a template with a previous implicit instantiation.
7907 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
7908 // avoid potentially strange codegen behavior. For example, if we extend
7909 // this conditional to dllimport, and we have a source file calling a
7910 // method on an implicitly instantiated template class instance and then
7911 // declaring a dllimport explicit instantiation definition for the same
7912 // template class, the codegen for the method call will not respect the
7913 // dllimport, while it will with cl. The Def will already have the DLL
7914 // attribute, since the Def and Specialization will be the same in the
7915 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
7916 // attribute to the Specialization; we just need to make it take effect.
7917 assert(Def == Specialization &&
7918 "Def and Specialization should match for implicit instantiation");
7919 dllExportImportClassTemplateSpecialization(*this, Def);
7920 }
7921
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007922 // Set the template specialization kind. Make sure it is set before
7923 // instantiating the members which will trigger ASTConsumer callbacks.
7924 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007925 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007926 } else {
7927
7928 // Set the template specialization kind.
7929 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007930 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007931
John McCall48871652010-08-21 09:40:31 +00007932 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007933}
7934
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007935// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007936DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007937Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007938 SourceLocation ExternLoc,
7939 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007940 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007941 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007942 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007943 IdentifierInfo *Name,
7944 SourceLocation NameLoc,
7945 AttributeList *Attr) {
7946
Douglas Gregord6ab8742009-05-28 23:31:59 +00007947 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007948 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007949 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007950 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007951 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007952 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007953 SourceLocation(), false, TypeResult(),
7954 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007955 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7956
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007957 if (!TagD)
7958 return true;
7959
John McCall48871652010-08-21 09:40:31 +00007960 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007961 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007962
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007963 if (Tag->isInvalidDecl())
7964 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007965
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007966 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7967 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7968 if (!Pattern) {
7969 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7970 << Context.getTypeDeclType(Record);
7971 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7972 return true;
7973 }
7974
Douglas Gregore47f5a72009-10-14 23:41:34 +00007975 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007976 // If the explicit instantiation is for a class or member class, the
7977 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007978 // simple-template-id.
7979 //
7980 // C++98 has the same restriction, just worded differently.
7981 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007982 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007983 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007984
Douglas Gregore47f5a72009-10-14 23:41:34 +00007985 // C++0x [temp.explicit]p2:
7986 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007987 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007988 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007989 TemplateSpecializationKind TSK
7990 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7991 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007992
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007993 // C++0x [temp.explicit]p2:
7994 // [...] An explicit instantiation shall appear in an enclosing
7995 // namespace of its template. [...]
7996 //
7997 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007998 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007999
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008000 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008001 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00008002 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008003 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00008004 PrevDecl = Record;
8005 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008006 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008007 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008008 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008009 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008010 PrevDecl,
8011 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008012 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008013 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008014 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00008015 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008016 return TagD;
8017 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008018
Douglas Gregor12e49d32009-10-15 22:53:21 +00008019 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008020 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008021 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00008022 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008023 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00008024 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008025 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008026 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00008027 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00008028 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8029 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00008030 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8031 << Pattern;
8032 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008033 } else {
8034 if (InstantiateClass(NameLoc, Record, Def,
8035 getTemplateInstantiationArgs(Record),
8036 TSK))
8037 return true;
8038
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008039 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00008040 if (!RecordDef)
8041 return true;
8042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008043 }
8044
Douglas Gregor1d957a32009-10-27 18:42:08 +00008045 // Instantiate all of the members of the class.
8046 InstantiateClassMembers(NameLoc, RecordDef,
8047 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008048
Douglas Gregor88d292c2010-05-13 16:44:06 +00008049 if (TSK == TSK_ExplicitInstantiationDefinition)
8050 MarkVTableUsed(NameLoc, RecordDef, true);
8051
Mike Stump87c57ac2009-05-16 07:39:55 +00008052 // FIXME: We don't have any representation for explicit instantiations of
8053 // member classes. Such a representation is not needed for compilation, but it
8054 // should be available for clients that want to see all of the declarations in
8055 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008056 return TagD;
8057}
8058
John McCallfaf5fb42010-08-26 23:41:50 +00008059DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8060 SourceLocation ExternLoc,
8061 SourceLocation TemplateLoc,
8062 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008063 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008064 // TODO: check if/when DNInfo should replace Name.
8065 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8066 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00008067 if (!Name) {
8068 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008069 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008070 diag::err_explicit_instantiation_requires_name)
8071 << D.getDeclSpec().getSourceRange()
8072 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008073
Douglas Gregor450f00842009-09-25 18:43:00 +00008074 return true;
8075 }
8076
8077 // The scope passed in may not be a decl scope. Zip up the scope tree until
8078 // we find one that is.
8079 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8080 (S->getFlags() & Scope::TemplateParamScope) != 0)
8081 S = S->getParent();
8082
8083 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00008084 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8085 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00008086 if (R.isNull())
8087 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008088
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008089 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00008090 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008091 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00008092 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008093 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8094 << Name;
8095 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008096 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008097 != DeclSpec::SCS_unspecified) {
8098 // Complain about then remove the storage class specifier.
8099 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8100 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008101
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008102 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00008103 }
8104
Douglas Gregor3c74d412009-10-14 20:14:33 +00008105 // C++0x [temp.explicit]p1:
8106 // [...] An explicit instantiation of a function template shall not use the
8107 // inline or constexpr specifiers.
8108 // Presumably, this also applies to member functions of class templates as
8109 // well.
Richard Smith83c19292011-10-18 03:44:03 +00008110 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008111 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008112 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00008113 diag::err_explicit_instantiation_inline :
8114 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00008115 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00008116 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00008117 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8118 // not already specified.
8119 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8120 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008121
Nathan Wilsonde498452016-02-08 05:34:00 +00008122 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8123 // applied only to the definition of a function template or variable template,
8124 // declared in namespace scope.
8125 if (D.getDeclSpec().isConceptSpecified()) {
8126 Diag(D.getDeclSpec().getConceptSpecLoc(),
8127 diag::err_concept_specified_specialization) << 0;
8128 return true;
8129 }
8130
Douglas Gregore47f5a72009-10-14 23:41:34 +00008131 // C++0x [temp.explicit]p2:
8132 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008133 // definition and an explicit instantiation declaration. An explicit
8134 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00008135 TemplateSpecializationKind TSK
8136 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8137 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008138
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008139 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00008140 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00008141
8142 if (!R->isFunctionType()) {
8143 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008144 // A [...] static data member of a class template can be explicitly
8145 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008146 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008147 // C++1y [temp.explicit]p1:
8148 // A [...] variable [...] template specialization can be explicitly
8149 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00008150 if (Previous.isAmbiguous())
8151 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008152
John McCall67c00872009-12-02 08:25:40 +00008153 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00008154 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008155
Larisse Voufo39a1e502013-08-06 01:03:05 +00008156 if (!PrevTemplate) {
8157 if (!Prev || !Prev->isStaticDataMember()) {
8158 // We expect to see a data data member here.
8159 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8160 << Name;
8161 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8162 P != PEnd; ++P)
8163 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8164 return true;
8165 }
8166
8167 if (!Prev->getInstantiatedFromStaticDataMember()) {
8168 // FIXME: Check for explicit specialization?
8169 Diag(D.getIdentifierLoc(),
8170 diag::err_explicit_instantiation_data_member_not_instantiated)
8171 << Prev;
8172 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8173 // FIXME: Can we provide a note showing where this was declared?
8174 return true;
8175 }
8176 } else {
8177 // Explicitly instantiate a variable template.
8178
8179 // C++1y [dcl.spec.auto]p6:
8180 // ... A program that uses auto or decltype(auto) in a context not
8181 // explicitly allowed in this section is ill-formed.
8182 //
8183 // This includes auto-typed variable template instantiations.
8184 if (R->isUndeducedType()) {
8185 Diag(T->getTypeLoc().getLocStart(),
8186 diag::err_auto_not_allowed_var_inst);
8187 return true;
8188 }
8189
Richard Smithef985ac2013-09-18 02:10:12 +00008190 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8191 // C++1y [temp.explicit]p3:
8192 // If the explicit instantiation is for a variable, the unqualified-id
8193 // in the declaration shall be a template-id.
8194 Diag(D.getIdentifierLoc(),
8195 diag::err_explicit_instantiation_without_template_id)
8196 << PrevTemplate;
8197 Diag(PrevTemplate->getLocation(),
8198 diag::note_explicit_instantiation_here);
8199 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00008200 }
8201
Nathan Wilson83839122016-04-09 02:55:27 +00008202 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8203 // explicit instantiation (14.8.2) [...] of a concept definition.
8204 if (PrevTemplate->isConcept()) {
8205 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8206 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8207 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8208 return true;
8209 }
8210
Richard Smithef985ac2013-09-18 02:10:12 +00008211 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00008212 TemplateArgumentListInfo TemplateArgs =
8213 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00008214
Larisse Voufo39a1e502013-08-06 01:03:05 +00008215 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8216 D.getIdentifierLoc(), TemplateArgs);
8217 if (Res.isInvalid())
8218 return true;
8219
8220 // Ignore access control bits, we don't need them for redeclaration
8221 // checking.
8222 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00008223 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008224
Douglas Gregore47f5a72009-10-14 23:41:34 +00008225 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008226 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008227 // or a static data member of a class template specialization, the name of
8228 // the class template specialization in the qualified-id for the member
8229 // name shall be a simple-template-id.
8230 //
8231 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008232 //
Richard Smith5977d872013-09-18 21:55:14 +00008233 // This does not apply to variable template specializations, where the
8234 // template-id is in the unqualified-id instead.
8235 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008236 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008237 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008238 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008239
Douglas Gregore47f5a72009-10-14 23:41:34 +00008240 // Check the scope of this explicit instantiation.
8241 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008242
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008243 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00008244 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8245 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008246 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008247 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00008248 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008249 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008250
Larisse Voufo39a1e502013-08-06 01:03:05 +00008251 if (!HasNoEffect) {
8252 // Instantiate static data member or variable template.
8253
8254 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8255 if (PrevTemplate) {
8256 // Merge attributes.
8257 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8258 ProcessDeclAttributeList(S, Prev, Attr);
8259 }
8260 if (TSK == TSK_ExplicitInstantiationDefinition)
8261 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8262 }
8263
8264 // Check the new variable specialization against the parsed input.
8265 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8266 Diag(T->getTypeLoc().getLocStart(),
8267 diag::err_invalid_var_template_spec_type)
8268 << 0 << PrevTemplate << R << Prev->getType();
8269 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8270 << 2 << PrevTemplate->getDeclName();
8271 return true;
8272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008273
Douglas Gregor450f00842009-09-25 18:43:00 +00008274 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00008275 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008276 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008277
8278 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00008279 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00008280 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00008281 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00008282 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00008283 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00008284 HasExplicitTemplateArgs = true;
8285 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008286
Douglas Gregor450f00842009-09-25 18:43:00 +00008287 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008288 // A [...] function [...] can be explicitly instantiated from its template.
8289 // A member function [...] of a class template can be explicitly
8290 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008291 // template.
John McCall58cc69d2010-01-27 01:50:18 +00008292 UnresolvedSet<8> Matches;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008293 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008294 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00008295 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8296 P != PEnd; ++P) {
8297 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00008298 if (!HasExplicitTemplateArgs) {
8299 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00008300 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
8301 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00008302 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00008303 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008304
John McCall58cc69d2010-01-27 01:50:18 +00008305 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008306 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8307 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00008308 }
Douglas Gregor450f00842009-09-25 18:43:00 +00008309 }
8310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008311
Douglas Gregor450f00842009-09-25 18:43:00 +00008312 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8313 if (!FunTmpl)
8314 continue;
8315
Larisse Voufo98b20f12013-07-19 23:00:19 +00008316 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008317 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008318 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008319 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00008320 (HasExplicitTemplateArgs ? &TemplateArgs
8321 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00008322 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008323 // Keep track of almost-matches.
8324 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00008325 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008326 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008327 (void)TDK;
8328 continue;
8329 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008330
Artem Belevich64135c32016-12-08 19:38:13 +00008331 // Target attributes are part of the cuda function signature, so
8332 // the cuda target of the instantiated function must match that of its
8333 // template. Given that C++ template deduction does not take
8334 // target attributes into account, we reject candidates here that
8335 // have a different target.
8336 if (LangOpts.CUDA &&
8337 IdentifyCUDATarget(Specialization,
8338 /* IgnoreImplicitHDAttributes = */ true) !=
8339 IdentifyCUDATarget(Attr)) {
8340 FailedCandidates.addCandidate().set(
8341 P.getPair(), FunTmpl->getTemplatedDecl(),
8342 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8343 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008344 }
8345
John McCall58cc69d2010-01-27 01:50:18 +00008346 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008347 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008348
Douglas Gregor450f00842009-09-25 18:43:00 +00008349 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008350 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008351 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008352 D.getIdentifierLoc(),
8353 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8354 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8355 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008356
John McCall58cc69d2010-01-27 01:50:18 +00008357 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008358 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008359
8360 // Ignore access control bits, we don't need them for redeclaration checking.
8361 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008362
Alexey Bataev73983912014-11-06 10:10:50 +00008363 // C++11 [except.spec]p4
8364 // In an explicit instantiation an exception-specification may be specified,
8365 // but is not required.
8366 // If an exception-specification is specified in an explicit instantiation
8367 // directive, it shall be compatible with the exception-specifications of
8368 // other declarations of that function.
8369 if (auto *FPT = R->getAs<FunctionProtoType>())
8370 if (FPT->hasExceptionSpec()) {
8371 unsigned DiagID =
8372 diag::err_mismatched_exception_spec_explicit_instantiation;
8373 if (getLangOpts().MicrosoftExt)
8374 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8375 bool Result = CheckEquivalentExceptionSpec(
8376 PDiag(DiagID) << Specialization->getType(),
8377 PDiag(diag::note_explicit_instantiation_here),
8378 Specialization->getType()->getAs<FunctionProtoType>(),
8379 Specialization->getLocation(), FPT, D.getLocStart());
8380 // In Microsoft mode, mismatching exception specifications just cause a
8381 // warning.
8382 if (!getLangOpts().MicrosoftExt && Result)
8383 return true;
8384 }
8385
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008386 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008387 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008388 diag::err_explicit_instantiation_member_function_not_instantiated)
8389 << Specialization
8390 << (Specialization->getTemplateSpecializationKind() ==
8391 TSK_ExplicitSpecialization);
8392 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8393 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008394 }
8395
Douglas Gregorec9fd132012-01-14 16:38:05 +00008396 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008397 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8398 PrevDecl = Specialization;
8399
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008400 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008401 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008402 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008403 PrevDecl,
8404 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008405 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008406 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008407 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008408
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008409 // FIXME: We may still want to build some representation of this
8410 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008411 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008412 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008413 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008414
8415 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008416 if (Attr)
8417 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008418
Richard Smitheb36ddf2014-04-24 22:45:46 +00008419 if (Specialization->isDefined()) {
8420 // Let the ASTConsumer know that this function has been explicitly
8421 // instantiated now, and its linkage might have changed.
8422 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8423 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008424 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008425
Douglas Gregore47f5a72009-10-14 23:41:34 +00008426 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008427 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008428 // or a static data member of a class template specialization, the name of
8429 // the class template specialization in the qualified-id for the member
8430 // name shall be a simple-template-id.
8431 //
8432 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008433 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008434 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008435 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008436 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008437 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008438 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008439 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008440
Nathan Wilson83839122016-04-09 02:55:27 +00008441 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8442 // explicit instantiation (14.8.2) [...] of a concept definition.
8443 if (FunTmpl && FunTmpl->isConcept() &&
8444 !D.getDeclSpec().isConceptSpecified()) {
8445 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8446 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8447 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8448 return true;
8449 }
8450
Douglas Gregore47f5a72009-10-14 23:41:34 +00008451 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008452 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008453 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008454 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008455 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008456
Douglas Gregor450f00842009-09-25 18:43:00 +00008457 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008458 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008459}
8460
John McCallfaf5fb42010-08-26 23:41:50 +00008461TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008462Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8463 const CXXScopeSpec &SS, IdentifierInfo *Name,
8464 SourceLocation TagLoc, SourceLocation NameLoc) {
8465 // This has to hold, because SS is expected to be defined.
8466 assert(Name && "Expected a name in a dependent tag");
8467
Aaron Ballman4a979672014-01-03 13:56:08 +00008468 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008469 if (!NNS)
8470 return true;
8471
Abramo Bagnara6150c882010-05-11 21:36:43 +00008472 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008473
Douglas Gregorba41d012010-04-24 16:38:41 +00008474 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8475 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008476 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008477 return true;
8478 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008479
Douglas Gregore7c20652011-03-02 00:47:37 +00008480 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008481 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008482 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008483
Douglas Gregore7c20652011-03-02 00:47:37 +00008484 // Create type-source location information for this type.
8485 TypeLocBuilder TLB;
8486 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008487 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008488 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8489 TL.setNameLoc(NameLoc);
8490 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008491}
8492
John McCallfaf5fb42010-08-26 23:41:50 +00008493TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008494Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8495 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008496 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008497 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008498 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008499
Richard Smith0bf8a4922011-10-18 20:49:44 +00008500 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8501 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008502 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008503 diag::warn_cxx98_compat_typename_outside_of_template :
8504 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008505 << FixItHint::CreateRemoval(TypenameLoc);
8506
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008507 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008508 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8509 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008510 if (T.isNull())
8511 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008512
8513 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8514 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008515 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008516 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008517 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008518 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008519 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008520 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008521 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008522 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008523 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008525
John McCallba7bf592010-08-24 05:47:05 +00008526 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008527}
8528
John McCallfaf5fb42010-08-26 23:41:50 +00008529TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008530Sema::ActOnTypenameType(Scope *S,
8531 SourceLocation TypenameLoc,
8532 const CXXScopeSpec &SS,
8533 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008534 TemplateTy TemplateIn,
8535 SourceLocation TemplateNameLoc,
8536 SourceLocation LAngleLoc,
8537 ASTTemplateArgsPtr TemplateArgsIn,
8538 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008539 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8540 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008541 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008542 diag::warn_cxx98_compat_typename_outside_of_template :
8543 diag::ext_typename_outside_of_template)
8544 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008545
Douglas Gregorb09518c2011-02-27 22:46:49 +00008546 // Translate the parser's template argument list in our AST format.
8547 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8548 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008549
Douglas Gregorb09518c2011-02-27 22:46:49 +00008550 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008551 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8552 // Construct a dependent template specialization type.
8553 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008554 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008555 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8556 DTN->getQualifier(),
8557 DTN->getIdentifier(),
8558 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008559
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008560 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008561 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008562 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008563 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008564 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8565 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008566 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008567 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008568 SpecTL.setLAngleLoc(LAngleLoc);
8569 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008570 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8571 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008572 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008573 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00008574
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008575 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8576 if (T.isNull())
8577 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008578
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008579 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008580 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008581 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008582 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008583 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8584 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008585 SpecTL.setLAngleLoc(LAngleLoc);
8586 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008587 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8588 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008589
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008590 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8591 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008592 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008593 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00008594
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008595 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8596 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008597}
8598
Douglas Gregorb09518c2011-02-27 22:46:49 +00008599
Richard Smith6f8d2c62012-05-09 05:17:00 +00008600/// Determine whether this failed name lookup should be treated as being
8601/// disabled by a usage of std::enable_if.
8602static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8603 SourceRange &CondRange) {
8604 // We must be looking for a ::type...
8605 if (!II.isStr("type"))
8606 return false;
8607
8608 // ... within an explicitly-written template specialization...
8609 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8610 return false;
8611 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008612 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8613 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8614 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008615 return false;
8616 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008617 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008618
8619 // ... which names a complete class template declaration...
8620 const TemplateDecl *EnableIfDecl =
8621 EnableIfTST->getTemplateName().getAsTemplateDecl();
8622 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8623 return false;
8624
8625 // ... called "enable_if".
8626 const IdentifierInfo *EnableIfII =
8627 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8628 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8629 return false;
8630
8631 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008632 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008633 return true;
8634}
8635
Douglas Gregor333489b2009-03-27 23:10:48 +00008636/// \brief Build the type that describes a C++ typename specifier,
8637/// e.g., "typename T::type".
8638QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00008639Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008640 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00008641 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008642 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008643 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008644 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008645 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008646
John McCall0b66eb32010-05-01 00:40:08 +00008647 DeclContext *Ctx = computeDeclContext(SS);
8648 if (!Ctx) {
8649 // If the nested-name-specifier is dependent and couldn't be
8650 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008651 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008652 return Context.getDependentNameType(Keyword,
8653 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008654 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008655 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008656
John McCall0b66eb32010-05-01 00:40:08 +00008657 // If the nested-name-specifier refers to the current instantiation,
8658 // the "typename" keyword itself is superfluous. In C++03, the
8659 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8660 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008661 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008662
John McCall0b66eb32010-05-01 00:40:08 +00008663 if (RequireCompleteDeclContext(SS, Ctx))
8664 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008665
8666 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008667 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008668 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008669 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008670 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008671 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008672 case LookupResult::NotFound: {
8673 // If we're looking up 'type' within a template named 'enable_if', produce
8674 // a more specific diagnostic.
8675 SourceRange CondRange;
8676 if (isEnableIf(QualifierLoc, II, CondRange)) {
8677 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8678 << Ctx << CondRange;
8679 return QualType();
8680 }
8681
Douglas Gregore40876a2009-10-13 21:16:44 +00008682 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008683 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008684 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008685
8686 case LookupResult::FoundUnresolvedValue: {
8687 // We found a using declaration that is a value. Most likely, the using
8688 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008689 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008690 IILoc);
8691 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8692 << Name << Ctx << FullRange;
8693 if (UnresolvedUsingValueDecl *Using
8694 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008695 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008696 Diag(Loc, diag::note_using_value_decl_missing_typename)
8697 << FixItHint::CreateInsertion(Loc, "typename ");
8698 }
8699 }
8700 // Fall through to create a dependent typename type, from which we can recover
8701 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008702
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008703 case LookupResult::NotFoundInCurrentInstantiation:
8704 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00008705 return Context.getDependentNameType(Keyword,
8706 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008707 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008708
8709 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008710 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008711 // We found a type. Build an ElaboratedType, since the
8712 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008713 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008714 return Context.getElaboratedType(ETK_Typename,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008715 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008716 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008717 }
8718
8719 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008720 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008721 break;
8722
8723 case LookupResult::FoundOverloaded:
8724 DiagID = diag::err_typename_nested_not_type;
8725 Referenced = *Result.begin();
8726 break;
8727
John McCall6538c932009-10-10 05:48:19 +00008728 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008729 return QualType();
8730 }
8731
8732 // If we get here, it's because name lookup did not find a
8733 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008734 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008735 IILoc);
8736 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008737 if (Referenced)
8738 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8739 << Name;
8740 return QualType();
8741}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008742
8743namespace {
8744 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008745 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008746 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008747 SourceLocation Loc;
8748 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008749
Douglas Gregor15acfb92009-08-06 16:20:37 +00008750 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008751 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008752
Mike Stump11289f42009-09-09 15:08:12 +00008753 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008754 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008755 DeclarationName Entity)
8756 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008757 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008758
8759 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008760 /// transformed.
8761 ///
8762 /// For the purposes of type reconstruction, a type has already been
8763 /// transformed if it is NULL or if it is not dependent.
8764 bool AlreadyTransformed(QualType T) {
8765 return T.isNull() || !T->isDependentType();
8766 }
Mike Stump11289f42009-09-09 15:08:12 +00008767
8768 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008769 /// rebuilt.
8770 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008771
Douglas Gregor15acfb92009-08-06 16:20:37 +00008772 /// \brief Returns the name of the entity whose type is being rebuilt.
8773 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008774
Douglas Gregoref6ab412009-10-27 06:26:26 +00008775 /// \brief Sets the "base" location and entity when that
8776 /// information is known based on another transformation.
8777 void setBase(SourceLocation Loc, DeclarationName Entity) {
8778 this->Loc = Loc;
8779 this->Entity = Entity;
8780 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00008781
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008782 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8783 // Lambdas never need to be transformed.
8784 return E;
8785 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008786 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008787} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008788
Douglas Gregor15acfb92009-08-06 16:20:37 +00008789/// \brief Rebuilds a type within the context of the current instantiation.
8790///
Mike Stump11289f42009-09-09 15:08:12 +00008791/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008792/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008793/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008794/// partial specialization thereof). This routine will rebuild that type now
8795/// that we have entered the declarator's scope, which may produce different
8796/// canonical types, e.g.,
8797///
8798/// \code
8799/// template<typename T>
8800/// struct X {
8801/// typedef T* pointer;
8802/// pointer data();
8803/// };
8804///
8805/// template<typename T>
8806/// typename X<T>::pointer X<T>::data() { ... }
8807/// \endcode
8808///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008809/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008810/// since we do not know that we can look into X<T> when we parsed the type.
8811/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008812/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008813/// as the canonical type of T*, allowing the return types of the out-of-line
8814/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008815TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8816 SourceLocation Loc,
8817 DeclarationName Name) {
8818 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008819 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008820
Douglas Gregor15acfb92009-08-06 16:20:37 +00008821 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8822 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008823}
Douglas Gregorbe999392009-09-15 16:23:51 +00008824
John McCalldadc5752010-08-24 06:29:42 +00008825ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008826 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8827 DeclarationName());
8828 return Rebuilder.TransformExpr(E);
8829}
8830
John McCall99b2fe52010-04-29 23:50:39 +00008831bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00008832 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00008833 return true;
John McCall2408e322010-04-27 00:57:59 +00008834
Douglas Gregor10176412011-02-25 16:07:42 +00008835 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008836 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8837 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008838 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00008839 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008840 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00008841 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008842
Douglas Gregor10176412011-02-25 16:07:42 +00008843 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008844 return false;
John McCall2408e322010-04-27 00:57:59 +00008845}
8846
Douglas Gregor041b0842011-10-14 15:31:12 +00008847/// \brief Rebuild the template parameters now that we know we're in a current
8848/// instantiation.
8849bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8850 TemplateParameterList *Params) {
8851 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8852 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008853
Douglas Gregor041b0842011-10-14 15:31:12 +00008854 // There is nothing to rebuild in a type parameter.
8855 if (isa<TemplateTypeParmDecl>(Param))
8856 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008857
Douglas Gregor041b0842011-10-14 15:31:12 +00008858 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00008859 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00008860 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8861 if (RebuildTemplateParamsInCurrentInstantiation(
8862 TTP->getTemplateParameters()))
8863 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008864
Douglas Gregor041b0842011-10-14 15:31:12 +00008865 continue;
8866 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00008867
Douglas Gregor041b0842011-10-14 15:31:12 +00008868 // Rebuild the type of a non-type template parameter.
8869 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008870 TypeSourceInfo *NewTSI
8871 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8872 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00008873 NTTP->getDeclName());
8874 if (!NewTSI)
8875 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008876
Douglas Gregor041b0842011-10-14 15:31:12 +00008877 if (NewTSI != NTTP->getTypeSourceInfo()) {
8878 NTTP->setTypeSourceInfo(NewTSI);
8879 NTTP->setType(NewTSI->getType());
8880 }
8881 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00008882
Douglas Gregor041b0842011-10-14 15:31:12 +00008883 return false;
8884}
8885
Douglas Gregorbe999392009-09-15 16:23:51 +00008886/// \brief Produces a formatted string that describes the binding of
8887/// template parameters to template arguments.
8888std::string
8889Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8890 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008891 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008892}
8893
8894std::string
8895Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8896 const TemplateArgument *Args,
8897 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008898 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008899 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008900
Douglas Gregore62e6a02009-11-11 19:13:48 +00008901 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008902 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008903
Douglas Gregorbe999392009-09-15 16:23:51 +00008904 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008905 if (I >= NumArgs)
8906 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008907
Douglas Gregorbe999392009-09-15 16:23:51 +00008908 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008909 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008910 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008911 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008912
Douglas Gregorbe999392009-09-15 16:23:51 +00008913 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008914 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008915 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008916 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008918
Douglas Gregor0192c232010-12-20 16:52:59 +00008919 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008920 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008921 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008922
8923 Out << ']';
8924 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008925}
Francois Pichet1c229c02011-04-22 22:18:13 +00008926
Richard Smithe40f2ba2013-08-07 21:41:30 +00008927void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8928 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008929 if (!FD)
8930 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008931
Justin Lebar28f09c52016-10-10 16:26:08 +00008932 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008933
8934 // Take tokens to avoid allocations
8935 LPT->Toks.swap(Toks);
8936 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00008937 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008938
8939 FD->setLateTemplateParsed(true);
8940}
8941
8942void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8943 if (!FD)
8944 return;
8945 FD->setLateTemplateParsed(false);
8946}
Francois Pichet1c229c02011-04-22 22:18:13 +00008947
8948bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8949 DeclContext *DC = CurContext;
8950
8951 while (DC) {
8952 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8953 const FunctionDecl *FD = RD->isLocalClass();
8954 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8955 } else if (DC->isTranslationUnit() || DC->isNamespace())
8956 return false;
8957
8958 DC = DC->getParent();
8959 }
8960 return false;
8961}
Richard Smith6739a102016-05-05 00:56:12 +00008962
Benjamin Kramera0a13c32016-08-06 11:21:04 +00008963namespace {
Richard Smith6739a102016-05-05 00:56:12 +00008964/// \brief Walk the path from which a declaration was instantiated, and check
8965/// that every explicit specialization along that path is visible. This enforces
8966/// C++ [temp.expl.spec]/6:
8967///
8968/// If a template, a member template or a member of a class template is
8969/// explicitly specialized then that specialization shall be declared before
8970/// the first use of that specialization that would cause an implicit
8971/// instantiation to take place, in every translation unit in which such a
8972/// use occurs; no diagnostic is required.
8973///
8974/// and also C++ [temp.class.spec]/1:
8975///
8976/// A partial specialization shall be declared before the first use of a
8977/// class template specialization that would make use of the partial
8978/// specialization as the result of an implicit or explicit instantiation
8979/// in every translation unit in which such a use occurs; no diagnostic is
8980/// required.
8981class ExplicitSpecializationVisibilityChecker {
8982 Sema &S;
8983 SourceLocation Loc;
8984 llvm::SmallVector<Module *, 8> Modules;
8985
8986public:
8987 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
8988 : S(S), Loc(Loc) {}
8989
8990 void check(NamedDecl *ND) {
8991 if (auto *FD = dyn_cast<FunctionDecl>(ND))
8992 return checkImpl(FD);
8993 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
8994 return checkImpl(RD);
8995 if (auto *VD = dyn_cast<VarDecl>(ND))
8996 return checkImpl(VD);
8997 if (auto *ED = dyn_cast<EnumDecl>(ND))
8998 return checkImpl(ED);
8999 }
9000
9001private:
9002 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9003 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9004 : Sema::MissingImportKind::ExplicitSpecialization;
9005 const bool Recover = true;
9006
9007 // If we got a custom set of modules (because only a subset of the
9008 // declarations are interesting), use them, otherwise let
9009 // diagnoseMissingImport intelligently pick some.
9010 if (Modules.empty())
9011 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9012 else
9013 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9014 }
9015
9016 // Check a specific declaration. There are three problematic cases:
9017 //
9018 // 1) The declaration is an explicit specialization of a template
9019 // specialization.
9020 // 2) The declaration is an explicit specialization of a member of an
9021 // templated class.
9022 // 3) The declaration is an instantiation of a template, and that template
9023 // is an explicit specialization of a member of a templated class.
9024 //
9025 // We don't need to go any deeper than that, as the instantiation of the
9026 // surrounding class / etc is not triggered by whatever triggered this
9027 // instantiation, and thus should be checked elsewhere.
9028 template<typename SpecDecl>
9029 void checkImpl(SpecDecl *Spec) {
9030 bool IsHiddenExplicitSpecialization = false;
9031 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9032 IsHiddenExplicitSpecialization =
9033 Spec->getMemberSpecializationInfo()
9034 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9035 : !S.hasVisibleDeclaration(Spec);
9036 } else {
9037 checkInstantiated(Spec);
9038 }
9039
9040 if (IsHiddenExplicitSpecialization)
9041 diagnose(Spec->getMostRecentDecl(), false);
9042 }
9043
9044 void checkInstantiated(FunctionDecl *FD) {
9045 if (auto *TD = FD->getPrimaryTemplate())
9046 checkTemplate(TD);
9047 }
9048
9049 void checkInstantiated(CXXRecordDecl *RD) {
9050 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9051 if (!SD)
9052 return;
9053
9054 auto From = SD->getSpecializedTemplateOrPartial();
9055 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9056 checkTemplate(TD);
9057 else if (auto *TD =
9058 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9059 if (!S.hasVisibleDeclaration(TD))
9060 diagnose(TD, true);
9061 checkTemplate(TD);
9062 }
9063 }
9064
9065 void checkInstantiated(VarDecl *RD) {
9066 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9067 if (!SD)
9068 return;
9069
9070 auto From = SD->getSpecializedTemplateOrPartial();
9071 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9072 checkTemplate(TD);
9073 else if (auto *TD =
9074 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9075 if (!S.hasVisibleDeclaration(TD))
9076 diagnose(TD, true);
9077 checkTemplate(TD);
9078 }
9079 }
9080
9081 void checkInstantiated(EnumDecl *FD) {}
9082
9083 template<typename TemplDecl>
9084 void checkTemplate(TemplDecl *TD) {
9085 if (TD->isMemberSpecialization()) {
9086 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9087 diagnose(TD->getMostRecentDecl(), false);
9088 }
9089 }
9090};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009091} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00009092
9093void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
9094 if (!getLangOpts().Modules)
9095 return;
9096
9097 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9098}
9099
9100/// \brief Check whether a template partial specialization that we've discovered
9101/// is hidden, and produce suitable diagnostics if so.
9102void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
9103 NamedDecl *Spec) {
9104 llvm::SmallVector<Module *, 8> Modules;
9105 if (!hasVisibleDeclaration(Spec, &Modules))
9106 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9107 MissingImportKind::PartialSpecialization,
9108 /*Recover*/true);
9109}