blob: ce41a5eb74f6a515bd2a4bedadc219a69c86a22f [file] [log] [blame]
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +000011
Douglas Gregor15acfb92009-08-06 16:20:37 +000012#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000013#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000015#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000019#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000020#include "clang/AST/TypeVisitor.h"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000021#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedTemplate.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000032#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000034#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000035
Eric Fiselier6ad68552016-07-01 01:24:09 +000036#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000037using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000039
John McCall9b72f892010-11-10 02:40:36 +000040// Exported for use by Parser.
41SourceRange
42clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 unsigned N) {
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46}
47
Douglas Gregorb7bfe792009-09-02 22:59:36 +000048/// \brief Determine whether the declaration found is acceptable as the name
49/// of a template and, if so, return that template declaration. Otherwise,
50/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000051static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000052 NamedDecl *Orig,
53 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000054 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000055
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000056 if (isa<TemplateDecl>(D)) {
57 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000058 return nullptr;
59
John McCalle9cccd82010-06-16 08:42:20 +000060 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000061 }
Mike Stump11289f42009-09-09 15:08:12 +000062
Douglas Gregorb7bfe792009-09-02 22:59:36 +000063 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
64 // C++ [temp.local]p1:
65 // Like normal (non-template) classes, class templates have an
66 // injected-class-name (Clause 9). The injected-class-name
67 // can be used with or without a template-argument-list. When
68 // it is used without a template-argument-list, it is
69 // equivalent to the injected-class-name followed by the
70 // template-parameters of the class template enclosed in
71 // <>. When it is used with a template-argument-list, it
72 // refers to the specified class template specialization,
73 // which could be the current specialization or another
74 // specialization.
75 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000076 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000077 if (Record->getDescribedClassTemplate())
78 return Record->getDescribedClassTemplate();
79
80 if (ClassTemplateSpecializationDecl *Spec
81 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
82 return Spec->getSpecializedTemplate();
83 }
Mike Stump11289f42009-09-09 15:08:12 +000084
Craig Topperc3ec1492014-05-26 06:22:03 +000085 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000086 }
Mike Stump11289f42009-09-09 15:08:12 +000087
Craig Topperc3ec1492014-05-26 06:22:03 +000088 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000089}
90
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000091void Sema::FilterAcceptableTemplateNames(LookupResult &R,
92 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +000093 // The set of class templates we've already seen.
94 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000095 LookupResult::Filter filter = R.makeFilter();
96 while (filter.hasNext()) {
97 NamedDecl *Orig = filter.next();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000098 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
99 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +0000100 if (!Repl)
101 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000102 else if (Repl != Orig) {
103
104 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000105 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000106 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000107 // one base class). If all of the injected-class-names that are found
108 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000109 // is used as a template-name, the reference refers to the class
110 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000111 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000112 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000113 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000114 filter.erase();
115 continue;
116 }
John McCallbd8062d2010-08-13 07:02:08 +0000117
118 // FIXME: we promote access to public here as a workaround to
119 // the fact that LookupResult doesn't let us remember that we
120 // found this template through a particular injected class name,
121 // which means we end up doing nasty things to the invariants.
122 // Pretending that access is public is *much* safer.
123 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000124 }
John McCalle66edc12009-11-24 19:00:30 +0000125 }
126 filter.done();
127}
128
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000129bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
130 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000131 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000132 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000133 return true;
134
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000135 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000136}
137
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000138TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000139 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000140 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000141 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000142 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000143 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000144 TemplateTy &TemplateResult,
145 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000146 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000147
Douglas Gregor3cf81312009-11-03 23:16:33 +0000148 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000149 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000150
Douglas Gregor3cf81312009-11-03 23:16:33 +0000151 switch (Name.getKind()) {
152 case UnqualifiedId::IK_Identifier:
153 TName = DeclarationName(Name.Identifier);
154 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000155
Douglas Gregor3cf81312009-11-03 23:16:33 +0000156 case UnqualifiedId::IK_OperatorFunctionId:
157 TName = Context.DeclarationNames.getCXXOperatorName(
158 Name.OperatorFunctionId.Operator);
159 break;
160
Alexis Hunted0530f2009-11-28 08:58:14 +0000161 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000162 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
163 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000164
Douglas Gregor3cf81312009-11-03 23:16:33 +0000165 default:
166 return TNK_Non_template;
167 }
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCallba7bf592010-08-24 05:47:05 +0000169 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000170
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000171 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000172 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
173 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000174 if (R.empty()) return TNK_Non_template;
175 if (R.isAmbiguous()) {
176 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000177 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000178
179 // FIXME: we might have ambiguous templates, in which case we
180 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000181 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000182 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000183
John McCalld28ae272009-12-02 08:04:21 +0000184 TemplateName Template;
185 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000186
John McCalld28ae272009-12-02 08:04:21 +0000187 unsigned ResultCount = R.end() - R.begin();
188 if (ResultCount > 1) {
189 // We assume that we'll preserve the qualifier from a function
190 // template name in other ways.
191 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
192 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000193
194 // We'll do this lookup again later.
195 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000196 } else {
John McCalld28ae272009-12-02 08:04:21 +0000197 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
198
199 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000200 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000201 Template = Context.getQualifiedTemplateName(Qualifier,
202 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000203 } else {
204 Template = TemplateName(TD);
205 }
206
John McCalldcc71402010-08-13 02:23:42 +0000207 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000208 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000209
210 // We'll do this lookup again later.
211 R.suppressDiagnostics();
212 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000213 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000214 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
215 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000216 TemplateKind =
217 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000218 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000219 }
Mike Stump11289f42009-09-09 15:08:12 +0000220
John McCalld28ae272009-12-02 08:04:21 +0000221 TemplateResult = TemplateTy::make(Template);
222 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000223}
224
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000225bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000226 SourceLocation IILoc,
227 Scope *S,
228 const CXXScopeSpec *SS,
229 TemplateTy &SuggestedTemplate,
230 TemplateNameKind &SuggestedKind) {
231 // We can't recover unless there's a dependent scope specifier preceding the
232 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000233 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000234 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
235 computeDeclContext(*SS))
236 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000237
Douglas Gregor18473f32010-01-12 21:28:44 +0000238 // The code is missing a 'template' keyword prior to the dependent template
239 // name.
240 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
241 Diag(IILoc, diag::err_template_kw_missing)
242 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000243 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000244 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000245 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
246 SuggestedKind = TNK_Dependent_template_name;
247 return true;
248}
249
John McCalle66edc12009-11-24 19:00:30 +0000250void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000251 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000252 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000253 bool EnteringContext,
254 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000255 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000256 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000257 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000258 bool isDependent = false;
259 if (!ObjectType.isNull()) {
260 // This nested-name-specifier occurs in a member access expression, e.g.,
261 // x->B::f, and we are looking into the type of the object.
262 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
263 LookupCtx = computeDeclContext(ObjectType);
264 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000265 assert((isDependent || !ObjectType->isIncompleteType() ||
266 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000267 "Caller should have completed object type");
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000268
269 // Template names cannot appear inside an Objective-C class or object type.
270 if (ObjectType->isObjCObjectOrInterfaceType()) {
271 Found.clear();
272 return;
273 }
John McCalle66edc12009-11-24 19:00:30 +0000274 } else if (SS.isSet()) {
275 // This nested-name-specifier occurs after another nested-name-specifier,
276 // so long into the context associated with the prior nested-name-specifier.
277 LookupCtx = computeDeclContext(SS, EnteringContext);
278 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279
John McCalle66edc12009-11-24 19:00:30 +0000280 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000281 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000282 return;
283 }
284
285 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000286 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000287 if (LookupCtx) {
288 // Perform "qualified" name lookup into the declaration context we
289 // computed, which is either the type of the base of a member access
290 // expression or the declaration context associated with a prior
291 // nested-name-specifier.
292 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000293 if (!ObjectType.isNull() && Found.empty()) {
294 // C++ [basic.lookup.classref]p1:
295 // In a class member access expression (5.2.5), if the . or -> token is
296 // immediately followed by an identifier followed by a <, the
297 // identifier must be looked up to determine whether the < is the
298 // beginning of a template argument list (14.2) or a less-than operator.
299 // The identifier is first looked up in the class of the object
300 // expression. If the identifier is not found, it is then looked up in
301 // the context of the entire postfix-expression and shall name a class
302 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000303 if (S) LookupName(Found, S);
304 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000305 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000306 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000307 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000308 // We cannot look into a dependent object type or nested nme
309 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000310 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000311 return;
312 } else {
313 // Perform unqualified name lookup in the current scope.
314 LookupName(Found, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000315
316 if (!ObjectType.isNull())
317 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000318 }
319
Douglas Gregorc119dd52010-01-12 17:06:20 +0000320 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000321 // If we did not find any names, attempt to correct any typos.
322 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000323 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000324 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000325 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
326 FilterCCC->WantTypeSpecifiers = false;
327 FilterCCC->WantExpressionKeywords = false;
328 FilterCCC->WantRemainingKeywords = false;
329 FilterCCC->WantCXXNamedCasts = true;
330 if (TypoCorrection Corrected = CorrectTypo(
331 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
332 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000333 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000334 if (auto *ND = Corrected.getFoundDecl())
335 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000336 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000337 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000338 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000339 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
340 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000341 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000342 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
343 << Name << LookupCtx << DroppedSpecifier
344 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000345 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000346 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000347 }
John McCalle9cccd82010-06-16 08:42:20 +0000348 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000349 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000350 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000351 }
352 }
353
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000354 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000355 if (Found.empty()) {
356 if (isDependent)
357 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000358 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000359 }
John McCalle66edc12009-11-24 19:00:30 +0000360
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000361 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000362 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000363 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000364 // [...] If the lookup in the class of the object expression finds a
365 // template, the name is also looked up in the context of the entire
366 // postfix-expression and [...]
367 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000368 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000369 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
370 LookupOrdinaryName);
371 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000372 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000373
John McCalle66edc12009-11-24 19:00:30 +0000374 if (FoundOuter.empty()) {
375 // - if the name is not found, the name found in the class of the
376 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000377 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
378 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000379 // - if the name is found in the context of the entire
380 // postfix-expression and does not name a class template, the name
381 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000382 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000383 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000384 // - if the name found is a class template, it must refer to the same
385 // entity as the one found in the class of the object expression,
386 // otherwise the program is ill-formed.
387 if (!Found.isSingleResult() ||
388 Found.getFoundDecl()->getCanonicalDecl()
389 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000390 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000391 diag::ext_nested_name_member_ref_lookup_ambiguous)
392 << Found.getLookupName()
393 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000394 Diag(Found.getRepresentativeDecl()->getLocation(),
395 diag::note_ambig_member_ref_object_type)
396 << ObjectType;
397 Diag(FoundOuter.getFoundDecl()->getLocation(),
398 diag::note_ambig_member_ref_scope);
399
400 // Recover by taking the template that we found in the object
401 // expression's type.
402 }
403 }
404 }
405}
406
John McCallcd4b4772009-12-02 03:53:29 +0000407/// ActOnDependentIdExpression - Handle a dependent id-expression that
408/// was just parsed. This is only possible with an explicit scope
409/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000410ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000411Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000412 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000413 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000414 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000415 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000416 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417
Reid Kleckner1af391df2016-03-11 18:59:12 +0000418 // C++11 [expr.prim.general]p12:
419 // An id-expression that denotes a non-static data member or non-static
420 // member function of a class can only be used:
421 // (...)
422 // - if that id-expression denotes a non-static data member and it
423 // appears in an unevaluated operand.
424 //
425 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
426 // CXXDependentScopeMemberExpr. The former can instantiate to either
427 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
428 // always a MemberExpr.
429 bool MightBeCxx11UnevalField =
430 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
431
432 if (!MightBeCxx11UnevalField && !isAddressOfOperand &&
433 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000434 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000435
John McCalle66edc12009-11-24 19:00:30 +0000436 // Since the 'this' expression is synthesized, we don't need to
437 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000438 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000439
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000440 return CXXDependentScopeMemberExpr::Create(
441 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
442 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
443 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000444 }
445
Abramo Bagnara7945c982012-01-27 09:46:47 +0000446 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000447}
448
John McCalldadc5752010-08-24 06:29:42 +0000449ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000450Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000451 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000452 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000453 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000454 return DependentScopeDeclRefExpr::Create(
455 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
456 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000457}
458
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000459
460/// Determine whether we would be unable to instantiate this template (because
461/// it either has no definition, or is in the process of being instantiated).
462bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
463 NamedDecl *Instantiation,
464 bool InstantiatedFromMember,
465 const NamedDecl *Pattern,
466 const NamedDecl *PatternDef,
467 TemplateSpecializationKind TSK,
468 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000469 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
470 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000471
Richard Smithedbc6e92016-10-14 21:41:24 +0000472 bool IsEntityBeingDefined = false;
473 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
474 IsEntityBeingDefined = TD->isBeingDefined();
475
476 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000477 NamedDecl *SuggestedDef = nullptr;
478 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
479 /*OnlyNeedComplete*/false)) {
480 // If we're allowed to diagnose this and recover, do so.
481 bool Recover = Complain && !isSFINAEContext();
482 if (Complain)
483 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
484 Sema::MissingImportKind::Definition, Recover);
485 return !Recover;
486 }
487 return false;
488 }
489
Richard Smith6f4e2e02016-08-23 19:41:39 +0000490 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
491 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000492
Richard Smithedbc6e92016-10-14 21:41:24 +0000493 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000494 QualType InstantiationTy;
495 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
496 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000497 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000498 Diag(PointOfInstantiation,
499 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000500 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000501 << InstantiationTy;
502 // Not much point in noting the template declaration here, since
503 // we're lexically inside it.
504 Instantiation->setInvalidDecl();
505 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000506 if (isa<FunctionDecl>(Instantiation)) {
507 Diag(PointOfInstantiation,
508 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000509 << /*member function*/ 1 << Instantiation->getDeclName()
510 << Instantiation->getDeclContext();
511 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000512 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000513 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000514 Diag(PointOfInstantiation,
515 diag::err_implicit_instantiate_member_undefined)
516 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000517 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000518 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000519 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000520 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000521 Diag(PointOfInstantiation,
522 diag::err_explicit_instantiation_undefined_func_template)
523 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000524 Note = diag::note_explicit_instantiation_here;
525 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000526 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
527 << (TSK != TSK_ImplicitInstantiation)
528 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000529 Note = diag::note_template_decl_here;
530 } else {
531 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
532 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
533 Diag(PointOfInstantiation,
534 diag::err_explicit_instantiation_undefined_var_template)
535 << Instantiation;
536 Instantiation->setInvalidDecl();
537 } else
538 Diag(PointOfInstantiation,
539 diag::err_explicit_instantiation_undefined_member)
540 << /*static data member*/ 2 << Instantiation->getDeclName()
541 << Instantiation->getDeclContext();
542 Note = diag::note_explicit_instantiation_here;
543 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000544 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000545 if (Note) // Diagnostics were emitted.
546 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000547
548 // In general, Instantiation isn't marked invalid to get more than one
549 // error for multiple undefined instantiations. But the code that does
550 // explicit declaration -> explicit definition conversion can't handle
551 // invalid declarations, so mark as invalid in that case.
552 if (TSK == TSK_ExplicitInstantiationDeclaration)
553 Instantiation->setInvalidDecl();
554 return true;
555}
556
Douglas Gregor5101c242008-12-05 18:15:24 +0000557/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
558/// that the template parameter 'PrevDecl' is being shadowed by a new
559/// declaration at location Loc. Returns true to indicate that this is
560/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000561void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000562 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000563
564 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000565 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000566 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000567
568 // C++ [temp.local]p4:
569 // A template-parameter shall not be redeclared within its
570 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000571 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000572 << cast<NamedDecl>(PrevDecl)->getDeclName();
573 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000574}
575
Douglas Gregor463421d2009-03-03 04:44:36 +0000576/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000577/// the parameter D to reference the templated declaration and return a pointer
578/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000579TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
580 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
581 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000582 return Temp;
583 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000584 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000585}
586
Douglas Gregoreb29d182011-01-05 17:40:24 +0000587ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
588 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000590 "Only template template arguments can be pack expansions here");
591 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
592 "Template template argument pack expansion without packs");
593 ParsedTemplateArgument Result(*this);
594 Result.EllipsisLoc = EllipsisLoc;
595 return Result;
596}
597
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000598static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
599 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000601 switch (Arg.getKind()) {
602 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000603 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000604 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000606 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000607 return TemplateArgumentLoc(TemplateArgument(T), DI);
608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000610 case ParsedTemplateArgument::NonType: {
611 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
612 return TemplateArgumentLoc(TemplateArgument(E), E);
613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000615 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000616 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000617 TemplateArgument TArg;
618 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000619 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000620 else
621 TArg = Template;
622 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000623 Arg.getScopeSpec().getWithLocInContext(
624 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000625 Arg.getLocation(),
626 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000627 }
628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000629
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000630 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000631}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000633/// \brief Translates template arguments as provided by the parser
634/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000635void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
636 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000637 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000638 TemplateArgs.addArgument(translateTemplateArgument(*this,
639 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000640}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000641
Richard Smithb80d5402013-06-25 22:21:36 +0000642static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
643 SourceLocation Loc,
644 IdentifierInfo *Name) {
645 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
646 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
647 if (PrevDecl && PrevDecl->isTemplateParameter())
648 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
649}
650
Douglas Gregor5101c242008-12-05 18:15:24 +0000651/// ActOnTypeParameter - Called when a C++ template type parameter
652/// (e.g., "typename T") has been parsed. Typename specifies whether
653/// the keyword "typename" was used to declare the type parameter
654/// (otherwise, "class" was used), and KeyLoc is the location of the
655/// "class" or "typename" keyword. ParamName is the name of the
656/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000657/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000658/// If the type parameter has a default argument, it will be added
659/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000660Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000661 SourceLocation EllipsisLoc,
662 SourceLocation KeyLoc,
663 IdentifierInfo *ParamName,
664 SourceLocation ParamNameLoc,
665 unsigned Depth, unsigned Position,
666 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000667 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000668 assert(S->isTemplateParamScope() &&
669 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000670
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000671 SourceLocation Loc = ParamNameLoc;
672 if (!ParamName)
673 Loc = KeyLoc;
674
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000675 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000676 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000677 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000678 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000679 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000680 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000681
682 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000683 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
684
Douglas Gregor5101c242008-12-05 18:15:24 +0000685 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000686 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000687 IdResolver.AddDecl(Param);
688 }
689
Douglas Gregorf5500772011-01-05 15:48:55 +0000690 // C++0x [temp.param]p9:
691 // A default template-argument may be specified for any kind of
692 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000693 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000694 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000695 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000696 }
697
Douglas Gregordc13ded2010-07-01 00:00:45 +0000698 // Handle the default argument, if provided.
699 if (DefaultArg) {
700 TypeSourceInfo *DefaultTInfo;
701 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000702
Douglas Gregordc13ded2010-07-01 00:00:45 +0000703 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000705 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000706 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000707 UPPC_DefaultArgument))
708 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709
Douglas Gregordc13ded2010-07-01 00:00:45 +0000710 // Check the template argument itself.
711 if (CheckTemplateArgument(Param, DefaultTInfo)) {
712 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000713 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000715
Richard Smith1469b912015-06-10 00:29:03 +0000716 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000717 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000718
John McCall48871652010-08-21 09:40:31 +0000719 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000720}
721
Douglas Gregor463421d2009-03-03 04:44:36 +0000722/// \brief Check that the type of a non-type template parameter is
723/// well-formed.
724///
725/// \returns the (possibly-promoted) parameter type if valid;
726/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000727QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000728Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000729 // We don't allow variably-modified types as the type of non-type template
730 // parameters.
731 if (T->isVariablyModifiedType()) {
732 Diag(Loc, diag::err_variably_modified_nontype_template_param)
733 << T;
734 return QualType();
735 }
736
Douglas Gregor463421d2009-03-03 04:44:36 +0000737 // C++ [temp.param]p4:
738 //
739 // A non-type template-parameter shall have one of the following
740 // (optionally cv-qualified) types:
741 //
742 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000743 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000744 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000745 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000746 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000747 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000748 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000749 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000750 // -- std::nullptr_t.
751 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000752 // If T is a dependent type, we can't do the check now, so we
753 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +0000754 T->isDependentType() ||
755 // Allow use of auto in template parameter declarations.
756 T->isUndeducedType()) {
757 if (T->isUndeducedType()) {
758 Diag(Loc, diag::warn_cxx14_compat_template_nontype_parm_auto_type)
759 << QualType(T->getContainedAutoType(), 0);
760 }
Richard Smithd0e1c952012-03-13 07:21:50 +0000761 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
762 // are ignored when determining its type.
763 return T.getUnqualifiedType();
764 }
765
Douglas Gregor463421d2009-03-03 04:44:36 +0000766 // C++ [temp.param]p8:
767 //
768 // A non-type template-parameter of type "array of T" or
769 // "function returning T" is adjusted to be of type "pointer to
770 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000771 else if (T->isArrayType() || T->isFunctionType())
772 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000773
Douglas Gregor463421d2009-03-03 04:44:36 +0000774 Diag(Loc, diag::err_template_nontype_parm_bad_type)
775 << T;
776
777 return QualType();
778}
779
John McCall48871652010-08-21 09:40:31 +0000780Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
781 unsigned Depth,
782 unsigned Position,
783 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000784 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000785 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
786 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000787
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000788 assert(S->isTemplateParamScope() &&
789 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000790 bool Invalid = false;
791
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000792 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
793 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000794 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000795 Invalid = true;
796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797
Richard Smithb80d5402013-06-25 22:21:36 +0000798 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000799 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000800 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000801 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000802 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000803 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000804 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000805 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000806 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000807
Douglas Gregor5101c242008-12-05 18:15:24 +0000808 if (Invalid)
809 Param->setInvalidDecl();
810
Richard Smithb80d5402013-06-25 22:21:36 +0000811 if (ParamName) {
812 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
813 ParamName);
814
Douglas Gregor5101c242008-12-05 18:15:24 +0000815 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000816 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000817 IdResolver.AddDecl(Param);
818 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819
Douglas Gregorf5500772011-01-05 15:48:55 +0000820 // C++0x [temp.param]p9:
821 // A default template-argument may be specified for any kind of
822 // template-parameter that is not a template parameter pack.
823 if (Default && IsParameterPack) {
824 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000825 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000826 }
827
Douglas Gregordc13ded2010-07-01 00:00:45 +0000828 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000829 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000830 // Check for unexpanded parameter packs.
831 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
832 return Param;
833
Douglas Gregordc13ded2010-07-01 00:00:45 +0000834 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000835 ExprResult DefaultRes =
836 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000837 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000838 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000839 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000840 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000841 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842
Richard Smith1469b912015-06-10 00:29:03 +0000843 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000844 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000845
John McCall48871652010-08-21 09:40:31 +0000846 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000847}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000848
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000849/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000850/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000851/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000852Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
853 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000854 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000855 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000856 IdentifierInfo *Name,
857 SourceLocation NameLoc,
858 unsigned Depth,
859 unsigned Position,
860 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000861 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000862 assert(S->isTemplateParamScope() &&
863 "Template template parameter not in template parameter scope!");
864
865 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000866 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000867 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000868 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000869 NameLoc.isInvalid()? TmpLoc : NameLoc,
870 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000871 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000872 Param->setAccess(AS_public);
873
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000874 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000875 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000876 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000877 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
878
John McCall48871652010-08-21 09:40:31 +0000879 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000880 IdResolver.AddDecl(Param);
881 }
882
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000883 if (Params->size() == 0) {
884 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
885 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
886 Param->setInvalidDecl();
887 }
888
Douglas Gregorf5500772011-01-05 15:48:55 +0000889 // C++0x [temp.param]p9:
890 // A default template-argument may be specified for any kind of
891 // template-parameter that is not a template parameter pack.
892 if (IsParameterPack && !Default.isInvalid()) {
893 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
894 Default = ParsedTemplateArgument();
895 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000896
Douglas Gregordc13ded2010-07-01 00:00:45 +0000897 if (!Default.isInvalid()) {
898 // Check only that we have a template template argument. We don't want to
899 // try to check well-formedness now, because our template template parameter
900 // might have dependent types in its template parameters, which we wouldn't
901 // be able to match now.
902 //
903 // If none of the template template parameter's template arguments mention
904 // other template parameters, we could actually perform more checking here.
905 // However, it isn't worth doing.
906 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
907 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000908 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000909 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000910 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000911 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000912
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000913 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000914 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000915 DefaultArg.getArgument().getAsTemplate(),
916 UPPC_DefaultArgument))
917 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000918
Richard Smith1469b912015-06-10 00:29:03 +0000919 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000920 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000921
John McCall48871652010-08-21 09:40:31 +0000922 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000923}
924
Hubert Tongf608c052016-04-29 18:05:37 +0000925/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
926/// constrained by RequiresClause, that contains the template parameters in
927/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000928TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000929Sema::ActOnTemplateParameterList(unsigned Depth,
930 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000931 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000932 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000933 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +0000934 SourceLocation RAngleLoc,
935 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000936 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000937 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000938
David Majnemer902f8c62015-12-27 07:16:27 +0000939 return TemplateParameterList::Create(
940 Context, TemplateLoc, LAngleLoc,
941 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000942 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000943}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000944
John McCall3e11ebe2010-03-15 10:12:16 +0000945static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
946 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000947 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000948}
949
John McCallfaf5fb42010-08-26 23:41:50 +0000950DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000951Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000952 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000953 IdentifierInfo *Name, SourceLocation NameLoc,
954 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000955 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000956 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000957 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000958 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000959 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000960 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000961 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000962 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000963 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000964 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000965
966 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000967 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000968 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000969
Abramo Bagnara6150c882010-05-11 21:36:43 +0000970 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
971 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000972
973 // There is no such thing as an unnamed class template.
974 if (!Name) {
975 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000976 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000977 }
978
Richard Smith6483d222012-04-21 01:27:54 +0000979 // Find any previous declaration with this name. For a friend with no
980 // scope explicitly specified, we only look for tag declarations (per
981 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000982 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000983 LookupResult Previous(*this, Name, NameLoc,
984 (SS.isEmpty() && TUK == TUK_Friend)
985 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000986 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000987 if (SS.isNotEmpty() && !SS.isInvalid()) {
988 SemanticContext = computeDeclContext(SS, true);
989 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000990 // FIXME: Horrible, horrible hack! We can't currently represent this
991 // in the AST, and historically we have just ignored such friend
992 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000993 Diag(NameLoc, TUK == TUK_Friend
994 ? diag::warn_template_qualified_friend_ignored
995 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000996 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000997 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000998 }
Mike Stump11289f42009-09-09 15:08:12 +0000999
John McCall0b66eb32010-05-01 00:40:08 +00001000 if (RequireCompleteDeclContext(SS, SemanticContext))
1001 return true;
1002
Douglas Gregor041b0842011-10-14 15:31:12 +00001003 // If we're adding a template to a dependent context, we may need to
1004 // rebuilding some of the types used within the template parameter list,
1005 // now that we know what the current instantiation is.
1006 if (SemanticContext->isDependentContext()) {
1007 ContextRAII SavedContext(*this, SemanticContext);
1008 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1009 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001010 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1011 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +00001012
John McCall27b18f82009-11-17 02:14:36 +00001013 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001014 } else {
1015 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001016
1017 // C++14 [class.mem]p14:
1018 // If T is the name of a class, then each of the following shall have a
1019 // name different from T:
1020 // -- every member template of class T
1021 if (TUK != TUK_Friend &&
1022 DiagnoseClassNameShadow(SemanticContext,
1023 DeclarationNameInfo(Name, NameLoc)))
1024 return true;
1025
John McCall27b18f82009-11-17 02:14:36 +00001026 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001027 }
Mike Stump11289f42009-09-09 15:08:12 +00001028
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001029 if (Previous.isAmbiguous())
1030 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001031
Craig Topperc3ec1492014-05-26 06:22:03 +00001032 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001033 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001034 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001035
Serge Pavlove50bf752016-06-10 04:39:07 +00001036 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1037 // Maybe we will complain about the shadowed template parameter.
1038 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1039 // Just pretend that we didn't see the previous declaration.
1040 PrevDecl = nullptr;
1041 }
1042
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001043 // If there is a previous declaration with the same name, check
1044 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +00001045 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001046 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001047
1048 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001049 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001050 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001051 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001052 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1053 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001054 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001055 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1056 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1057 PrevClassTemplate
1058 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1059 ->getSpecializedTemplate();
1060 }
1061 }
1062
John McCalld43784f2009-12-18 11:25:59 +00001063 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001064 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001065 // [...] When looking for a prior declaration of a class or a function
1066 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001067 // function is neither a qualified name nor a template-id, scopes outside
1068 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001069 if (!SS.isSet()) {
1070 DeclContext *OutermostContext = CurContext;
1071 while (!OutermostContext->isFileContext())
1072 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001073
Richard Smith61e582f2012-04-20 07:12:26 +00001074 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001075 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1076 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1077 SemanticContext = PrevDecl->getDeclContext();
1078 } else {
1079 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001080 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001081 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001082 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001083 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001084
1085 // Check that the chosen semantic context doesn't already contain a
1086 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001087 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001088 DeclContext *LookupContext = SemanticContext;
1089 while (LookupContext->isTransparentContext())
1090 LookupContext = LookupContext->getLookupParent();
1091 LookupQualifiedName(Previous, LookupContext);
1092
1093 if (Previous.isAmbiguous())
1094 return true;
1095
1096 if (Previous.begin() != Previous.end())
1097 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001098 }
John McCall90d3bb92009-12-17 23:21:11 +00001099 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001100 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001101 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1102 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001103 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001104
Richard Smithfc805ca2015-07-06 04:43:58 +00001105 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1106 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1107 if (SS.isEmpty() &&
1108 !(PrevClassTemplate &&
1109 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1110 SemanticContext->getRedeclContext()))) {
1111 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1112 Diag(Shadow->getTargetDecl()->getLocation(),
1113 diag::note_using_decl_target);
1114 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1115 // Recover by ignoring the old declaration.
1116 PrevDecl = PrevClassTemplate = nullptr;
1117 }
1118 }
1119
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001120 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001121 // Ensure that the template parameter lists are compatible. Skip this check
1122 // for a friend in a dependent context: the template parameter list itself
1123 // could be dependent.
1124 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1125 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001126 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001127 /*Complain=*/true,
1128 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001129 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001130
1131 // C++ [temp.class]p4:
1132 // In a redeclaration, partial specialization, explicit
1133 // specialization or explicit instantiation of a class template,
1134 // the class-key shall agree in kind with the original class
1135 // template declaration (7.1.5.3).
1136 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001137 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001138 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001139 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001140 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001141 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001142 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001143 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001144 }
1145
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001146 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001147 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001148 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001149 // If we have a prior definition that is not visible, treat this as
1150 // simply making that previous definition visible.
1151 NamedDecl *Hidden = nullptr;
1152 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001153 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001154 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1155 assert(Tmpl && "original definition of a class template is not a "
1156 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001157 makeMergedDefinitionVisible(Hidden, KWLoc);
1158 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001159 return Def;
1160 }
1161
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001162 Diag(NameLoc, diag::err_redefinition) << Name;
1163 Diag(Def->getLocation(), diag::note_previous_definition);
1164 // FIXME: Would it make sense to try to "forget" the previous
1165 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001166 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001167 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001168 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001169 } else if (PrevDecl) {
1170 // C++ [temp]p5:
1171 // A class template shall not have the same name as any other
1172 // template, class, function, object, enumeration, enumerator,
1173 // namespace, or type in the same scope (3.3), except as specified
1174 // in (14.5.4).
1175 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1176 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001177 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001178 }
1179
Douglas Gregordba32632009-02-10 19:49:53 +00001180 // Check the template parameter list of this declaration, possibly
1181 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001182 // template declaration. Skip this check for a friend in a dependent
1183 // context, because the template parameter list might be dependent.
1184 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001185 CheckTemplateParameterList(
1186 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001187 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1188 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001189 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1190 SemanticContext->isDependentContext())
1191 ? TPC_ClassTemplateMember
1192 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1193 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001194 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001195
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001196 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001197 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001198 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001199 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1200 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001201 : diag::err_member_decl_does_not_match)
1202 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001203 Invalid = true;
1204 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001205 }
1206
Mike Stump11289f42009-09-09 15:08:12 +00001207 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001208 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001209 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001210 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001211 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001212 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001213 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001214 NewClass->setTemplateParameterListsInfo(
1215 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1216 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001217
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001218 // Add alignment attributes if necessary; these attributes are checked when
1219 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001220 if (TUK == TUK_Definition) {
1221 AddAlignmentAttributesForRecord(NewClass);
1222 AddMsStructLayoutForRecord(NewClass);
1223 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001224
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001225 ClassTemplateDecl *NewTemplate
1226 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1227 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001228 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001229 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001230
Douglas Gregor21823bf2011-12-20 18:11:52 +00001231 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001232 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001233
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001234 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001235 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001236 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001237 assert(T->isDependentType() && "Class template type is not dependent?");
1238 (void)T;
1239
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001240 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001241 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001242 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001243 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1244 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001245
Anders Carlsson137108d2009-03-26 01:24:28 +00001246 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001247 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001248 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001249
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001250 // Set the lexical context of these templates
1251 NewClass->setLexicalDeclContext(CurContext);
1252 NewTemplate->setLexicalDeclContext(CurContext);
1253
John McCall9bb74a52009-07-31 02:45:11 +00001254 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001255 NewClass->startDefinition();
1256
1257 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001258 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001259
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001260 if (PrevClassTemplate)
1261 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1262
Rafael Espindola385c0422012-07-13 18:04:45 +00001263 AddPushedVisibilityAttribute(NewClass);
1264
Richard Smith234ff472014-08-23 00:49:01 +00001265 if (TUK != TUK_Friend) {
1266 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1267 Scope *Outer = S;
1268 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1269 Outer = Outer->getParent();
1270 PushOnScopeChains(NewTemplate, Outer);
1271 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001272 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001273 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001274 NewClass->setAccess(PrevClassTemplate->getAccess());
1275 }
John McCall27b5c252009-09-14 21:59:20 +00001276
Richard Smith64017682013-07-17 23:53:16 +00001277 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278
John McCall27b5c252009-09-14 21:59:20 +00001279 // Friend templates are visible in fairly strange ways.
1280 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001281 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001282 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001283 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1284 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001285 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001288 FriendDecl *Friend = FriendDecl::Create(
1289 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001290 Friend->setAccess(AS_public);
1291 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001292 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001293
Douglas Gregordba32632009-02-10 19:49:53 +00001294 if (Invalid) {
1295 NewTemplate->setInvalidDecl();
1296 NewClass->setInvalidDecl();
1297 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001298
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001299 ActOnDocumentableDecl(NewTemplate);
1300
John McCall48871652010-08-21 09:40:31 +00001301 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001302}
1303
Douglas Gregored5731f2009-11-25 17:50:39 +00001304/// \brief Diagnose the presence of a default template argument on a
1305/// template parameter, which is ill-formed in certain contexts.
1306///
1307/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001308static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001309 Sema::TemplateParamListContext TPC,
1310 SourceLocation ParamLoc,
1311 SourceRange DefArgRange) {
1312 switch (TPC) {
1313 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001314 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001315 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001316 return false;
1317
1318 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001319 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001320 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001321 // A default template-argument shall not be specified in a
1322 // function template declaration or a function template
1323 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001324 // If a friend function template declaration specifies a default
1325 // template-argument, that declaration shall be a definition and shall be
1326 // the only declaration of the function template in the translation unit.
1327 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001328 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001329 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1330 : diag::ext_template_parameter_default_in_function_template)
1331 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001332 return false;
1333
1334 case Sema::TPC_ClassTemplateMember:
1335 // C++0x [temp.param]p9:
1336 // A default template-argument shall not be specified in the
1337 // template-parameter-lists of the definition of a member of a
1338 // class template that appears outside of the member's class.
1339 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1340 << DefArgRange;
1341 return true;
1342
David Majnemerba8f17a2013-06-25 22:08:55 +00001343 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001344 case Sema::TPC_FriendFunctionTemplate:
1345 // C++ [temp.param]p9:
1346 // A default template-argument shall not be specified in a
1347 // friend template declaration.
1348 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1349 << DefArgRange;
1350 return true;
1351
1352 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1353 // for friend function templates if there is only a single
1354 // declaration (and it is a definition). Strange!
1355 }
1356
David Blaikie8a40f702012-01-17 06:56:22 +00001357 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001358}
1359
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001360/// \brief Check for unexpanded parameter packs within the template parameters
1361/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001362static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1363 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001364 // A template template parameter which is a parameter pack is also a pack
1365 // expansion.
1366 if (TTP->isParameterPack())
1367 return false;
1368
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001369 TemplateParameterList *Params = TTP->getTemplateParameters();
1370 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1371 NamedDecl *P = Params->getParam(I);
1372 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001373 if (!NTTP->isParameterPack() &&
1374 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001375 NTTP->getTypeSourceInfo(),
1376 Sema::UPPC_NonTypeTemplateParameterType))
1377 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001378
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001379 continue;
1380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001381
1382 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001383 = dyn_cast<TemplateTemplateParmDecl>(P))
1384 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1385 return true;
1386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001388 return false;
1389}
1390
Douglas Gregordba32632009-02-10 19:49:53 +00001391/// \brief Checks the validity of a template parameter list, possibly
1392/// considering the template parameter list from a previous
1393/// declaration.
1394///
1395/// If an "old" template parameter list is provided, it must be
1396/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1397/// template parameter list.
1398///
1399/// \param NewParams Template parameter list for a new template
1400/// declaration. This template parameter list will be updated with any
1401/// default arguments that are carried through from the previous
1402/// template parameter list.
1403///
1404/// \param OldParams If provided, template parameter list from a
1405/// previous declaration of the same template. Default template
1406/// arguments will be merged from the old template parameter list to
1407/// the new template parameter list.
1408///
Douglas Gregored5731f2009-11-25 17:50:39 +00001409/// \param TPC Describes the context in which we are checking the given
1410/// template parameter list.
1411///
Douglas Gregordba32632009-02-10 19:49:53 +00001412/// \returns true if an error occurred, false otherwise.
1413bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001414 TemplateParameterList *OldParams,
1415 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001416 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001417
Douglas Gregordba32632009-02-10 19:49:53 +00001418 // C++ [temp.param]p10:
1419 // The set of default template-arguments available for use with a
1420 // template declaration or definition is obtained by merging the
1421 // default arguments from the definition (if in scope) and all
1422 // declarations in scope in the same way default function
1423 // arguments are (8.3.6).
1424 bool SawDefaultArgument = false;
1425 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001426
Mike Stumpc89c8e32009-02-11 23:03:27 +00001427 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001428 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001429 if (OldParams)
1430 OldParam = OldParams->begin();
1431
Douglas Gregor0693def2011-01-27 01:40:17 +00001432 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001433 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1434 NewParamEnd = NewParams->end();
1435 NewParam != NewParamEnd; ++NewParam) {
1436 // Variables used to diagnose redundant default arguments
1437 bool RedundantDefaultArg = false;
1438 SourceLocation OldDefaultLoc;
1439 SourceLocation NewDefaultLoc;
1440
David Blaikie651c73c2011-10-19 05:19:50 +00001441 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001442 bool MissingDefaultArg = false;
1443
David Blaikie651c73c2011-10-19 05:19:50 +00001444 // Variable used to diagnose non-final parameter packs
1445 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001446
Douglas Gregordba32632009-02-10 19:49:53 +00001447 if (TemplateTypeParmDecl *NewTypeParm
1448 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001449 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001450 if (NewTypeParm->hasDefaultArgument() &&
1451 DiagnoseDefaultTemplateArgument(*this, TPC,
1452 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001453 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001454 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001455 NewTypeParm->removeDefaultArgument();
1456
1457 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001458 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001459 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001460 if (NewTypeParm->isParameterPack()) {
1461 assert(!NewTypeParm->hasDefaultArgument() &&
1462 "Parameter packs can't have a default argument!");
1463 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001464 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001465 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001466 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1467 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1468 SawDefaultArgument = true;
1469 RedundantDefaultArg = true;
1470 PreviousDefaultArgLoc = NewDefaultLoc;
1471 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1472 // Merge the default argument from the old declaration to the
1473 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001474 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001475 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1476 } else if (NewTypeParm->hasDefaultArgument()) {
1477 SawDefaultArgument = true;
1478 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1479 } else if (SawDefaultArgument)
1480 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001481 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001482 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001483 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001484 if (!NewNonTypeParm->isParameterPack() &&
1485 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001486 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001487 UPPC_NonTypeTemplateParameterType)) {
1488 Invalid = true;
1489 continue;
1490 }
1491
Douglas Gregored5731f2009-11-25 17:50:39 +00001492 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001493 if (NewNonTypeParm->hasDefaultArgument() &&
1494 DiagnoseDefaultTemplateArgument(*this, TPC,
1495 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001496 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001497 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001498 }
1499
Mike Stump12b8ce12009-08-04 21:02:39 +00001500 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001501 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001502 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001503 if (NewNonTypeParm->isParameterPack()) {
1504 assert(!NewNonTypeParm->hasDefaultArgument() &&
1505 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001506 if (!NewNonTypeParm->isPackExpansion())
1507 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001508 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001509 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001510 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1511 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1512 SawDefaultArgument = true;
1513 RedundantDefaultArg = true;
1514 PreviousDefaultArgLoc = NewDefaultLoc;
1515 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1516 // Merge the default argument from the old declaration to the
1517 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001518 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001519 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1520 } else if (NewNonTypeParm->hasDefaultArgument()) {
1521 SawDefaultArgument = true;
1522 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1523 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001524 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001525 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001526 TemplateTemplateParmDecl *NewTemplateParm
1527 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001528
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001529 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001530 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001531 Invalid = true;
1532 continue;
1533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001534
David Blaikie651c73c2011-10-19 05:19:50 +00001535 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001536 if (NewTemplateParm->hasDefaultArgument() &&
1537 DiagnoseDefaultTemplateArgument(*this, TPC,
1538 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001539 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001540 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001541
1542 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001543 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001544 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001545 if (NewTemplateParm->isParameterPack()) {
1546 assert(!NewTemplateParm->hasDefaultArgument() &&
1547 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001548 if (!NewTemplateParm->isPackExpansion())
1549 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001550 } else if (OldTemplateParm &&
1551 hasVisibleDefaultArgument(OldTemplateParm) &&
1552 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001553 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1554 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001555 SawDefaultArgument = true;
1556 RedundantDefaultArg = true;
1557 PreviousDefaultArgLoc = NewDefaultLoc;
1558 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1559 // Merge the default argument from the old declaration to the
1560 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001561 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001562 PreviousDefaultArgLoc
1563 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001564 } else if (NewTemplateParm->hasDefaultArgument()) {
1565 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001566 PreviousDefaultArgLoc
1567 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001568 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001569 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001570 }
1571
Richard Smith1fde8ec2012-09-07 02:06:42 +00001572 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001573 // If a template parameter of a primary class template or alias template
1574 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001575 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001576 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1577 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001578 Diag((*NewParam)->getLocation(),
1579 diag::err_template_param_pack_must_be_last_template_parameter);
1580 Invalid = true;
1581 }
1582
Douglas Gregordba32632009-02-10 19:49:53 +00001583 if (RedundantDefaultArg) {
1584 // C++ [temp.param]p12:
1585 // A template-parameter shall not be given default arguments
1586 // by two different declarations in the same scope.
1587 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1588 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1589 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001590 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001591 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001592 // If a template-parameter of a class template has a default
1593 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001594 // have a default template-argument supplied or be a template parameter
1595 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001596 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001597 diag::err_template_param_default_arg_missing);
1598 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1599 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001600 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001601 }
1602
1603 // If we have an old template parameter list that we're merging
1604 // in, move on to the next parameter.
1605 if (OldParams)
1606 ++OldParam;
1607 }
1608
Douglas Gregor0693def2011-01-27 01:40:17 +00001609 // We were missing some default arguments at the end of the list, so remove
1610 // all of the default arguments.
1611 if (RemoveDefaultArguments) {
1612 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1613 NewParamEnd = NewParams->end();
1614 NewParam != NewParamEnd; ++NewParam) {
1615 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1616 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001617 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001618 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1619 NTTP->removeDefaultArgument();
1620 else
1621 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1622 }
1623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001624
Douglas Gregordba32632009-02-10 19:49:53 +00001625 return Invalid;
1626}
Douglas Gregord32e0282009-02-09 23:23:08 +00001627
John McCalla020a012010-10-20 05:44:58 +00001628namespace {
1629
1630/// A class which looks for a use of a certain level of template
1631/// parameter.
1632struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1633 typedef RecursiveASTVisitor<DependencyChecker> super;
1634
1635 unsigned Depth;
1636 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001637 SourceLocation MatchLoc;
1638
1639 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001640
1641 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1642 NamedDecl *ND = Params->getParam(0);
1643 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1644 Depth = PD->getDepth();
1645 } else if (NonTypeTemplateParmDecl *PD =
1646 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1647 Depth = PD->getDepth();
1648 } else {
1649 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1650 }
1651 }
1652
Richard Smith6056d5e2014-02-09 00:54:43 +00001653 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001654 if (ParmDepth >= Depth) {
1655 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001656 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001657 return true;
1658 }
1659 return false;
1660 }
1661
Richard Smith6056d5e2014-02-09 00:54:43 +00001662 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1663 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1664 }
1665
John McCalla020a012010-10-20 05:44:58 +00001666 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1667 return !Matches(T->getDepth());
1668 }
1669
1670 bool TraverseTemplateName(TemplateName N) {
1671 if (TemplateTemplateParmDecl *PD =
1672 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001673 if (Matches(PD->getDepth()))
1674 return false;
John McCalla020a012010-10-20 05:44:58 +00001675 return super::TraverseTemplateName(N);
1676 }
1677
1678 bool VisitDeclRefExpr(DeclRefExpr *E) {
1679 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001680 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1681 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001682 return false;
John McCalla020a012010-10-20 05:44:58 +00001683 return super::VisitDeclRefExpr(E);
1684 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001685
1686 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1687 return TraverseType(T->getReplacementType());
1688 }
1689
1690 bool
1691 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1692 return TraverseTemplateArgument(T->getArgumentPack());
1693 }
1694
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001695 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1696 return TraverseType(T->getInjectedSpecializationType());
1697 }
John McCalla020a012010-10-20 05:44:58 +00001698};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001699} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001700
Douglas Gregor972fe532011-05-10 18:27:06 +00001701/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001702/// list.
1703static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001704DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001705 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001706 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001707 return Checker.Match;
1708}
1709
Douglas Gregor972fe532011-05-10 18:27:06 +00001710// Find the source range corresponding to the named type in the given
1711// nested-name-specifier, if any.
1712static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1713 QualType T,
1714 const CXXScopeSpec &SS) {
1715 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1716 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1717 if (const Type *CurType = NNS->getAsType()) {
1718 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1719 return NNSLoc.getTypeLoc().getSourceRange();
1720 } else
1721 break;
1722
1723 NNSLoc = NNSLoc.getPrefix();
1724 }
1725
1726 return SourceRange();
1727}
1728
Mike Stump11289f42009-09-09 15:08:12 +00001729/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001730/// specifier, returning the template parameter list that applies to the
1731/// name.
1732///
1733/// \param DeclStartLoc the start of the declaration that has a scope
1734/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001735///
Douglas Gregor972fe532011-05-10 18:27:06 +00001736/// \param DeclLoc The location of the declaration itself.
1737///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001738/// \param SS the scope specifier that will be matched to the given template
1739/// parameter lists. This scope specifier precedes a qualified name that is
1740/// being declared.
1741///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001742/// \param TemplateId The template-id following the scope specifier, if there
1743/// is one. Used to check for a missing 'template<>'.
1744///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001745/// \param ParamLists the template parameter lists, from the outermost to the
1746/// innermost template parameter lists.
1747///
John McCalle820e5e2010-04-13 20:37:33 +00001748/// \param IsFriend Whether to apply the slightly different rules for
1749/// matching template parameters to scope specifiers in friend
1750/// declarations.
1751///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001752/// \param IsExplicitSpecialization will be set true if the entity being
1753/// declared is an explicit specialization, false otherwise.
1754///
Mike Stump11289f42009-09-09 15:08:12 +00001755/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001756/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001757/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001758/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001759/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001760/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001761TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1762 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001763 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001764 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1765 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001766 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001767 Invalid = false;
1768
1769 // The sequence of nested types to which we will match up the template
1770 // parameter lists. We first build this list by starting with the type named
1771 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001772 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001773 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001774 if (SS.getScopeRep()) {
1775 if (CXXRecordDecl *Record
1776 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1777 T = Context.getTypeDeclType(Record);
1778 else
1779 T = QualType(SS.getScopeRep()->getAsType(), 0);
1780 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001781
1782 // If we found an explicit specialization that prevents us from needing
1783 // 'template<>' headers, this will be set to the location of that
1784 // explicit specialization.
1785 SourceLocation ExplicitSpecLoc;
1786
1787 while (!T.isNull()) {
1788 NestedTypes.push_back(T);
1789
1790 // Retrieve the parent of a record type.
1791 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1792 // If this type is an explicit specialization, we're done.
1793 if (ClassTemplateSpecializationDecl *Spec
1794 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1795 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1796 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1797 ExplicitSpecLoc = Spec->getLocation();
1798 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001799 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001800 } else if (Record->getTemplateSpecializationKind()
1801 == TSK_ExplicitSpecialization) {
1802 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001803 break;
1804 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001805
1806 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1807 T = Context.getTypeDeclType(Parent);
1808 else
1809 T = QualType();
1810 continue;
1811 }
1812
1813 if (const TemplateSpecializationType *TST
1814 = T->getAs<TemplateSpecializationType>()) {
1815 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1816 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1817 T = Context.getTypeDeclType(Parent);
1818 else
1819 T = QualType();
1820 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001821 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001822 }
1823
1824 // Look one step prior in a dependent template specialization type.
1825 if (const DependentTemplateSpecializationType *DependentTST
1826 = T->getAs<DependentTemplateSpecializationType>()) {
1827 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1828 T = QualType(NNS->getAsType(), 0);
1829 else
1830 T = QualType();
1831 continue;
1832 }
1833
1834 // Look one step prior in a dependent name type.
1835 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1836 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1837 T = QualType(NNS->getAsType(), 0);
1838 else
1839 T = QualType();
1840 continue;
1841 }
1842
1843 // Retrieve the parent of an enumeration type.
1844 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1845 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1846 // check here.
1847 EnumDecl *Enum = EnumT->getDecl();
1848
1849 // Get to the parent type.
1850 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1851 T = Context.getTypeDeclType(Parent);
1852 else
1853 T = QualType();
1854 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001855 }
Mike Stump11289f42009-09-09 15:08:12 +00001856
Douglas Gregor972fe532011-05-10 18:27:06 +00001857 T = QualType();
1858 }
1859 // Reverse the nested types list, since we want to traverse from the outermost
1860 // to the innermost while checking template-parameter-lists.
1861 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001862
Douglas Gregor972fe532011-05-10 18:27:06 +00001863 // C++0x [temp.expl.spec]p17:
1864 // A member or a member template may be nested within many
1865 // enclosing class templates. In an explicit specialization for
1866 // such a member, the member declaration shall be preceded by a
1867 // template<> for each enclosing class template that is
1868 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001869 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001870
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001871 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001872 if (SawNonEmptyTemplateParameterList) {
1873 Diag(DeclLoc, diag::err_specialize_member_of_template)
1874 << !Recovery << Range;
1875 Invalid = true;
1876 IsExplicitSpecialization = false;
1877 return true;
1878 }
1879
1880 return false;
1881 };
1882
1883 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1884 // Check that we can have an explicit specialization here.
1885 if (CheckExplicitSpecialization(Range, true))
1886 return true;
1887
1888 // We don't have a template header, but we should.
1889 SourceLocation ExpectedTemplateLoc;
1890 if (!ParamLists.empty())
1891 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1892 else
1893 ExpectedTemplateLoc = DeclStartLoc;
1894
1895 Diag(DeclLoc, diag::err_template_spec_needs_header)
1896 << Range
1897 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1898 return false;
1899 };
1900
Douglas Gregor972fe532011-05-10 18:27:06 +00001901 unsigned ParamIdx = 0;
1902 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1903 ++TypeIdx) {
1904 T = NestedTypes[TypeIdx];
1905
1906 // Whether we expect a 'template<>' header.
1907 bool NeedEmptyTemplateHeader = false;
1908
1909 // Whether we expect a template header with parameters.
1910 bool NeedNonemptyTemplateHeader = false;
1911
1912 // For a dependent type, the set of template parameters that we
1913 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001914 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001915
Douglas Gregor373af9b2011-05-11 23:26:17 +00001916 // C++0x [temp.expl.spec]p15:
1917 // A member or a member template may be nested within many enclosing
1918 // class templates. In an explicit specialization for such a member, the
1919 // member declaration shall be preceded by a template<> for each
1920 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001921 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1922 if (ClassTemplatePartialSpecializationDecl *Partial
1923 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1924 ExpectedTemplateParams = Partial->getTemplateParameters();
1925 NeedNonemptyTemplateHeader = true;
1926 } else if (Record->isDependentType()) {
1927 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001928 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001929 ->getTemplateParameters();
1930 NeedNonemptyTemplateHeader = true;
1931 }
1932 } else if (ClassTemplateSpecializationDecl *Spec
1933 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1934 // C++0x [temp.expl.spec]p4:
1935 // Members of an explicitly specialized class template are defined
1936 // in the same manner as members of normal classes, and not using
1937 // the template<> syntax.
1938 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1939 NeedEmptyTemplateHeader = true;
1940 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001941 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001942 } else if (Record->getTemplateSpecializationKind()) {
1943 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001944 != TSK_ExplicitSpecialization &&
1945 TypeIdx == NumTypes - 1)
1946 IsExplicitSpecialization = true;
1947
1948 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001949 }
1950 } else if (const TemplateSpecializationType *TST
1951 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001952 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001953 ExpectedTemplateParams = Template->getTemplateParameters();
1954 NeedNonemptyTemplateHeader = true;
1955 }
1956 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1957 // FIXME: We actually could/should check the template arguments here
1958 // against the corresponding template parameter list.
1959 NeedNonemptyTemplateHeader = false;
1960 }
1961
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001962 // C++ [temp.expl.spec]p16:
1963 // In an explicit specialization declaration for a member of a class
1964 // template or a member template that ap- pears in namespace scope, the
1965 // member template and some of its enclosing class templates may remain
1966 // unspecialized, except that the declaration shall not explicitly
1967 // specialize a class member template if its en- closing class templates
1968 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001969 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001970 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001971 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1972 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001973 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001974 } else
1975 SawNonEmptyTemplateParameterList = true;
1976 }
1977
Douglas Gregor972fe532011-05-10 18:27:06 +00001978 if (NeedEmptyTemplateHeader) {
1979 // If we're on the last of the types, and we need a 'template<>' header
1980 // here, then it's an explicit specialization.
1981 if (TypeIdx == NumTypes - 1)
1982 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001983
1984 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001985 if (ParamLists[ParamIdx]->size() > 0) {
1986 // The header has template parameters when it shouldn't. Complain.
1987 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1988 diag::err_template_param_list_matches_nontemplate)
1989 << T
1990 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1991 ParamLists[ParamIdx]->getRAngleLoc())
1992 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1993 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001994 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001995 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001996
Douglas Gregor972fe532011-05-10 18:27:06 +00001997 // Consume this template header.
1998 ++ParamIdx;
1999 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002000 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002001
2002 if (!IsFriend)
2003 if (DiagnoseMissingExplicitSpecialization(
2004 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002005 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002006
Douglas Gregor972fe532011-05-10 18:27:06 +00002007 continue;
2008 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002009
Douglas Gregor972fe532011-05-10 18:27:06 +00002010 if (NeedNonemptyTemplateHeader) {
2011 // In friend declarations we can have template-ids which don't
2012 // depend on the corresponding template parameter lists. But
2013 // assume that empty parameter lists are supposed to match this
2014 // template-id.
2015 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002016 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002017 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002018 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002019 else
2020 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002021 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002022
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002023 if (ParamIdx < ParamLists.size()) {
2024 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002025 if (ExpectedTemplateParams &&
2026 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2027 ExpectedTemplateParams,
2028 true, TPL_TemplateMatch))
2029 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002030
Douglas Gregor972fe532011-05-10 18:27:06 +00002031 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002032 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002033 TPC_ClassTemplateMember))
2034 Invalid = true;
2035
2036 ++ParamIdx;
2037 continue;
2038 }
2039
2040 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2041 << T
2042 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2043 Invalid = true;
2044 continue;
2045 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002046 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002047
Douglas Gregord8d297c2009-07-21 23:53:31 +00002048 // If there were at least as many template-ids as there were template
2049 // parameter lists, then there are no template parameter lists remaining for
2050 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002051 if (ParamIdx >= ParamLists.size()) {
2052 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002053 // We don't have a template header for the declaration itself, but we
2054 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002055 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00002056 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2057 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002058
2059 // Fabricate an empty template parameter list for the invented header.
2060 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002061 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002062 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002063 }
2064
Craig Topperc3ec1492014-05-26 06:22:03 +00002065 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002066 }
Mike Stump11289f42009-09-09 15:08:12 +00002067
Douglas Gregord8d297c2009-07-21 23:53:31 +00002068 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002069 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002070 bool HasAnyExplicitSpecHeader = false;
2071 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002072 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002073 if (ParamLists[I]->size() == 0)
2074 HasAnyExplicitSpecHeader = true;
2075 else
2076 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002077 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002078
Douglas Gregor972fe532011-05-10 18:27:06 +00002079 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002080 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2081 : diag::err_template_spec_extra_headers)
2082 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2083 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002084
2085 // If there was a specialization somewhere, such that 'template<>' is
2086 // not required, and there were any 'template<>' headers, note where the
2087 // specialization occurred.
2088 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2089 Diag(ExplicitSpecLoc,
2090 diag::note_explicit_template_spec_does_not_need_header)
2091 << NestedTypes.back();
2092
2093 // We have a template parameter list with no corresponding scope, which
2094 // means that the resulting template declaration can't be instantiated
2095 // properly (we'll end up with dependent nodes when we shouldn't).
2096 if (!AllExplicitSpecHeaders)
2097 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002098 }
Mike Stump11289f42009-09-09 15:08:12 +00002099
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002100 // C++ [temp.expl.spec]p16:
2101 // In an explicit specialization declaration for a member of a class
2102 // template or a member template that ap- pears in namespace scope, the
2103 // member template and some of its enclosing class templates may remain
2104 // unspecialized, except that the declaration shall not explicitly
2105 // specialize a class member template if its en- closing class templates
2106 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002107 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002108 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2109 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002110 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002111
Douglas Gregord8d297c2009-07-21 23:53:31 +00002112 // Return the last template parameter list, which corresponds to the
2113 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002114 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002115}
2116
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002117void Sema::NoteAllFoundTemplates(TemplateName Name) {
2118 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2119 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002120 << (isa<FunctionTemplateDecl>(Template)
2121 ? 0
2122 : isa<ClassTemplateDecl>(Template)
2123 ? 1
2124 : isa<VarTemplateDecl>(Template)
2125 ? 2
2126 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2127 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002128 return;
2129 }
2130
2131 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2132 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2133 IEnd = OST->end();
2134 I != IEnd; ++I)
2135 Diag((*I)->getLocation(), diag::note_template_declared_here)
2136 << 0 << (*I)->getDeclName();
2137
2138 return;
2139 }
2140}
2141
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002142static QualType
2143checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2144 const SmallVectorImpl<TemplateArgument> &Converted,
2145 SourceLocation TemplateLoc,
2146 TemplateArgumentListInfo &TemplateArgs) {
2147 ASTContext &Context = SemaRef.getASTContext();
2148 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002149 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002150 // Specializations of __make_integer_seq<S, T, N> are treated like
2151 // S<T, 0, ..., N-1>.
2152
2153 // C++14 [inteseq.intseq]p1:
2154 // T shall be an integer type.
2155 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2156 SemaRef.Diag(TemplateArgs[1].getLocation(),
2157 diag::err_integer_sequence_integral_element_type);
2158 return QualType();
2159 }
2160
2161 // C++14 [inteseq.make]p1:
2162 // If N is negative the program is ill-formed.
2163 TemplateArgument NumArgsArg = Converted[2];
2164 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2165 if (NumArgs < 0) {
2166 SemaRef.Diag(TemplateArgs[2].getLocation(),
2167 diag::err_integer_sequence_negative_length);
2168 return QualType();
2169 }
2170
2171 QualType ArgTy = NumArgsArg.getIntegralType();
2172 TemplateArgumentListInfo SyntheticTemplateArgs;
2173 // The type argument gets reused as the first template argument in the
2174 // synthetic template argument list.
2175 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2176 // Expand N into 0 ... N-1.
2177 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2178 I < NumArgs; ++I) {
2179 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002180 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2181 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002182 }
2183 // The first template argument will be reused as the template decl that
2184 // our synthetic template arguments will be applied to.
2185 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2186 TemplateLoc, SyntheticTemplateArgs);
2187 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002188
2189 case BTK__type_pack_element:
2190 // Specializations of
2191 // __type_pack_element<Index, T_1, ..., T_N>
2192 // are treated like T_Index.
2193 assert(Converted.size() == 2 &&
2194 "__type_pack_element should be given an index and a parameter pack");
2195
2196 // If the Index is out of bounds, the program is ill-formed.
2197 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2198 llvm::APSInt Index = IndexArg.getAsIntegral();
2199 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2200 "type std::size_t, and hence be non-negative");
2201 if (Index >= Ts.pack_size()) {
2202 SemaRef.Diag(TemplateArgs[0].getLocation(),
2203 diag::err_type_pack_element_out_of_bounds);
2204 return QualType();
2205 }
2206
2207 // We simply return the type at index `Index`.
2208 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2209 return Nth->getAsType();
2210 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002211 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2212}
2213
Douglas Gregordc572a32009-03-30 22:58:21 +00002214QualType Sema::CheckTemplateIdType(TemplateName Name,
2215 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002216 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002217 DependentTemplateName *DTN
2218 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002219 if (DTN && DTN->isIdentifier())
2220 // When building a template-id where the template-name is dependent,
2221 // assume the template is a type template. Either our assumption is
2222 // correct, or the code is ill-formed and will be diagnosed when the
2223 // dependent name is substituted.
2224 return Context.getDependentTemplateSpecializationType(ETK_None,
2225 DTN->getQualifier(),
2226 DTN->getIdentifier(),
2227 TemplateArgs);
2228
Douglas Gregordc572a32009-03-30 22:58:21 +00002229 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002230 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2231 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002232 // We might have a substituted template template parameter pack. If so,
2233 // build a template specialization type for it.
2234 if (Name.getAsSubstTemplateTemplateParmPack())
2235 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002236
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002237 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2238 << Name;
2239 NoteAllFoundTemplates(Name);
2240 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002241 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002242
Douglas Gregorc40290e2009-03-09 23:48:35 +00002243 // Check that the template argument list is well-formed for this
2244 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002245 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002246 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002247 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002248 return QualType();
2249
Douglas Gregorc40290e2009-03-09 23:48:35 +00002250 QualType CanonType;
2251
Douglas Gregor678d76c2011-07-01 01:22:09 +00002252 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002253 if (TypeAliasTemplateDecl *AliasTemplate =
2254 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002255 // Find the canonical type for this type alias template specialization.
2256 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2257 if (Pattern->isInvalidDecl())
2258 return QualType();
2259
2260 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002261 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002262
2263 // Only substitute for the innermost template argument list.
2264 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002265 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002266 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2267 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002268 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002269
Richard Smith802c4b72012-08-23 06:16:52 +00002270 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002271 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002272 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002273 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002274
Richard Smith3f1b5d02011-05-05 21:57:07 +00002275 CanonType = SubstType(Pattern->getUnderlyingType(),
2276 TemplateArgLists, AliasTemplate->getLocation(),
2277 AliasTemplate->getDeclName());
2278 if (CanonType.isNull())
2279 return QualType();
2280 } else if (Name.isDependent() ||
2281 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002282 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002283 // This class template specialization is a dependent
2284 // type. Therefore, its canonical type is another class template
2285 // specialization type that contains all of the converted
2286 // arguments in canonical form. This ensures that, e.g., A<T> and
2287 // A<T, T> have identical types when A is declared as:
2288 //
2289 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002290 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002291 CanonType = Context.getTemplateSpecializationType(CanonName,
David Majnemer6fbeee32016-07-07 04:43:07 +00002292 Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002293
Douglas Gregora8e02e72009-07-28 23:00:59 +00002294 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002295 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002296 // In the future, we need to teach getTemplateSpecializationType to only
2297 // build the canonical type and return that to us.
2298 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002299
2300 // This might work out to be a current instantiation, in which
2301 // case the canonical type needs to be the InjectedClassNameType.
2302 //
2303 // TODO: in theory this could be a simple hashtable lookup; most
2304 // changes to CurContext don't change the set of current
2305 // instantiations.
2306 if (isa<ClassTemplateDecl>(Template)) {
2307 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2308 // If we get out to a namespace, we're done.
2309 if (Ctx->isFileContext()) break;
2310
2311 // If this isn't a record, keep looking.
2312 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2313 if (!Record) continue;
2314
2315 // Look for one of the two cases with InjectedClassNameTypes
2316 // and check whether it's the same template.
2317 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2318 !Record->getDescribedClassTemplate())
2319 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002320
John McCall2408e322010-04-27 00:57:59 +00002321 // Fetch the injected class name type and check whether its
2322 // injected type is equal to the type we just built.
2323 QualType ICNT = Context.getTypeDeclType(Record);
2324 QualType Injected = cast<InjectedClassNameType>(ICNT)
2325 ->getInjectedSpecializationType();
2326
2327 if (CanonType != Injected->getCanonicalTypeInternal())
2328 continue;
2329
2330 // If so, the canonical type of this TST is the injected
2331 // class name type of the record we just found.
2332 assert(ICNT.isCanonical());
2333 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002334 break;
2335 }
2336 }
Mike Stump11289f42009-09-09 15:08:12 +00002337 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002338 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002339 // Find the class template specialization declaration that
2340 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002341 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002342 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002343 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002344 if (!Decl) {
2345 // This is the first time we have referenced this class template
2346 // specialization. Create the canonical declaration and add it to
2347 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002348 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002349 ClassTemplate->getTemplatedDecl()->getTagKind(),
2350 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002351 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002352 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002353 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00002354 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002355 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002356 if (ClassTemplate->isOutOfLine())
2357 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002358 }
2359
Chandler Carruth2acfb222013-09-27 22:14:40 +00002360 // Diagnose uses of this specialization.
2361 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2362
Douglas Gregorc40290e2009-03-09 23:48:35 +00002363 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002364 assert(isa<RecordType>(CanonType) &&
2365 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002366 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2367 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2368 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002369 }
Mike Stump11289f42009-09-09 15:08:12 +00002370
Douglas Gregorc40290e2009-03-09 23:48:35 +00002371 // Build the fully-sugared type for this class template
2372 // specialization, which refers back to the class template
2373 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002374 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002375}
2376
John McCallfaf5fb42010-08-26 23:41:50 +00002377TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002378Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002379 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002380 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002381 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002382 SourceLocation RAngleLoc,
2383 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002384 if (SS.isInvalid())
2385 return true;
2386
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002387 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002388
Douglas Gregorc40290e2009-03-09 23:48:35 +00002389 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002390 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002391 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002392
Douglas Gregor5a064722011-02-28 17:23:35 +00002393 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002394 QualType T
2395 = Context.getDependentTemplateSpecializationType(ETK_None,
2396 DTN->getQualifier(),
2397 DTN->getIdentifier(),
2398 TemplateArgs);
2399 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002400 TypeLocBuilder TLB;
2401 DependentTemplateSpecializationTypeLoc SpecTL
2402 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002403 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2404 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002405 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002406 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002407 SpecTL.setLAngleLoc(LAngleLoc);
2408 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002409 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2410 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2411 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2412 }
2413
John McCall6b51f282009-11-23 01:53:49 +00002414 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002415
2416 if (Result.isNull())
2417 return true;
2418
Douglas Gregore7c20652011-03-02 00:47:37 +00002419 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002420 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002421 TemplateSpecializationTypeLoc SpecTL
2422 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002423 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002424 SpecTL.setTemplateNameLoc(TemplateLoc);
2425 SpecTL.setLAngleLoc(LAngleLoc);
2426 SpecTL.setRAngleLoc(RAngleLoc);
2427 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2428 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002429
Abramo Bagnara4244b432012-01-27 08:46:19 +00002430 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2431 // constructor or destructor name (in such a case, the scope specifier
2432 // will be attached to the enclosing Decl or Expr node).
2433 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002434 // Create an elaborated-type-specifier containing the nested-name-specifier.
2435 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2436 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002437 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002438 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2439 }
2440
2441 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002442}
John McCall06f6fe8d2009-09-04 01:14:41 +00002443
Douglas Gregore7c20652011-03-02 00:47:37 +00002444TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002445 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002446 SourceLocation TagLoc,
2447 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002448 SourceLocation TemplateKWLoc,
2449 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002450 SourceLocation TemplateLoc,
2451 SourceLocation LAngleLoc,
2452 ASTTemplateArgsPtr TemplateArgsIn,
2453 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002454 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002455
2456 // Translate the parser's template argument list in our AST format.
2457 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2458 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2459
2460 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002461 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002462 ElaboratedTypeKeyword Keyword
2463 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002464
Douglas Gregore7c20652011-03-02 00:47:37 +00002465 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2466 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2467 DTN->getQualifier(),
2468 DTN->getIdentifier(),
2469 TemplateArgs);
2470
2471 // Build type-source information.
2472 TypeLocBuilder TLB;
2473 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002474 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2475 SpecTL.setElaboratedKeywordLoc(TagLoc);
2476 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002477 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002478 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002479 SpecTL.setLAngleLoc(LAngleLoc);
2480 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002481 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2482 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2483 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2484 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002485
2486 if (TypeAliasTemplateDecl *TAT =
2487 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2488 // C++0x [dcl.type.elab]p2:
2489 // If the identifier resolves to a typedef-name or the simple-template-id
2490 // resolves to an alias template specialization, the
2491 // elaborated-type-specifier is ill-formed.
Reid Klecknerf33bfcb02016-10-03 18:34:23 +00002492 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << NTK_TypeAliasTemplate;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002493 Diag(TAT->getLocation(), diag::note_declared_at);
2494 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002495
2496 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2497 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002498 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002499
2500 // Check the tag kind
2501 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002502 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002503
John McCalld8fe9af2009-09-08 17:47:29 +00002504 IdentifierInfo *Id = D->getIdentifier();
2505 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002506
Richard Trieucaa33d32011-06-10 03:11:26 +00002507 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002508 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002509 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002510 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002511 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002512 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002513 }
2514 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002515
Douglas Gregore7c20652011-03-02 00:47:37 +00002516 // Provide source-location information for the template specialization.
2517 TypeLocBuilder TLB;
2518 TemplateSpecializationTypeLoc SpecTL
2519 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002520 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002521 SpecTL.setTemplateNameLoc(TemplateLoc);
2522 SpecTL.setLAngleLoc(LAngleLoc);
2523 SpecTL.setRAngleLoc(RAngleLoc);
2524 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2525 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002526
Douglas Gregore7c20652011-03-02 00:47:37 +00002527 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002528 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002529 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2530 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002531 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002532 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2533 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002534}
2535
Larisse Voufo39a1e502013-08-06 01:03:05 +00002536static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002537 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2538 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002539
2540static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2541 NamedDecl *PrevDecl,
2542 SourceLocation Loc,
2543 bool IsPartialSpecialization);
2544
2545static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002546
Richard Smith300e0c32013-09-24 04:49:23 +00002547static bool isTemplateArgumentTemplateParameter(
2548 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2549 switch (Arg.getKind()) {
2550 case TemplateArgument::Null:
2551 case TemplateArgument::NullPtr:
2552 case TemplateArgument::Integral:
2553 case TemplateArgument::Declaration:
2554 case TemplateArgument::Pack:
2555 case TemplateArgument::TemplateExpansion:
2556 return false;
2557
2558 case TemplateArgument::Type: {
2559 QualType Type = Arg.getAsType();
2560 const TemplateTypeParmType *TPT =
2561 Arg.getAsType()->getAs<TemplateTypeParmType>();
2562 return TPT && !Type.hasQualifiers() &&
2563 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2564 }
2565
2566 case TemplateArgument::Expression: {
2567 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2568 if (!DRE || !DRE->getDecl())
2569 return false;
2570 const NonTypeTemplateParmDecl *NTTP =
2571 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2572 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2573 }
2574
2575 case TemplateArgument::Template:
2576 const TemplateTemplateParmDecl *TTP =
2577 dyn_cast_or_null<TemplateTemplateParmDecl>(
2578 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2579 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2580 }
2581 llvm_unreachable("unexpected kind of template argument");
2582}
2583
2584static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2585 ArrayRef<TemplateArgument> Args) {
2586 if (Params->size() != Args.size())
2587 return false;
2588
2589 unsigned Depth = Params->getDepth();
2590
2591 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2592 TemplateArgument Arg = Args[I];
2593
2594 // If the parameter is a pack expansion, the argument must be a pack
2595 // whose only element is a pack expansion.
2596 if (Params->getParam(I)->isParameterPack()) {
2597 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2598 !Arg.pack_begin()->isPackExpansion())
2599 return false;
2600 Arg = Arg.pack_begin()->getPackExpansionPattern();
2601 }
2602
2603 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2604 return false;
2605 }
2606
2607 return true;
2608}
2609
Richard Smith4b55a9c2014-04-17 03:29:33 +00002610/// Convert the parser's template argument list representation into our form.
2611static TemplateArgumentListInfo
2612makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2613 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2614 TemplateId.RAngleLoc);
2615 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2616 TemplateId.NumArgs);
2617 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2618 return TemplateArgs;
2619}
2620
Larisse Voufo39a1e502013-08-06 01:03:05 +00002621DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002622 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002623 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002624 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002625 // D must be variable template id.
2626 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2627 "Variable template specialization is declared with a template it.");
2628
2629 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002630 TemplateArgumentListInfo TemplateArgs =
2631 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002632 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2633 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2634 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002635
Richard Smithbeef3452014-01-16 23:39:20 +00002636 TemplateName Name = TemplateId->Template.get();
2637
2638 // The template-id must name a variable template.
2639 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002640 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2641 if (!VarTemplate) {
2642 NamedDecl *FnTemplate;
2643 if (auto *OTS = Name.getAsOverloadedTemplate())
2644 FnTemplate = *OTS->begin();
2645 else
2646 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2647 if (FnTemplate)
2648 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2649 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002650 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2651 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002652 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002653
2654 // Check for unexpanded parameter packs in any of the template arguments.
2655 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2656 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2657 UPPC_PartialSpecialization))
2658 return true;
2659
2660 // Check that the template argument list is well-formed for this
2661 // template.
2662 SmallVector<TemplateArgument, 4> Converted;
2663 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2664 false, Converted))
2665 return true;
2666
Larisse Voufo39a1e502013-08-06 01:03:05 +00002667 // Find the variable template (partial) specialization declaration that
2668 // corresponds to these arguments.
2669 if (IsPartialSpecialization) {
2670 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002671 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2672 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002673 return true;
2674
2675 bool InstantiationDependent;
2676 if (!Name.isDependent() &&
2677 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00002678 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00002679 InstantiationDependent)) {
2680 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2681 << VarTemplate->getDeclName();
2682 IsPartialSpecialization = false;
2683 }
Richard Smith300e0c32013-09-24 04:49:23 +00002684
2685 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2686 Converted)) {
2687 // C++ [temp.class.spec]p9b3:
2688 //
2689 // -- The argument list of the specialization shall not be identical
2690 // to the implicit argument list of the primary template.
2691 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2692 << /*variable template*/ 1
2693 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2694 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2695 // FIXME: Recover from this by treating the declaration as a redeclaration
2696 // of the primary template.
2697 return true;
2698 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002699 }
2700
Craig Topperc3ec1492014-05-26 06:22:03 +00002701 void *InsertPos = nullptr;
2702 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002703
2704 if (IsPartialSpecialization)
2705 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002706 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002707 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002708 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002709
Craig Topperc3ec1492014-05-26 06:22:03 +00002710 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002711
2712 // Check whether we can declare a variable template specialization in
2713 // the current scope.
2714 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2715 TemplateNameLoc,
2716 IsPartialSpecialization))
2717 return true;
2718
2719 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2720 // Since the only prior variable template specialization with these
2721 // arguments was referenced but not declared, reuse that
2722 // declaration node as our own, updating its source location and
2723 // the list of outer template parameters to reflect our new declaration.
2724 Specialization = PrevDecl;
2725 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002726 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002727 } else if (IsPartialSpecialization) {
2728 // Create a new class template partial specialization declaration node.
2729 VarTemplatePartialSpecializationDecl *PrevPartial =
2730 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002731 VarTemplatePartialSpecializationDecl *Partial =
2732 VarTemplatePartialSpecializationDecl::Create(
2733 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2734 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00002735 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002736
2737 if (!PrevPartial)
2738 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2739 Specialization = Partial;
2740
2741 // If we are providing an explicit specialization of a member variable
2742 // template specialization, make a note of that.
2743 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002744 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002745
2746 // Check that all of the template parameters of the variable template
2747 // partial specialization are deducible from the template
2748 // arguments. If not, this variable template partial specialization
2749 // will never be used.
2750 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2751 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2752 TemplateParams->getDepth(), DeducibleParams);
2753
2754 if (!DeducibleParams.all()) {
2755 unsigned NumNonDeducible =
2756 DeducibleParams.size() - DeducibleParams.count();
2757 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002758 << /*variable template*/ 1 << (NumNonDeducible > 1)
2759 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002760 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2761 if (!DeducibleParams[I]) {
2762 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2763 if (Param->getDeclName())
2764 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2765 << Param->getDeclName();
2766 else
2767 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002768 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002769 }
2770 }
2771 }
2772 } else {
2773 // Create a new class template specialization declaration node for
2774 // this explicit specialization or friend declaration.
2775 Specialization = VarTemplateSpecializationDecl::Create(
2776 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00002777 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002778 Specialization->setTemplateArgsInfo(TemplateArgs);
2779
2780 if (!PrevDecl)
2781 VarTemplate->AddSpecialization(Specialization, InsertPos);
2782 }
2783
2784 // C++ [temp.expl.spec]p6:
2785 // If a template, a member template or the member of a class template is
2786 // explicitly specialized then that specialization shall be declared
2787 // before the first use of that specialization that would cause an implicit
2788 // instantiation to take place, in every translation unit in which such a
2789 // use occurs; no diagnostic is required.
2790 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2791 bool Okay = false;
2792 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2793 // Is there any previous explicit specialization declaration?
2794 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2795 Okay = true;
2796 break;
2797 }
2798 }
2799
2800 if (!Okay) {
2801 SourceRange Range(TemplateNameLoc, RAngleLoc);
2802 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2803 << Name << Range;
2804
2805 Diag(PrevDecl->getPointOfInstantiation(),
2806 diag::note_instantiation_required_here)
2807 << (PrevDecl->getTemplateSpecializationKind() !=
2808 TSK_ImplicitInstantiation);
2809 return true;
2810 }
2811 }
2812
2813 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2814 Specialization->setLexicalDeclContext(CurContext);
2815
2816 // Add the specialization into its lexical context, so that it can
2817 // be seen when iterating through the list of declarations in that
2818 // context. However, specializations are not found by name lookup.
2819 CurContext->addDecl(Specialization);
2820
2821 // Note that this is an explicit specialization.
2822 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2823
2824 if (PrevDecl) {
2825 // Check that this isn't a redefinition of this specialization,
2826 // merging with previous declarations.
2827 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2828 ForRedeclaration);
2829 PrevSpec.addDecl(PrevDecl);
2830 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002831 } else if (Specialization->isStaticDataMember() &&
2832 Specialization->isOutOfLine()) {
2833 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002834 }
2835
2836 // Link instantiations of static data members back to the template from
2837 // which they were instantiated.
2838 if (Specialization->isStaticDataMember())
2839 Specialization->setInstantiationOfStaticDataMember(
2840 VarTemplate->getTemplatedDecl(),
2841 Specialization->getSpecializationKind());
2842
2843 return Specialization;
2844}
2845
2846namespace {
2847/// \brief A partial specialization whose template arguments have matched
2848/// a given template-id.
2849struct PartialSpecMatchResult {
2850 VarTemplatePartialSpecializationDecl *Partial;
2851 TemplateArgumentList *Args;
2852};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002853} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00002854
2855DeclResult
2856Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2857 SourceLocation TemplateNameLoc,
2858 const TemplateArgumentListInfo &TemplateArgs) {
2859 assert(Template && "A variable template id without template?");
2860
2861 // Check that the template argument list is well-formed for this template.
2862 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002863 if (CheckTemplateArgumentList(
2864 Template, TemplateNameLoc,
2865 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002866 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002867 return true;
2868
2869 // Find the variable template specialization declaration that
2870 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002871 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002872 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00002873 Converted, InsertPos)) {
2874 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002875 // If we already have a variable template specialization, return it.
2876 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00002877 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002878
2879 // This is the first time we have referenced this variable template
2880 // specialization. Create the canonical declaration and add it to
2881 // the set of specializations, based on the closest partial specialization
2882 // that it represents. That is,
2883 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2884 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002885 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002886 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2887 bool AmbiguousPartialSpec = false;
2888 typedef PartialSpecMatchResult MatchResult;
2889 SmallVector<MatchResult, 4> Matched;
2890 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002891 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2892 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002893
2894 // 1. Attempt to find the closest partial specialization that this
2895 // specializes, if any.
2896 // If any of the template arguments is dependent, then this is probably
2897 // a placeholder for an incomplete declarative context; which must be
2898 // complete by instantiation time. Thus, do not search through the partial
2899 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002900 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2901 // Perhaps better after unification of DeduceTemplateArguments() and
2902 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002903 bool InstantiationDependent = false;
2904 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2905 TemplateArgs, InstantiationDependent)) {
2906
2907 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2908 Template->getPartialSpecializations(PartialSpecs);
2909
2910 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2911 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2912 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2913
2914 if (TemplateDeductionResult Result =
2915 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2916 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002917 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002918 FailedCandidates.addCandidate().set(
2919 DeclAccessPair::make(Template, AS_public), Partial,
2920 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002921 (void)Result;
2922 } else {
2923 Matched.push_back(PartialSpecMatchResult());
2924 Matched.back().Partial = Partial;
2925 Matched.back().Args = Info.take();
2926 }
2927 }
2928
Larisse Voufo39a1e502013-08-06 01:03:05 +00002929 if (Matched.size() >= 1) {
2930 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2931 if (Matched.size() == 1) {
2932 // -- If exactly one matching specialization is found, the
2933 // instantiation is generated from that specialization.
2934 // We don't need to do anything for this.
2935 } else {
2936 // -- If more than one matching specialization is found, the
2937 // partial order rules (14.5.4.2) are used to determine
2938 // whether one of the specializations is more specialized
2939 // than the others. If none of the specializations is more
2940 // specialized than all of the other matching
2941 // specializations, then the use of the variable template is
2942 // ambiguous and the program is ill-formed.
2943 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2944 PEnd = Matched.end();
2945 P != PEnd; ++P) {
2946 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2947 PointOfInstantiation) ==
2948 P->Partial)
2949 Best = P;
2950 }
2951
2952 // Determine if the best partial specialization is more specialized than
2953 // the others.
2954 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2955 PEnd = Matched.end();
2956 P != PEnd; ++P) {
2957 if (P != Best && getMoreSpecializedPartialSpecialization(
2958 P->Partial, Best->Partial,
2959 PointOfInstantiation) != Best->Partial) {
2960 AmbiguousPartialSpec = true;
2961 break;
2962 }
2963 }
2964 }
2965
2966 // Instantiate using the best variable template partial specialization.
2967 InstantiationPattern = Best->Partial;
2968 InstantiationArgs = Best->Args;
2969 } else {
2970 // -- If no match is found, the instantiation is generated
2971 // from the primary template.
2972 // InstantiationPattern = Template->getTemplatedDecl();
2973 }
2974 }
2975
Larisse Voufo39a1e502013-08-06 01:03:05 +00002976 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00002977 // Note that we do not instantiate a definition until we see an odr-use
2978 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002979 // FIXME: LateAttrs et al.?
2980 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2981 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2982 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2983 if (!Decl)
2984 return true;
2985
2986 if (AmbiguousPartialSpec) {
2987 // Partial ordering did not produce a clear winner. Complain.
2988 Decl->setInvalidDecl();
2989 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2990 << Decl;
2991
2992 // Print the matching partial specializations.
2993 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2994 PEnd = Matched.end();
2995 P != PEnd; ++P)
2996 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2997 << getTemplateArgumentBindingsText(
2998 P->Partial->getTemplateParameters(), *P->Args);
2999 return true;
3000 }
3001
3002 if (VarTemplatePartialSpecializationDecl *D =
3003 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3004 Decl->setInstantiationOf(D, InstantiationArgs);
3005
Richard Smith6739a102016-05-05 00:56:12 +00003006 checkSpecializationVisibility(TemplateNameLoc, Decl);
3007
Larisse Voufo39a1e502013-08-06 01:03:05 +00003008 assert(Decl && "No variable template specialization?");
3009 return Decl;
3010}
3011
3012ExprResult
3013Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3014 const DeclarationNameInfo &NameInfo,
3015 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3016 const TemplateArgumentListInfo *TemplateArgs) {
3017
3018 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3019 *TemplateArgs);
3020 if (Decl.isInvalid())
3021 return ExprError();
3022
3023 VarDecl *Var = cast<VarDecl>(Decl.get());
3024 if (!Var->getTemplateSpecializationKind())
3025 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3026 NameInfo.getLoc());
3027
3028 // Build an ordinary singleton decl ref.
3029 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003030 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003031}
3032
John McCalldadc5752010-08-24 06:29:42 +00003033ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003034 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003035 LookupResult &R,
3036 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003037 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003038 // FIXME: Can we do any checking at this point? I guess we could check the
3039 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003040 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003041 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003042 // foo<int> could identify a single function unambiguously
3043 // This approach does NOT work, since f<int>(1);
3044 // gets resolved prior to resorting to overload resolution
3045 // i.e., template<class T> void f(double);
3046 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003047
3048 // These should be filtered out by our callers.
3049 assert(!R.empty() && "empty lookup results when building templateid");
3050 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3051
Larisse Voufo39a1e502013-08-06 01:03:05 +00003052 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003053 bool InstantiationDependent;
3054 if (R.getAsSingle<VarTemplateDecl>() &&
3055 !TemplateSpecializationType::anyDependentTemplateArguments(
3056 *TemplateArgs, InstantiationDependent)) {
3057 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3058 R.getAsSingle<VarTemplateDecl>(),
3059 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003060 }
3061
John McCall58cc69d2010-01-27 01:50:18 +00003062 // We don't want lookup warnings at this point.
3063 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003064
John McCalle66edc12009-11-24 19:00:30 +00003065 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003066 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003067 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003068 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003069 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003070 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003071 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003072
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003073 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003074}
3075
John McCalle66edc12009-11-24 19:00:30 +00003076// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003077ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003078Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003079 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003080 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003081 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003082
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003083 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003084 DeclContext *DC;
3085 if (!(DC = computeDeclContext(SS, false)) ||
3086 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003087 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003088 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003089
Douglas Gregor786123d2010-05-21 23:18:07 +00003090 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003091 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003092 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003093 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003094
John McCalle66edc12009-11-24 19:00:30 +00003095 if (R.isAmbiguous())
3096 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003097
John McCalle66edc12009-11-24 19:00:30 +00003098 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003099 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3100 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003101 return ExprError();
3102 }
3103
3104 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003105 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003106 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003107 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003108 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3109 return ExprError();
3110 }
3111
Abramo Bagnara7945c982012-01-27 09:46:47 +00003112 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003113}
3114
Douglas Gregorb67535d2009-03-31 00:43:58 +00003115/// \brief Form a dependent template name.
3116///
3117/// This action forms a dependent template name given the template
3118/// name and its (presumably dependent) scope specifier. For
3119/// example, given "MetaFun::template apply", the scope specifier \p
3120/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3121/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003122TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003123 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003124 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003125 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003126 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003127 bool EnteringContext,
3128 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003129 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3130 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003131 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003132 diag::warn_cxx98_compat_template_outside_of_template :
3133 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003134 << FixItHint::CreateRemoval(TemplateKWLoc);
3135
Craig Topperc3ec1492014-05-26 06:22:03 +00003136 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003137 if (SS.isSet())
3138 LookupCtx = computeDeclContext(SS, EnteringContext);
3139 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003140 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003141 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003142 // C++0x [temp.names]p5:
3143 // If a name prefixed by the keyword template is not the name of
3144 // a template, the program is ill-formed. [Note: the keyword
3145 // template may not be applied to non-template members of class
3146 // templates. -end note ] [ Note: as is the case with the
3147 // typename prefix, the template prefix is allowed in cases
3148 // where it is not strictly necessary; i.e., when the
3149 // nested-name-specifier or the expression on the left of the ->
3150 // or . is not dependent on a template-parameter, or the use
3151 // does not appear in the scope of a template. -end note]
3152 //
3153 // Note: C++03 was more strict here, because it banned the use of
3154 // the "template" keyword prior to a template-name that was not a
3155 // dependent name. C++ DR468 relaxed this requirement (the
3156 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003157 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003158 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003159 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003160 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003161 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003162 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3163 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003164 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3165 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003166 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003167 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003168 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003169 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003170 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003171 << Name.getSourceRange()
3172 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003173 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003174 } else {
3175 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003176 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003177 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003178 }
3179
Aaron Ballman4a979672014-01-03 13:56:08 +00003180 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003181
Douglas Gregor3cf81312009-11-03 23:16:33 +00003182 switch (Name.getKind()) {
3183 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003184 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003185 Name.Identifier));
3186 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187
Douglas Gregor71395fa2009-11-04 00:56:37 +00003188 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003189 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003190 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003191 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003192
3193 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003194 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003195
Douglas Gregor3cf81312009-11-03 23:16:33 +00003196 default:
3197 break;
3198 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003199
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003200 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003201 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003202 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003203 << Name.getSourceRange()
3204 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003205 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003206}
3207
Mike Stump11289f42009-09-09 15:08:12 +00003208bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003209 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003210 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003211 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003212 QualType ArgType;
3213 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003214
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003215 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003216 switch(Arg.getKind()) {
3217 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003218 // C++ [temp.arg.type]p1:
3219 // A template-argument for a template-parameter which is a
3220 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003221 ArgType = Arg.getAsType();
3222 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003223 break;
3224 case TemplateArgument::Template: {
3225 // We have a template type parameter but the template argument
3226 // is a template without any arguments.
3227 SourceRange SR = AL.getSourceRange();
3228 TemplateName Name = Arg.getAsTemplate();
3229 Diag(SR.getBegin(), diag::err_template_missing_args)
3230 << Name << SR;
3231 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3232 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003233
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003234 return true;
3235 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003236 case TemplateArgument::Expression: {
3237 // We have a template type parameter but the template argument is an
3238 // expression; see if maybe it is missing the "typename" keyword.
3239 CXXScopeSpec SS;
3240 DeclarationNameInfo NameInfo;
3241
3242 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3243 SS.Adopt(ArgExpr->getQualifierLoc());
3244 NameInfo = ArgExpr->getNameInfo();
3245 } else if (DependentScopeDeclRefExpr *ArgExpr =
3246 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3247 SS.Adopt(ArgExpr->getQualifierLoc());
3248 NameInfo = ArgExpr->getNameInfo();
3249 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3250 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003251 if (ArgExpr->isImplicitAccess()) {
3252 SS.Adopt(ArgExpr->getQualifierLoc());
3253 NameInfo = ArgExpr->getMemberNameInfo();
3254 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003255 }
3256
Reid Kleckner377c1592014-06-10 23:29:48 +00003257 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003258 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3259 LookupParsedName(Result, CurScope, &SS);
3260
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003261 if (Result.getAsSingle<TypeDecl>() ||
3262 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003263 LookupResult::NotFoundInCurrentInstantiation) {
3264 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003265 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003266 Diag(Loc, getLangOpts().MSVCCompat
3267 ? diag::ext_ms_template_type_arg_missing_typename
3268 : diag::err_template_arg_must_be_type_suggest)
3269 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003270 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003271
3272 // Recover by synthesizing a type using the location information that we
3273 // already have.
3274 ArgType =
3275 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3276 TypeLocBuilder TLB;
3277 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3278 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3279 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3280 TL.setNameLoc(NameInfo.getLoc());
3281 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3282
3283 // Overwrite our input TemplateArgumentLoc so that we can recover
3284 // properly.
3285 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3286 TemplateArgumentLocInfo(TSI));
3287
3288 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003289 }
3290 }
3291 // fallthrough
3292 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003293 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003294 // We have a template type parameter but the template argument
3295 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003296 SourceRange SR = AL.getSourceRange();
3297 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003298 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003299
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003300 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003301 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003302 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003303
Reid Kleckner377c1592014-06-10 23:29:48 +00003304 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003305 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003306
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003307 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003308 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003309
3310 // Objective-C ARC:
3311 // If an explicitly-specified template argument type is a lifetime type
3312 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003313 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003314 ArgType->isObjCLifetimeType() &&
3315 !ArgType.getObjCLifetime()) {
3316 Qualifiers Qs;
3317 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3318 ArgType = Context.getQualifiedType(ArgType, Qs);
3319 }
3320
3321 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003322 return false;
3323}
3324
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003325/// \brief Substitute template arguments into the default template argument for
3326/// the given template type parameter.
3327///
3328/// \param SemaRef the semantic analysis object for which we are performing
3329/// the substitution.
3330///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003331/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003332/// for.
3333///
3334/// \param TemplateLoc the location of the template name that started the
3335/// template-id we are checking.
3336///
3337/// \param RAngleLoc the location of the right angle bracket ('>') that
3338/// terminates the template-id.
3339///
3340/// \param Param the template template parameter whose default we are
3341/// substituting into.
3342///
3343/// \param Converted the list of template arguments provided for template
3344/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003345/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003346static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003347SubstDefaultTemplateArgument(Sema &SemaRef,
3348 TemplateDecl *Template,
3349 SourceLocation TemplateLoc,
3350 SourceLocation RAngleLoc,
3351 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003352 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003353 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003354
3355 // If the argument type is dependent, instantiate it now based
3356 // on the previously-computed template arguments.
3357 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003358 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003359 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003360 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003361 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003362 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003363
David Majnemer8b622692016-07-03 21:17:51 +00003364 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003365
3366 // Only substitute for the innermost template argument list.
3367 MultiLevelTemplateArgumentList TemplateArgLists;
3368 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3369 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3370 TemplateArgLists.addOuterTemplateArguments(None);
3371
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003372 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003373 ArgType =
3374 SemaRef.SubstType(ArgType, TemplateArgLists,
3375 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003376 }
3377
3378 return ArgType;
3379}
3380
3381/// \brief Substitute template arguments into the default template argument for
3382/// the given non-type template parameter.
3383///
3384/// \param SemaRef the semantic analysis object for which we are performing
3385/// the substitution.
3386///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003387/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003388/// for.
3389///
3390/// \param TemplateLoc the location of the template name that started the
3391/// template-id we are checking.
3392///
3393/// \param RAngleLoc the location of the right angle bracket ('>') that
3394/// terminates the template-id.
3395///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003396/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003397/// substituting into.
3398///
3399/// \param Converted the list of template arguments provided for template
3400/// parameters that precede \p Param in the template parameter list.
3401///
3402/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003403static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003404SubstDefaultTemplateArgument(Sema &SemaRef,
3405 TemplateDecl *Template,
3406 SourceLocation TemplateLoc,
3407 SourceLocation RAngleLoc,
3408 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003409 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003410 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003411 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003412 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003413 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003414 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003415
David Majnemer8b622692016-07-03 21:17:51 +00003416 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003417
3418 // Only substitute for the innermost template argument list.
3419 MultiLevelTemplateArgumentList TemplateArgLists;
3420 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3421 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3422 TemplateArgLists.addOuterTemplateArguments(None);
3423
Faisal Vali48401eb2015-11-19 19:20:17 +00003424 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3425 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003426 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003427}
3428
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003429/// \brief Substitute template arguments into the default template argument for
3430/// the given template template parameter.
3431///
3432/// \param SemaRef the semantic analysis object for which we are performing
3433/// the substitution.
3434///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003436/// for.
3437///
3438/// \param TemplateLoc the location of the template name that started the
3439/// template-id we are checking.
3440///
3441/// \param RAngleLoc the location of the right angle bracket ('>') that
3442/// terminates the template-id.
3443///
3444/// \param Param the template template parameter whose default we are
3445/// substituting into.
3446///
3447/// \param Converted the list of template arguments provided for template
3448/// parameters that precede \p Param in the template parameter list.
3449///
Douglas Gregordf846d12011-03-02 18:46:51 +00003450/// \param QualifierLoc Will be set to the nested-name-specifier (with
3451/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003452///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003453/// \returns the substituted template argument, or NULL if an error occurred.
3454static TemplateName
3455SubstDefaultTemplateArgument(Sema &SemaRef,
3456 TemplateDecl *Template,
3457 SourceLocation TemplateLoc,
3458 SourceLocation RAngleLoc,
3459 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003460 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003461 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00003462 Sema::InstantiatingTemplate Inst(
3463 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
3464 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003465 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003466 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003467
David Majnemer8b622692016-07-03 21:17:51 +00003468 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003469
3470 // Only substitute for the innermost template argument list.
3471 MultiLevelTemplateArgumentList TemplateArgLists;
3472 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3473 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3474 TemplateArgLists.addOuterTemplateArguments(None);
3475
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003476 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003477 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003478 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003479 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003480 QualifierLoc =
3481 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003482 if (!QualifierLoc)
3483 return TemplateName();
3484 }
David Majnemer89189202013-08-28 23:48:32 +00003485
3486 return SemaRef.SubstTemplateName(
3487 QualifierLoc,
3488 Param->getDefaultArgument().getArgument().getAsTemplate(),
3489 Param->getDefaultArgument().getTemplateNameLoc(),
3490 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003491}
3492
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003493/// \brief If the given template parameter has a default template
3494/// argument, substitute into that default template argument and
3495/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003496TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003497Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3498 SourceLocation TemplateLoc,
3499 SourceLocation RAngleLoc,
3500 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003501 SmallVectorImpl<TemplateArgument>
3502 &Converted,
3503 bool &HasDefaultArg) {
3504 HasDefaultArg = false;
3505
3506 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003507 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003508 return TemplateArgumentLoc();
3509
Richard Smithc87b9382013-07-04 01:01:24 +00003510 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003511 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003512 TemplateLoc,
3513 RAngleLoc,
3514 TypeParm,
3515 Converted);
3516 if (DI)
3517 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3518
3519 return TemplateArgumentLoc();
3520 }
3521
3522 if (NonTypeTemplateParmDecl *NonTypeParm
3523 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003524 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003525 return TemplateArgumentLoc();
3526
Richard Smithc87b9382013-07-04 01:01:24 +00003527 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003528 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003529 TemplateLoc,
3530 RAngleLoc,
3531 NonTypeParm,
3532 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003533 if (Arg.isInvalid())
3534 return TemplateArgumentLoc();
3535
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003536 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003537 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3538 }
3539
3540 TemplateTemplateParmDecl *TempTempParm
3541 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003542 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003543 return TemplateArgumentLoc();
3544
Richard Smithc87b9382013-07-04 01:01:24 +00003545 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003546 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003547 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003548 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003549 RAngleLoc,
3550 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003551 Converted,
3552 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003553 if (TName.isNull())
3554 return TemplateArgumentLoc();
3555
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003556 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003557 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003558 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3559}
3560
Douglas Gregorda0fb532009-11-11 19:31:23 +00003561/// \brief Check that the given template argument corresponds to the given
3562/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003563///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003565/// checked.
3566///
Richard Trieu15b66532015-01-24 02:48:32 +00003567/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003568///
3569/// \param Template The template in which the template argument resides.
3570///
3571/// \param TemplateLoc The location of the template name for the template
3572/// whose argument list we're matching.
3573///
3574/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3575/// the template argument list.
3576///
3577/// \param ArgumentPackIndex The index into the argument pack where this
3578/// argument will be placed. Only valid if the parameter is a parameter pack.
3579///
3580/// \param Converted The checked, converted argument will be added to the
3581/// end of this small vector.
3582///
3583/// \param CTAK Describes how we arrived at this particular template argument:
3584/// explicitly written, deduced, etc.
3585///
3586/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003587bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003588 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003589 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003590 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003591 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003592 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003593 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003594 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003595 // Check template type parameters.
3596 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003597 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003598
Douglas Gregoreebed722009-11-11 19:41:09 +00003599 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003601 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003602 // with the template arguments we've seen thus far. But if the
3603 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003604 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003605 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3606 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003607
Peter Collingbourne01687632010-12-10 17:08:53 +00003608 if (NTTPType->isDependentType() &&
3609 !isa<TemplateTemplateParmDecl>(Template) &&
3610 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003611 // Do substitution on the type of the non-type template parameter.
3612 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003613 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003614 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003615 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003616 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003617
3618 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003619 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003620 NTTPType = SubstType(NTTPType,
3621 MultiLevelTemplateArgumentList(TemplateArgs),
3622 NTTP->getLocation(),
3623 NTTP->getDeclName());
3624 // If that worked, check the non-type template parameter type
3625 // for validity.
3626 if (!NTTPType.isNull())
3627 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3628 NTTP->getLocation());
3629 if (NTTPType.isNull())
3630 return true;
3631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003632
Douglas Gregorda0fb532009-11-11 19:31:23 +00003633 switch (Arg.getArgument().getKind()) {
3634 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003635 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003636
Douglas Gregorda0fb532009-11-11 19:31:23 +00003637 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003638 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003639 ExprResult Res =
3640 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3641 Result, CTAK);
3642 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003643 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003644
Richard Trieu15b66532015-01-24 02:48:32 +00003645 // If the resulting expression is new, then use it in place of the
3646 // old expression in the template argument.
3647 if (Res.get() != Arg.getArgument().getAsExpr()) {
3648 TemplateArgument TA(Res.get());
3649 Arg = TemplateArgumentLoc(TA, Res.get());
3650 }
3651
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003652 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003653 break;
3654 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655
Douglas Gregorda0fb532009-11-11 19:31:23 +00003656 case TemplateArgument::Declaration:
3657 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003658 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003659 // We've already checked this template argument, so just copy
3660 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003661 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003662 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663
Douglas Gregorda0fb532009-11-11 19:31:23 +00003664 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003665 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003666 // We were given a template template argument. It may not be ill-formed;
3667 // see below.
3668 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003669 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3670 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003671 // We have a template argument such as \c T::template X, which we
3672 // parsed as a template template argument. However, since we now
3673 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003674 // template name into an expression.
3675
3676 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3677 Arg.getTemplateNameLoc());
3678
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003679 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003680 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003681 // FIXME: the template-template arg was a DependentTemplateName,
3682 // so it was provided with a template keyword. However, its source
3683 // location is not stored in the template argument structure.
3684 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003685 ExprResult E = DependentScopeDeclRefExpr::Create(
3686 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3687 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003688
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003689 // If we parsed the template argument as a pack expansion, create a
3690 // pack expansion expression.
3691 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003692 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003693 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003694 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003695 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003696
Douglas Gregorda0fb532009-11-11 19:31:23 +00003697 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003698 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003699 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003700 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003701
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003702 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003703 break;
3704 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003705
Douglas Gregorda0fb532009-11-11 19:31:23 +00003706 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003707 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003708 // therefore cannot be a non-type template argument.
3709 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3710 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003711
Douglas Gregorda0fb532009-11-11 19:31:23 +00003712 Diag(Param->getLocation(), diag::note_template_param_here);
3713 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003714
Douglas Gregorda0fb532009-11-11 19:31:23 +00003715 case TemplateArgument::Type: {
3716 // We have a non-type template parameter but the template
3717 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003718
Douglas Gregorda0fb532009-11-11 19:31:23 +00003719 // C++ [temp.arg]p2:
3720 // In a template-argument, an ambiguity between a type-id and
3721 // an expression is resolved to a type-id, regardless of the
3722 // form of the corresponding template-parameter.
3723 //
3724 // We warn specifically about this case, since it can be rather
3725 // confusing for users.
3726 QualType T = Arg.getArgument().getAsType();
3727 SourceRange SR = Arg.getSourceRange();
3728 if (T->isFunctionType())
3729 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3730 else
3731 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3732 Diag(Param->getLocation(), diag::note_template_param_here);
3733 return true;
3734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003735
Douglas Gregorda0fb532009-11-11 19:31:23 +00003736 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003737 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003738 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
Douglas Gregorda0fb532009-11-11 19:31:23 +00003740 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003741 }
3742
3743
Douglas Gregorda0fb532009-11-11 19:31:23 +00003744 // Check template template parameters.
3745 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003746
Douglas Gregorda0fb532009-11-11 19:31:23 +00003747 // Substitute into the template parameter list of the template
3748 // template parameter, since previously-supplied template arguments
3749 // may appear within the template template parameter.
3750 {
3751 // Set up a template instantiation context.
3752 LocalInstantiationScope Scope(*this);
3753 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003754 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003755 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003756 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003757 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758
David Majnemer8b622692016-07-03 21:17:51 +00003759 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003760 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003762 MultiLevelTemplateArgumentList(TemplateArgs)));
3763 if (!TempParm)
3764 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003765 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003766
Douglas Gregorda0fb532009-11-11 19:31:23 +00003767 switch (Arg.getArgument().getKind()) {
3768 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003769 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770
Douglas Gregorda0fb532009-11-11 19:31:23 +00003771 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003772 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003773 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003774 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003775
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003776 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003777 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003778
Douglas Gregorda0fb532009-11-11 19:31:23 +00003779 case TemplateArgument::Expression:
3780 case TemplateArgument::Type:
3781 // We have a template template parameter but the template
3782 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003783 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003784 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003785 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003786
Douglas Gregorda0fb532009-11-11 19:31:23 +00003787 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003788 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003789 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003790 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003791 case TemplateArgument::NullPtr:
3792 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003793
Douglas Gregorda0fb532009-11-11 19:31:23 +00003794 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003795 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003797
Douglas Gregorda0fb532009-11-11 19:31:23 +00003798 return false;
3799}
3800
Douglas Gregor8e072612012-02-03 07:34:46 +00003801/// \brief Diagnose an arity mismatch in the
3802static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3803 SourceLocation TemplateLoc,
3804 TemplateArgumentListInfo &TemplateArgs) {
3805 TemplateParameterList *Params = Template->getTemplateParameters();
3806 unsigned NumParams = Params->size();
3807 unsigned NumArgs = TemplateArgs.size();
3808
3809 SourceRange Range;
3810 if (NumArgs > NumParams)
3811 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3812 TemplateArgs.getRAngleLoc());
3813 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3814 << (NumArgs > NumParams)
3815 << (isa<ClassTemplateDecl>(Template)? 0 :
3816 isa<FunctionTemplateDecl>(Template)? 1 :
3817 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3818 << Template << Range;
3819 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3820 << Params->getSourceRange();
3821 return true;
3822}
3823
Richard Smith1fde8ec2012-09-07 02:06:42 +00003824/// \brief Check whether the template parameter is a pack expansion, and if so,
3825/// determine the number of parameters produced by that expansion. For instance:
3826///
3827/// \code
3828/// template<typename ...Ts> struct A {
3829/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3830/// };
3831/// \endcode
3832///
3833/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3834/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003835static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003836 if (NonTypeTemplateParmDecl *NTTP
3837 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3838 if (NTTP->isExpandedParameterPack())
3839 return NTTP->getNumExpansionTypes();
3840 }
3841
3842 if (TemplateTemplateParmDecl *TTP
3843 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3844 if (TTP->isExpandedParameterPack())
3845 return TTP->getNumExpansionTemplateParameters();
3846 }
3847
David Blaikie7a30dc52013-02-21 01:47:18 +00003848 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003849}
3850
Richard Smith35c1df52015-06-17 20:16:32 +00003851/// Diagnose a missing template argument.
3852template<typename TemplateParmDecl>
3853static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3854 TemplateDecl *TD,
3855 const TemplateParmDecl *D,
3856 TemplateArgumentListInfo &Args) {
3857 // Dig out the most recent declaration of the template parameter; there may be
3858 // declarations of the template that are more recent than TD.
3859 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3860 ->getTemplateParameters()
3861 ->getParam(D->getIndex()));
3862
3863 // If there's a default argument that's not visible, diagnose that we're
3864 // missing a module import.
3865 llvm::SmallVector<Module*, 8> Modules;
3866 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3867 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3868 D->getDefaultArgumentLoc(), Modules,
3869 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00003870 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00003871 return true;
3872 }
3873
3874 // FIXME: If there's a more recent default argument that *is* visible,
3875 // diagnose that it was declared too late.
3876
3877 return diagnoseArityMismatch(S, TD, Loc, Args);
3878}
3879
Douglas Gregord32e0282009-02-09 23:23:08 +00003880/// \brief Check that the given template argument list is well-formed
3881/// for specializing the given template.
3882bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3883 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003884 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003885 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003886 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003887 // Make a copy of the template arguments for processing. Only make the
3888 // changes at the end when successful in matching the arguments to the
3889 // template.
3890 TemplateArgumentListInfo NewArgs = TemplateArgs;
3891
Douglas Gregord32e0282009-02-09 23:23:08 +00003892 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003893
Richard Trieu15b66532015-01-24 02:48:32 +00003894 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003895
Mike Stump11289f42009-09-09 15:08:12 +00003896 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003897 // [...] The type and form of each template-argument specified in
3898 // a template-id shall match the type and form specified for the
3899 // corresponding parameter declared by the template in its
3900 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003901 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003902 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003903 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003904 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003905 for (TemplateParameterList::iterator Param = Params->begin(),
3906 ParamEnd = Params->end();
3907 Param != ParamEnd; /* increment in loop */) {
3908 // If we have an expanded parameter pack, make sure we don't have too
3909 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003910 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003911 if (*Expansions == ArgumentPack.size()) {
3912 // We're done with this parameter pack. Pack up its arguments and add
3913 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003914 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00003915 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003916 ArgumentPack.clear();
3917
Richard Smith1fde8ec2012-09-07 02:06:42 +00003918 // This argument is assigned to the next parameter.
3919 ++Param;
3920 continue;
3921 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3922 // Not enough arguments for this parameter pack.
3923 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3924 << false
3925 << (isa<ClassTemplateDecl>(Template)? 0 :
3926 isa<FunctionTemplateDecl>(Template)? 1 :
3927 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3928 << Template;
3929 Diag(Template->getLocation(), diag::note_template_decl_here)
3930 << Params->getSourceRange();
3931 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003932 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003933 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003934
Richard Smith1fde8ec2012-09-07 02:06:42 +00003935 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003936 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003937 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003938 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003939 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003940 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003941
Richard Smith96d71c32014-11-12 23:38:38 +00003942 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003943 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003944 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3945 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003946 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003947 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003948 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003949 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003950 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003951 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003952 Diag((*Param)->getLocation(), diag::note_template_param_here);
3953 return true;
3954 }
3955
Richard Smith1fde8ec2012-09-07 02:06:42 +00003956 // We're now done with this argument.
3957 ++ArgIdx;
3958
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003959 if ((*Param)->isTemplateParameterPack()) {
3960 // The template parameter was a template parameter pack, so take the
3961 // deduced argument and place it on the argument pack. Note that we
3962 // stay on the same template parameter so that we can deduce more
3963 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003964 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003965 } else {
3966 // Move to the next template parameter.
3967 ++Param;
3968 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003969
Richard Smith96d71c32014-11-12 23:38:38 +00003970 // If we just saw a pack expansion into a non-pack, then directly convert
3971 // the remaining arguments, because we don't know what parameters they'll
3972 // match up with.
3973 if (PackExpansionIntoNonPack) {
3974 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003975 // If we were part way through filling in an expanded parameter pack,
3976 // fall back to just producing individual arguments.
3977 Converted.insert(Converted.end(),
3978 ArgumentPack.begin(), ArgumentPack.end());
3979 ArgumentPack.clear();
3980 }
3981
3982 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003983 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003984 ++ArgIdx;
3985 }
3986
Richard Smith1fde8ec2012-09-07 02:06:42 +00003987 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003988 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003989
Douglas Gregor84d49a22009-11-11 21:54:23 +00003990 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003992
Douglas Gregor2f157c92011-06-03 02:59:40 +00003993 // If we're checking a partial template argument list, we're done.
3994 if (PartialTemplateArgs) {
3995 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00003996 Converted.push_back(
3997 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3998
Richard Smith1fde8ec2012-09-07 02:06:42 +00003999 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00004000 }
4001
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004002 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004003 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00004004 if ((*Param)->isTemplateParameterPack()) {
4005 assert(!getExpandedPackSize(*Param) &&
4006 "Should have dealt with this already");
4007
4008 // A non-expanded parameter pack before the end of the parameter list
4009 // only occurs for an ill-formed template parameter list, unless we've
4010 // got a partial argument list for a function template, so just bail out.
4011 if (Param + 1 != ParamEnd)
4012 return true;
4013
Benjamin Kramercce63472015-08-05 09:40:22 +00004014 Converted.push_back(
4015 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004016 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00004017
4018 ++Param;
4019 continue;
4020 }
4021
Douglas Gregor8e072612012-02-03 07:34:46 +00004022 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00004023 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004024
Douglas Gregor84d49a22009-11-11 21:54:23 +00004025 // Retrieve the default template argument from the template
4026 // parameter. For each kind of template parameter, we substitute the
4027 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004028 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004029 // the default argument.
4030 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004031 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004032 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4033 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004034
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004035 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004036 Template,
4037 TemplateLoc,
4038 RAngleLoc,
4039 TTP,
4040 Converted);
4041 if (!ArgType)
4042 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004043
Douglas Gregor84d49a22009-11-11 21:54:23 +00004044 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4045 ArgType);
4046 } else if (NonTypeTemplateParmDecl *NTTP
4047 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004048 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004049 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4050 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004051
John McCalldadc5752010-08-24 06:29:42 +00004052 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004053 TemplateLoc,
4054 RAngleLoc,
4055 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004056 Converted);
4057 if (E.isInvalid())
4058 return true;
4059
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004060 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004061 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4062 } else {
4063 TemplateTemplateParmDecl *TempParm
4064 = cast<TemplateTemplateParmDecl>(*Param);
4065
Richard Smith95d83952015-06-10 20:36:34 +00004066 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004067 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4068 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004069
Douglas Gregordf846d12011-03-02 18:46:51 +00004070 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004071 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004072 TemplateLoc,
4073 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004074 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004075 Converted,
4076 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004077 if (Name.isNull())
4078 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004079
Douglas Gregor9d802122011-03-02 17:09:35 +00004080 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4081 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004082 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004083
Douglas Gregor84d49a22009-11-11 21:54:23 +00004084 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00004085 // the default template argument. We're not actually instantiating a
4086 // template here, we just create this object to put a note into the
4087 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004088 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4089 SourceRange(TemplateLoc, RAngleLoc));
4090 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004091 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004092
Douglas Gregor84d49a22009-11-11 21:54:23 +00004093 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004094 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004095 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004096 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004097
Richard Trieu15b66532015-01-24 02:48:32 +00004098 // Core issue 150 (assumed resolution): if this is a template template
4099 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004100 // template definition.
4101 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004102 NewArgs.addArgument(Arg);
4103
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004104 // Move to the next template parameter and argument.
4105 ++Param;
4106 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108
Richard Smith07f79912014-06-06 16:00:50 +00004109 // If we're performing a partial argument substitution, allow any trailing
4110 // pack expansions; they might be empty. This can happen even if
4111 // PartialTemplateArgs is false (the list of arguments is complete but
4112 // still dependent).
4113 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4114 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004115 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4116 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004117 }
4118
Douglas Gregor8e072612012-02-03 07:34:46 +00004119 // If we have any leftover arguments, then there were too many arguments.
4120 // Complain and fail.
4121 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004122 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4123
4124 // No problems found with the new argument list, propagate changes back
4125 // to caller.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00004126 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004127
Richard Smith1fde8ec2012-09-07 02:06:42 +00004128 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004129}
4130
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004131namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004132 class UnnamedLocalNoLinkageFinder
4133 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004134 {
4135 Sema &S;
4136 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004137
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004138 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004139
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004140 public:
4141 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4142
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143 bool Visit(QualType T) {
4144 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004146
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004147#define TYPE(Class, Parent) \
4148 bool Visit##Class##Type(const Class##Type *);
4149#define ABSTRACT_TYPE(Class, Parent) \
4150 bool Visit##Class##Type(const Class##Type *) { return false; }
4151#define NON_CANONICAL_TYPE(Class, Parent) \
4152 bool Visit##Class##Type(const Class##Type *) { return false; }
4153#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004154
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004155 bool VisitTagDecl(const TagDecl *Tag);
4156 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4157 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004158} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004159
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004161 return false;
4162}
4163
4164bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4165 return Visit(T->getElementType());
4166}
4167
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004168bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004169 return Visit(T->getPointeeType());
4170}
4171
4172bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004174 return Visit(T->getPointeeType());
4175}
4176
4177bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004178 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004179 return Visit(T->getPointeeType());
4180}
4181
4182bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004183 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004184 return Visit(T->getPointeeType());
4185}
4186
4187bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004189 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4190}
4191
4192bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004193 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004194 return Visit(T->getElementType());
4195}
4196
4197bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004198 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004199 return Visit(T->getElementType());
4200}
4201
4202bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004203 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004204 return Visit(T->getElementType());
4205}
4206
4207bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004208 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004209 return Visit(T->getElementType());
4210}
4211
4212bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004213 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004214 return Visit(T->getElementType());
4215}
4216
4217bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4218 return Visit(T->getElementType());
4219}
4220
4221bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4222 return Visit(T->getElementType());
4223}
4224
4225bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4226 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004227 for (const auto &A : T->param_types()) {
4228 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004229 return true;
4230 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004231
Alp Toker314cc812014-01-25 16:55:45 +00004232 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004233}
4234
4235bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4236 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004237 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004238}
4239
4240bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4241 const UnresolvedUsingType*) {
4242 return false;
4243}
4244
4245bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4246 return false;
4247}
4248
4249bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4250 return Visit(T->getUnderlyingType());
4251}
4252
4253bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4254 return false;
4255}
4256
Alexis Hunte852b102011-05-24 22:41:36 +00004257bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4258 const UnaryTransformType*) {
4259 return false;
4260}
4261
Richard Smith30482bc2011-02-20 03:19:35 +00004262bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4263 return Visit(T->getDeducedType());
4264}
4265
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004266bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4267 return VisitTagDecl(T->getDecl());
4268}
4269
4270bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4271 return VisitTagDecl(T->getDecl());
4272}
4273
4274bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4275 const TemplateTypeParmType*) {
4276 return false;
4277}
4278
Douglas Gregorada4b792011-01-14 02:55:32 +00004279bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4280 const SubstTemplateTypeParmPackType *) {
4281 return false;
4282}
4283
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004284bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4285 const TemplateSpecializationType*) {
4286 return false;
4287}
4288
4289bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4290 const InjectedClassNameType* T) {
4291 return VisitTagDecl(T->getDecl());
4292}
4293
4294bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4295 const DependentNameType* T) {
4296 return VisitNestedNameSpecifier(T->getQualifier());
4297}
4298
4299bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4300 const DependentTemplateSpecializationType* T) {
4301 return VisitNestedNameSpecifier(T->getQualifier());
4302}
4303
Douglas Gregord2fa7662010-12-20 02:24:11 +00004304bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4305 const PackExpansionType* T) {
4306 return Visit(T->getPattern());
4307}
4308
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004309bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4310 return false;
4311}
4312
4313bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4314 const ObjCInterfaceType *) {
4315 return false;
4316}
4317
4318bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4319 const ObjCObjectPointerType *) {
4320 return false;
4321}
4322
Eli Friedman0dfb8892011-10-06 23:00:33 +00004323bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4324 return Visit(T->getValueType());
4325}
4326
Xiuli Pan9c14e282016-01-09 12:53:17 +00004327bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4328 return false;
4329}
4330
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004331bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4332 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004333 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004334 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004335 diag::warn_cxx98_compat_template_arg_local_type :
4336 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004337 << S.Context.getTypeDeclType(Tag) << SR;
4338 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004339 }
4340
John McCall5ea95772013-03-09 00:54:27 +00004341 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004342 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004343 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004344 diag::warn_cxx98_compat_template_arg_unnamed_type :
4345 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004346 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4347 return true;
4348 }
4349
4350 return false;
4351}
4352
4353bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4354 NestedNameSpecifier *NNS) {
4355 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4356 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004358 switch (NNS->getKind()) {
4359 case NestedNameSpecifier::Identifier:
4360 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004361 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004362 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004363 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004364 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004366 case NestedNameSpecifier::TypeSpec:
4367 case NestedNameSpecifier::TypeSpecWithTemplate:
4368 return Visit(QualType(NNS->getAsType(), 0));
4369 }
David Blaikie8a40f702012-01-17 06:56:22 +00004370 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004371}
4372
Douglas Gregord32e0282009-02-09 23:23:08 +00004373/// \brief Check a template argument against its corresponding
4374/// template type parameter.
4375///
4376/// This routine implements the semantics of C++ [temp.arg.type]. It
4377/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004378bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004379 TypeSourceInfo *ArgInfo) {
4380 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004381 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004382 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004383
4384 if (Arg->isVariablyModifiedType()) {
4385 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004386 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004387 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004388 }
4389
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004390 // C++03 [temp.arg.type]p2:
4391 // A local type, a type with no linkage, an unnamed type or a type
4392 // compounded from any of these types shall not be used as a
4393 // template-argument for a template type-parameter.
4394 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004395 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004396 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004397 bool NeedsCheck;
4398 if (LangOpts.CPlusPlus11)
4399 NeedsCheck =
4400 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4401 SR.getBegin()) ||
4402 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4403 SR.getBegin());
4404 else
4405 NeedsCheck = Arg->hasUnnamedOrLocalType();
4406
4407 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004408 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4409 (void)Finder.Visit(Context.getCanonicalType(Arg));
4410 }
4411
Douglas Gregord32e0282009-02-09 23:23:08 +00004412 return false;
4413}
4414
Douglas Gregor20fdef32012-04-10 17:08:25 +00004415enum NullPointerValueKind {
4416 NPV_NotNullPointer,
4417 NPV_NullPointer,
4418 NPV_Error
4419};
4420
4421/// \brief Determine whether the given template argument is a null pointer
4422/// value of the appropriate type.
4423static NullPointerValueKind
4424isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4425 QualType ParamType, Expr *Arg) {
4426 if (Arg->isValueDependent() || Arg->isTypeDependent())
4427 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004428
Richard Smithdb0ac552015-12-18 22:40:25 +00004429 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004430 llvm_unreachable(
4431 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004432
David Majnemer5c734ad2014-08-14 00:49:23 +00004433 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004434 return NPV_NotNullPointer;
4435
4436 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004437 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4438 if (ArgRV.isInvalid())
4439 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004440 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004441
Douglas Gregor20fdef32012-04-10 17:08:25 +00004442 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004443 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004444 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004445 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004446 EvalResult.HasSideEffects) {
4447 SourceLocation DiagLoc = Arg->getExprLoc();
4448
4449 // If our only note is the usual "invalid subexpression" note, just point
4450 // the caret at its location rather than producing an essentially
4451 // redundant note.
4452 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4453 diag::note_invalid_subexpr_in_const_expr) {
4454 DiagLoc = Notes[0].first;
4455 Notes.clear();
4456 }
4457
4458 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4459 << Arg->getType() << Arg->getSourceRange();
4460 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4461 S.Diag(Notes[I].first, Notes[I].second);
4462
4463 S.Diag(Param->getLocation(), diag::note_template_param_here);
4464 return NPV_Error;
4465 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004466
4467 // C++11 [temp.arg.nontype]p1:
4468 // - an address constant expression of type std::nullptr_t
4469 if (Arg->getType()->isNullPtrType())
4470 return NPV_NullPointer;
4471
4472 // - a constant expression that evaluates to a null pointer value (4.10); or
4473 // - a constant expression that evaluates to a null member pointer value
4474 // (4.11); or
4475 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4476 (EvalResult.Val.isMemberPointer() &&
4477 !EvalResult.Val.getMemberPointerDecl())) {
4478 // If our expression has an appropriate type, we've succeeded.
4479 bool ObjCLifetimeConversion;
4480 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4481 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4482 ObjCLifetimeConversion))
4483 return NPV_NullPointer;
4484
4485 // The types didn't match, but we know we got a null pointer; complain,
4486 // then recover as if the types were correct.
4487 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4488 << Arg->getType() << ParamType << Arg->getSourceRange();
4489 S.Diag(Param->getLocation(), diag::note_template_param_here);
4490 return NPV_NullPointer;
4491 }
4492
4493 // If we don't have a null pointer value, but we do have a NULL pointer
4494 // constant, suggest a cast to the appropriate type.
4495 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4496 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4497 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004498 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4499 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4500 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004501 S.Diag(Param->getLocation(), diag::note_template_param_here);
4502 return NPV_NullPointer;
4503 }
4504
4505 // FIXME: If we ever want to support general, address-constant expressions
4506 // as non-type template arguments, we should return the ExprResult here to
4507 // be interpreted by the caller.
4508 return NPV_NotNullPointer;
4509}
4510
David Majnemer61c39a12013-08-23 05:39:39 +00004511/// \brief Checks whether the given template argument is compatible with its
4512/// template parameter.
4513static bool CheckTemplateArgumentIsCompatibleWithParameter(
4514 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4515 Expr *Arg, QualType ArgType) {
4516 bool ObjCLifetimeConversion;
4517 if (ParamType->isPointerType() &&
4518 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4519 S.IsQualificationConversion(ArgType, ParamType, false,
4520 ObjCLifetimeConversion)) {
4521 // For pointer-to-object types, qualification conversions are
4522 // permitted.
4523 } else {
4524 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4525 if (!ParamRef->getPointeeType()->isFunctionType()) {
4526 // C++ [temp.arg.nontype]p5b3:
4527 // For a non-type template-parameter of type reference to
4528 // object, no conversions apply. The type referred to by the
4529 // reference may be more cv-qualified than the (otherwise
4530 // identical) type of the template- argument. The
4531 // template-parameter is bound directly to the
4532 // template-argument, which shall be an lvalue.
4533
4534 // FIXME: Other qualifiers?
4535 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4536 unsigned ArgQuals = ArgType.getCVRQualifiers();
4537
4538 if ((ParamQuals | ArgQuals) != ParamQuals) {
4539 S.Diag(Arg->getLocStart(),
4540 diag::err_template_arg_ref_bind_ignores_quals)
4541 << ParamType << Arg->getType() << Arg->getSourceRange();
4542 S.Diag(Param->getLocation(), diag::note_template_param_here);
4543 return true;
4544 }
4545 }
4546 }
4547
4548 // At this point, the template argument refers to an object or
4549 // function with external linkage. We now need to check whether the
4550 // argument and parameter types are compatible.
4551 if (!S.Context.hasSameUnqualifiedType(ArgType,
4552 ParamType.getNonReferenceType())) {
4553 // We can't perform this conversion or binding.
4554 if (ParamType->isReferenceType())
4555 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4556 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4557 else
4558 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4559 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4560 S.Diag(Param->getLocation(), diag::note_template_param_here);
4561 return true;
4562 }
4563 }
4564
4565 return false;
4566}
4567
Douglas Gregorccb07762009-02-11 19:52:55 +00004568/// \brief Checks whether the given template argument is the address
4569/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004570static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004571CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4572 NonTypeTemplateParmDecl *Param,
4573 QualType ParamType,
4574 Expr *ArgIn,
4575 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004576 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004577 Expr *Arg = ArgIn;
4578 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004579
Douglas Gregorb242683d2010-04-01 18:32:35 +00004580 bool AddressTaken = false;
4581 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004582 if (S.getLangOpts().MicrosoftExt) {
4583 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4584 // dereference and address-of operators.
4585 Arg = Arg->IgnoreParenCasts();
4586
4587 bool ExtWarnMSTemplateArg = false;
4588 UnaryOperatorKind FirstOpKind;
4589 SourceLocation FirstOpLoc;
4590 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4591 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4592 if (UnOpKind == UO_Deref)
4593 ExtWarnMSTemplateArg = true;
4594 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4595 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4596 if (!AddrOpLoc.isValid()) {
4597 FirstOpKind = UnOpKind;
4598 FirstOpLoc = UnOp->getOperatorLoc();
4599 }
4600 } else
4601 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004602 }
David Majnemer61c39a12013-08-23 05:39:39 +00004603 if (FirstOpLoc.isValid()) {
4604 if (ExtWarnMSTemplateArg)
4605 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4606 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004607
David Majnemer61c39a12013-08-23 05:39:39 +00004608 if (FirstOpKind == UO_AddrOf)
4609 AddressTaken = true;
4610 else if (Arg->getType()->isPointerType()) {
4611 // We cannot let pointers get dereferenced here, that is obviously not a
4612 // constant expression.
4613 assert(FirstOpKind == UO_Deref);
4614 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4615 << Arg->getSourceRange();
4616 }
4617 }
4618 } else {
4619 // See through any implicit casts we added to fix the type.
4620 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004621
David Majnemer61c39a12013-08-23 05:39:39 +00004622 // C++ [temp.arg.nontype]p1:
4623 //
4624 // A template-argument for a non-type, non-template
4625 // template-parameter shall be one of: [...]
4626 //
4627 // -- the address of an object or function with external
4628 // linkage, including function templates and function
4629 // template-ids but excluding non-static class members,
4630 // expressed as & id-expression where the & is optional if
4631 // the name refers to a function or array, or if the
4632 // corresponding template-parameter is a reference; or
4633
4634 // In C++98/03 mode, give an extension warning on any extra parentheses.
4635 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4636 bool ExtraParens = false;
4637 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4638 if (!Invalid && !ExtraParens) {
4639 S.Diag(Arg->getLocStart(),
4640 S.getLangOpts().CPlusPlus11
4641 ? diag::warn_cxx98_compat_template_arg_extra_parens
4642 : diag::ext_template_arg_extra_parens)
4643 << Arg->getSourceRange();
4644 ExtraParens = true;
4645 }
4646
4647 Arg = Parens->getSubExpr();
4648 }
4649
4650 while (SubstNonTypeTemplateParmExpr *subst =
4651 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4652 Arg = subst->getReplacement()->IgnoreImpCasts();
4653
4654 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4655 if (UnOp->getOpcode() == UO_AddrOf) {
4656 Arg = UnOp->getSubExpr();
4657 AddressTaken = true;
4658 AddrOpLoc = UnOp->getOperatorLoc();
4659 }
4660 }
4661
4662 while (SubstNonTypeTemplateParmExpr *subst =
4663 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4664 Arg = subst->getReplacement()->IgnoreImpCasts();
4665 }
John McCall7c454bb2011-07-15 05:09:51 +00004666
David Majnemer07910d62014-06-26 07:48:46 +00004667 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4668 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4669
4670 // If our parameter has pointer type, check for a null template value.
4671 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4672 NullPointerValueKind NPV;
4673 // dllimport'd entities aren't constant but are available inside of template
4674 // arguments.
4675 if (Entity && Entity->hasAttr<DLLImportAttr>())
4676 NPV = NPV_NotNullPointer;
4677 else
4678 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4679 switch (NPV) {
4680 case NPV_NullPointer:
4681 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004682 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4683 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004684 return false;
4685
4686 case NPV_Error:
4687 return true;
4688
4689 case NPV_NotNullPointer:
4690 break;
4691 }
4692 }
4693
Chandler Carruth724a8a12010-01-31 10:01:20 +00004694 // Stop checking the precise nature of the argument if it is value dependent,
4695 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004696 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004697 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004698 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004699 }
David Majnemer61c39a12013-08-23 05:39:39 +00004700
4701 if (isa<CXXUuidofExpr>(Arg)) {
4702 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4703 ArgIn, Arg, ArgType))
4704 return true;
4705
4706 Converted = TemplateArgument(ArgIn);
4707 return false;
4708 }
4709
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004710 if (!DRE) {
4711 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4712 << Arg->getSourceRange();
4713 S.Diag(Param->getLocation(), diag::note_template_param_here);
4714 return true;
4715 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004716
Douglas Gregorccb07762009-02-11 19:52:55 +00004717 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004718 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004719 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004720 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004721 S.Diag(Param->getLocation(), diag::note_template_param_here);
4722 return true;
4723 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004724
4725 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004726 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004727 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004728 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004729 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004730 S.Diag(Param->getLocation(), diag::note_template_param_here);
4731 return true;
4732 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004733 }
Mike Stump11289f42009-09-09 15:08:12 +00004734
Richard Smith9380e0e2012-04-04 21:11:30 +00004735 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4736 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004737
Richard Smith9380e0e2012-04-04 21:11:30 +00004738 // A non-type template argument must refer to an object or function.
4739 if (!Func && !Var) {
4740 // We found something, but we don't know specifically what it is.
4741 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4742 << Arg->getSourceRange();
4743 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4744 return true;
4745 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004746
Richard Smith9380e0e2012-04-04 21:11:30 +00004747 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004748 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004749 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004750 diag::warn_cxx98_compat_template_arg_object_internal :
4751 diag::ext_template_arg_object_internal)
4752 << !Func << Entity << Arg->getSourceRange();
4753 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4754 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004755 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004756 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4757 << !Func << Entity << Arg->getSourceRange();
4758 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4759 << !Func;
4760 return true;
4761 }
4762
4763 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004764 // If the template parameter has pointer type, the function decays.
4765 if (ParamType->isPointerType() && !AddressTaken)
4766 ArgType = S.Context.getPointerType(Func->getType());
4767 else if (AddressTaken && ParamType->isReferenceType()) {
4768 // If we originally had an address-of operator, but the
4769 // parameter has reference type, complain and (if things look
4770 // like they will work) drop the address-of operator.
4771 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4772 ParamType.getNonReferenceType())) {
4773 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4774 << ParamType;
4775 S.Diag(Param->getLocation(), diag::note_template_param_here);
4776 return true;
4777 }
4778
4779 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4780 << ParamType
4781 << FixItHint::CreateRemoval(AddrOpLoc);
4782 S.Diag(Param->getLocation(), diag::note_template_param_here);
4783
4784 ArgType = Func->getType();
4785 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004786 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004787 // A value of reference type is not an object.
4788 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004789 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004790 diag::err_template_arg_reference_var)
4791 << Var->getType() << Arg->getSourceRange();
4792 S.Diag(Param->getLocation(), diag::note_template_param_here);
4793 return true;
4794 }
4795
Richard Smith9380e0e2012-04-04 21:11:30 +00004796 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004797 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004798 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4799 << Arg->getSourceRange();
4800 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4801 return true;
4802 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004803
4804 // If the template parameter has pointer type, we must have taken
4805 // the address of this object.
4806 if (ParamType->isReferenceType()) {
4807 if (AddressTaken) {
4808 // If we originally had an address-of operator, but the
4809 // parameter has reference type, complain and (if things look
4810 // like they will work) drop the address-of operator.
4811 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4812 ParamType.getNonReferenceType())) {
4813 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4814 << ParamType;
4815 S.Diag(Param->getLocation(), diag::note_template_param_here);
4816 return true;
4817 }
4818
4819 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4820 << ParamType
4821 << FixItHint::CreateRemoval(AddrOpLoc);
4822 S.Diag(Param->getLocation(), diag::note_template_param_here);
4823
4824 ArgType = Var->getType();
4825 }
4826 } else if (!AddressTaken && ParamType->isPointerType()) {
4827 if (Var->getType()->isArrayType()) {
4828 // Array-to-pointer decay.
4829 ArgType = S.Context.getArrayDecayedType(Var->getType());
4830 } else {
4831 // If the template parameter has pointer type but the address of
4832 // this object was not taken, complain and (possibly) recover by
4833 // taking the address of the entity.
4834 ArgType = S.Context.getPointerType(Var->getType());
4835 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4836 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4837 << ParamType;
4838 S.Diag(Param->getLocation(), diag::note_template_param_here);
4839 return true;
4840 }
4841
4842 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4843 << ParamType
4844 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4845
4846 S.Diag(Param->getLocation(), diag::note_template_param_here);
4847 }
4848 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004849 }
Mike Stump11289f42009-09-09 15:08:12 +00004850
David Majnemer61c39a12013-08-23 05:39:39 +00004851 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4852 Arg, ArgType))
4853 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004854
4855 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004856 Converted =
4857 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004858 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004859 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004860}
4861
4862/// \brief Checks whether the given template argument is a pointer to
4863/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004864static bool CheckTemplateArgumentPointerToMember(Sema &S,
4865 NonTypeTemplateParmDecl *Param,
4866 QualType ParamType,
4867 Expr *&ResultArg,
4868 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004869 bool Invalid = false;
4870
Douglas Gregor20fdef32012-04-10 17:08:25 +00004871 // Check for a null pointer value.
4872 Expr *Arg = ResultArg;
4873 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4874 case NPV_Error:
4875 return true;
4876 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004877 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004878 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4879 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004880 return false;
4881 case NPV_NotNullPointer:
4882 break;
4883 }
4884
4885 bool ObjCLifetimeConversion;
4886 if (S.IsQualificationConversion(Arg->getType(),
4887 ParamType.getNonReferenceType(),
4888 false, ObjCLifetimeConversion)) {
4889 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004890 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004891 ResultArg = Arg;
4892 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4893 ParamType.getNonReferenceType())) {
4894 // We can't perform this conversion.
4895 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4896 << Arg->getType() << ParamType << Arg->getSourceRange();
4897 S.Diag(Param->getLocation(), diag::note_template_param_here);
4898 return true;
4899 }
4900
Douglas Gregorccb07762009-02-11 19:52:55 +00004901 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004902 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004903 Arg = Cast->getSubExpr();
4904
4905 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004906 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004907 // A template-argument for a non-type, non-template
4908 // template-parameter shall be one of: [...]
4909 //
4910 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004911 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004912
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004913 // In C++98/03 mode, give an extension warning on any extra parentheses.
4914 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4915 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004916 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004917 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004918 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004919 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004920 diag::warn_cxx98_compat_template_arg_extra_parens :
4921 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004922 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004923 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004924 }
4925
4926 Arg = Parens->getSubExpr();
4927 }
4928
John McCall7c454bb2011-07-15 05:09:51 +00004929 while (SubstNonTypeTemplateParmExpr *subst =
4930 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4931 Arg = subst->getReplacement()->IgnoreImpCasts();
4932
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004933 // A pointer-to-member constant written &Class::member.
4934 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004935 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004936 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4937 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004938 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004939 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004941 // A constant of pointer-to-member type.
4942 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4943 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4944 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004945 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004946 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004947 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004948 } else {
4949 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004950 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004951 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004952 return Invalid;
4953 }
4954 }
4955 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004956
Craig Topperc3ec1492014-05-26 06:22:03 +00004957 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004958 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004959
Douglas Gregorccb07762009-02-11 19:52:55 +00004960 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004961 return S.Diag(Arg->getLocStart(),
4962 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004963 << Arg->getSourceRange();
4964
David Majnemer3ac84e62013-10-22 21:56:38 +00004965 if (isa<FieldDecl>(DRE->getDecl()) ||
4966 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4967 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004968 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004969 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004970 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4971 "Only non-static member pointers can make it here");
4972
4973 // Okay: this is the address of a non-static member, and therefore
4974 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004975 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004976 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004977 } else {
4978 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004979 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004980 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004981 return Invalid;
4982 }
4983
4984 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004985 S.Diag(Arg->getLocStart(),
4986 diag::err_template_arg_not_pointer_to_member_form)
4987 << Arg->getSourceRange();
4988 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004989 return true;
4990}
4991
Douglas Gregord32e0282009-02-09 23:23:08 +00004992/// \brief Check a template argument against its corresponding
4993/// non-type template parameter.
4994///
Douglas Gregor463421d2009-03-03 04:44:36 +00004995/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004996/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004997/// returns the converted template argument. \p ParamType is the
4998/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004999ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00005000 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00005001 TemplateArgument &Converted,
5002 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005003 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00005004
Richard Smith5f274382016-09-28 23:55:27 +00005005 // If the parameter type somehow involves auto, deduce the type now.
5006 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
5007 if (DeduceAutoType(
5008 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
5009 Arg, ParamType) == DAR_Failed) {
5010 Diag(Arg->getExprLoc(),
5011 diag::err_non_type_template_parm_type_deduction_failure)
5012 << Param->getDeclName() << Param->getType() << Arg->getType()
5013 << Arg->getSourceRange();
5014 Diag(Param->getLocation(), diag::note_template_param_here);
5015 return ExprError();
5016 }
5017 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5018 // an error. The error message normally references the parameter
5019 // declaration, but here we'll pass the argument location because that's
5020 // where the parameter type is deduced.
5021 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5022 if (ParamType.isNull()) {
5023 Diag(Param->getLocation(), diag::note_template_param_here);
5024 return ExprError();
5025 }
5026 }
5027
Douglas Gregor86560402009-02-10 23:36:10 +00005028 // If either the parameter has a dependent type or the argument is
5029 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00005030 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00005031 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005032 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005033 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00005034 }
Douglas Gregor86560402009-02-10 23:36:10 +00005035
Richard Smithd663fdd2014-12-17 20:42:37 +00005036 // We should have already dropped all cv-qualifiers by now.
5037 assert(!ParamType.hasQualifiers() &&
5038 "non-type template parameter type cannot be qualified");
5039
5040 if (CTAK == CTAK_Deduced &&
5041 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
5042 // C++ [temp.deduct.type]p17:
5043 // If, in the declaration of a function template with a non-type
5044 // template-parameter, the non-type template-parameter is used
5045 // in an expression in the function parameter-list and, if the
5046 // corresponding template-argument is deduced, the
5047 // template-argument type shall match the type of the
5048 // template-parameter exactly, except that a template-argument
5049 // deduced from an array bound may be of any integral type.
5050 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
5051 << Arg->getType().getUnqualifiedType()
5052 << ParamType.getUnqualifiedType();
5053 Diag(Param->getLocation(), diag::note_template_param_here);
5054 return ExprError();
5055 }
5056
Richard Smith410cc892014-11-26 03:26:53 +00005057 if (getLangOpts().CPlusPlus1z) {
5058 // FIXME: We can do some limited checking for a value-dependent but not
5059 // type-dependent argument.
5060 if (Arg->isValueDependent()) {
5061 Converted = TemplateArgument(Arg);
5062 return Arg;
5063 }
5064
5065 // C++1z [temp.arg.nontype]p1:
5066 // A template-argument for a non-type template parameter shall be
5067 // a converted constant expression of the type of the template-parameter.
5068 APValue Value;
5069 ExprResult ArgResult = CheckConvertedConstantExpression(
5070 Arg, ParamType, Value, CCEK_TemplateArg);
5071 if (ArgResult.isInvalid())
5072 return ExprError();
5073
Richard Smithd663fdd2014-12-17 20:42:37 +00005074 QualType CanonParamType = Context.getCanonicalType(ParamType);
5075
Richard Smith410cc892014-11-26 03:26:53 +00005076 // Convert the APValue to a TemplateArgument.
5077 switch (Value.getKind()) {
5078 case APValue::Uninitialized:
5079 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005080 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005081 break;
5082 case APValue::Int:
5083 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005084 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005085 break;
5086 case APValue::MemberPointer: {
5087 assert(ParamType->isMemberPointerType());
5088
5089 // FIXME: We need TemplateArgument representation and mangling for these.
5090 if (!Value.getMemberPointerPath().empty()) {
5091 Diag(Arg->getLocStart(),
5092 diag::err_template_arg_member_ptr_base_derived_not_supported)
5093 << Value.getMemberPointerDecl() << ParamType
5094 << Arg->getSourceRange();
5095 return ExprError();
5096 }
5097
5098 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005099 Converted = VD ? TemplateArgument(VD, CanonParamType)
5100 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005101 break;
5102 }
5103 case APValue::LValue: {
5104 // For a non-type template-parameter of pointer or reference type,
5105 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00005106 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5107 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00005108 // -- a temporary object
5109 // -- a string literal
5110 // -- the result of a typeid expression, or
5111 // -- a predefind __func__ variable
5112 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5113 if (isa<CXXUuidofExpr>(E)) {
5114 Converted = TemplateArgument(const_cast<Expr*>(E));
5115 break;
5116 }
5117 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5118 << Arg->getSourceRange();
5119 return ExprError();
5120 }
5121 auto *VD = const_cast<ValueDecl *>(
5122 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5123 // -- a subobject
5124 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5125 VD && VD->getType()->isArrayType() &&
5126 Value.getLValuePath()[0].ArrayIndex == 0 &&
5127 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5128 // Per defect report (no number yet):
5129 // ... other than a pointer to the first element of a complete array
5130 // object.
5131 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5132 Value.isLValueOnePastTheEnd()) {
5133 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5134 << Value.getAsString(Context, ParamType);
5135 return ExprError();
5136 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005137 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005138 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005139 assert((!VD || !ParamType->isNullPtrType()) &&
5140 "non-null value of type nullptr_t?");
5141 Converted = VD ? TemplateArgument(VD, CanonParamType)
5142 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005143 break;
5144 }
5145 case APValue::AddrLabelDiff:
5146 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5147 case APValue::Float:
5148 case APValue::ComplexInt:
5149 case APValue::ComplexFloat:
5150 case APValue::Vector:
5151 case APValue::Array:
5152 case APValue::Struct:
5153 case APValue::Union:
5154 llvm_unreachable("invalid kind for template argument");
5155 }
5156
5157 return ArgResult.get();
5158 }
5159
Douglas Gregor86560402009-02-10 23:36:10 +00005160 // C++ [temp.arg.nontype]p5:
5161 // The following conversions are performed on each expression used
5162 // as a non-type template-argument. If a non-type
5163 // template-argument cannot be converted to the type of the
5164 // corresponding template-parameter then the program is
5165 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005166 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005167 // C++11:
5168 // -- for a non-type template-parameter of integral or
5169 // enumeration type, conversions permitted in a converted
5170 // constant expression are applied.
5171 //
5172 // C++98:
5173 // -- for a non-type template-parameter of integral or
5174 // enumeration type, integral promotions (4.5) and integral
5175 // conversions (4.7) are applied.
5176
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005177 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005178 // We can't check arbitrary value-dependent arguments.
5179 // FIXME: If there's no viable conversion to the template parameter type,
5180 // we should be able to diagnose that prior to instantiation.
5181 if (Arg->isValueDependent()) {
5182 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005183 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00005184 }
5185
5186 // C++ [temp.arg.nontype]p1:
5187 // A template-argument for a non-type, non-template template-parameter
5188 // shall be one of:
5189 //
5190 // -- for a non-type template-parameter of integral or enumeration
5191 // type, a converted constant expression of the type of the
5192 // template-parameter; or
5193 llvm::APSInt Value;
5194 ExprResult ArgResult =
5195 CheckConvertedConstantExpression(Arg, ParamType, Value,
5196 CCEK_TemplateArg);
5197 if (ArgResult.isInvalid())
5198 return ExprError();
5199
5200 // Widen the argument value to sizeof(parameter type). This is almost
5201 // always a no-op, except when the parameter type is bool. In
5202 // that case, this may extend the argument from 1 bit to 8 bits.
5203 QualType IntegerType = ParamType;
5204 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5205 IntegerType = Enum->getDecl()->getIntegerType();
5206 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5207
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005208 Converted = TemplateArgument(Context, Value,
5209 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005210 return ArgResult;
5211 }
5212
Richard Smith08b12f12011-10-27 22:11:44 +00005213 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5214 if (ArgResult.isInvalid())
5215 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005216 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005217
5218 QualType ArgType = Arg->getType();
5219
Douglas Gregor86560402009-02-10 23:36:10 +00005220 // C++ [temp.arg.nontype]p1:
5221 // A template-argument for a non-type, non-template
5222 // template-parameter shall be one of:
5223 //
5224 // -- an integral constant-expression of integral or enumeration
5225 // type; or
5226 // -- the name of a non-type template-parameter; or
5227 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005228 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005229 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005230 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005231 diag::err_template_arg_not_integral_or_enumeral)
5232 << ArgType << Arg->getSourceRange();
5233 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005234 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005235 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005236 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5237 QualType T;
5238
5239 public:
5240 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005241
5242 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5243 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005244 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5245 }
5246 } Diagnoser(ArgType);
5247
5248 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005249 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005250 if (!Arg)
5251 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005252 }
5253
Richard Smithd663fdd2014-12-17 20:42:37 +00005254 // From here on out, all we care about is the unqualified form
5255 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005256 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005257
5258 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005259 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005260 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005261 } else if (ParamType->isBooleanType()) {
5262 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005263 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005264 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5265 !ParamType->isEnumeralType()) {
5266 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005267 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005268 } else {
5269 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005270 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005271 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005272 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005273 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005274 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005275 }
5276
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005277 // Add the value of this argument to the list of converted
5278 // arguments. We use the bitwidth and signedness of the template
5279 // parameter.
5280 if (Arg->isValueDependent()) {
5281 // The argument is value-dependent. Create a new
5282 // TemplateArgument with the converted expression.
5283 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005284 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005285 }
5286
Douglas Gregor52aba872009-03-14 00:20:21 +00005287 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005288 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005289 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005290
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005291 if (ParamType->isBooleanType()) {
5292 // Value must be zero or one.
5293 Value = Value != 0;
5294 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5295 if (Value.getBitWidth() != AllowedBits)
5296 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005297 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005298 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005299 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005300
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005301 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005302 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005303 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005304 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005305 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005306 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005307
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005308 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005309 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005310 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005311 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005312 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5313 << Arg->getSourceRange();
5314 Diag(Param->getLocation(), diag::note_template_param_here);
5315 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005316
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005317 // Complain if we overflowed the template parameter's type.
5318 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005319 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005320 RequiredBits = OldValue.getActiveBits();
5321 else if (OldValue.isUnsigned())
5322 RequiredBits = OldValue.getActiveBits() + 1;
5323 else
5324 RequiredBits = OldValue.getMinSignedBits();
5325 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005326 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005327 diag::warn_template_arg_too_large)
5328 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5329 << Arg->getSourceRange();
5330 Diag(Param->getLocation(), diag::note_template_param_here);
5331 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005332 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005333
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005334 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005335 ParamType->isEnumeralType()
5336 ? Context.getCanonicalType(ParamType)
5337 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005338 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005339 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005340
Richard Smith08b12f12011-10-27 22:11:44 +00005341 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005342 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5343
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005344 // Handle pointer-to-function, reference-to-function, and
5345 // pointer-to-member-function all in (roughly) the same way.
5346 if (// -- For a non-type template-parameter of type pointer to
5347 // function, only the function-to-pointer conversion (4.3) is
5348 // applied. If the template-argument represents a set of
5349 // overloaded functions (or a pointer to such), the matching
5350 // function is selected from the set (13.4).
5351 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005352 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005353 // -- For a non-type template-parameter of type reference to
5354 // function, no conversions apply. If the template-argument
5355 // represents a set of overloaded functions, the matching
5356 // function is selected from the set (13.4).
5357 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005358 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005359 // -- For a non-type template-parameter of type pointer to
5360 // member function, no conversions apply. If the
5361 // template-argument represents a set of overloaded member
5362 // functions, the matching member function is selected from
5363 // the set (13.4).
5364 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005365 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005366 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005367
Douglas Gregor064fdb22010-04-14 23:11:21 +00005368 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005369 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005370 true,
5371 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005372 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005373 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005374
5375 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5376 ArgType = Arg->getType();
5377 } else
John Wiegley01296292011-04-08 18:41:53 +00005378 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005379 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005380
John Wiegley01296292011-04-08 18:41:53 +00005381 if (!ParamType->isMemberPointerType()) {
5382 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5383 ParamType,
5384 Arg, Converted))
5385 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005386 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005387 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005388
Douglas Gregor20fdef32012-04-10 17:08:25 +00005389 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5390 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005391 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005392 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005393 }
5394
Chris Lattner696197c2009-02-20 21:37:53 +00005395 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005396 // -- for a non-type template-parameter of type pointer to
5397 // object, qualification conversions (4.4) and the
5398 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005399 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005400 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005401 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005402
John Wiegley01296292011-04-08 18:41:53 +00005403 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5404 ParamType,
5405 Arg, Converted))
5406 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005407 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005408 }
Mike Stump11289f42009-09-09 15:08:12 +00005409
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005410 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005411 // -- For a non-type template-parameter of type reference to
5412 // object, no conversions apply. The type referred to by the
5413 // reference may be more cv-qualified than the (otherwise
5414 // identical) type of the template-argument. The
5415 // template-parameter is bound directly to the
5416 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005417 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005418 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005419
Douglas Gregor064fdb22010-04-14 23:11:21 +00005420 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005421 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5422 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005423 true,
5424 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005425 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005426 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005427
5428 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5429 ArgType = Arg->getType();
5430 } else
John Wiegley01296292011-04-08 18:41:53 +00005431 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005432 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005433
John Wiegley01296292011-04-08 18:41:53 +00005434 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5435 ParamType,
5436 Arg, Converted))
5437 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005438 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005439 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005440
Douglas Gregor20fdef32012-04-10 17:08:25 +00005441 // Deal with parameters of type std::nullptr_t.
5442 if (ParamType->isNullPtrType()) {
5443 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5444 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005445 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005446 }
5447
5448 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5449 case NPV_NotNullPointer:
5450 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5451 << Arg->getType() << ParamType;
5452 Diag(Param->getLocation(), diag::note_template_param_here);
5453 return ExprError();
5454
5455 case NPV_Error:
5456 return ExprError();
5457
5458 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005459 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005460 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5461 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005462 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005463 }
5464 }
5465
Douglas Gregor0e558532009-02-11 16:16:59 +00005466 // -- For a non-type template-parameter of type pointer to data
5467 // member, qualification conversions (4.4) are applied.
5468 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5469
Douglas Gregor20fdef32012-04-10 17:08:25 +00005470 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5471 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005472 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005473 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005474}
5475
5476/// \brief Check a template argument against its corresponding
5477/// template template parameter.
5478///
5479/// This routine implements the semantics of C++ [temp.arg.template].
5480/// It returns true if an error occurred, and false otherwise.
5481bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005482 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005483 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005484 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005485 TemplateDecl *Template = Name.getAsTemplateDecl();
5486 if (!Template) {
5487 // Any dependent template name is fine.
5488 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5489 return false;
5490 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005491
Richard Smith3f1b5d02011-05-05 21:57:07 +00005492 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005493 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005494 // the name of a class template or an alias template, expressed as an
5495 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005496 // primary class templates are considered when matching the
5497 // template template argument with the corresponding parameter;
5498 // partial specializations are not considered even if their
5499 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005500 //
5501 // Note that we also allow template template parameters here, which
5502 // will happen when we are dealing with, e.g., class template
5503 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005504 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005505 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00005506 !isa<TypeAliasTemplateDecl>(Template) &&
5507 !isa<BuiltinTemplateDecl>(Template)) {
5508 assert(isa<FunctionTemplateDecl>(Template) &&
5509 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00005510 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00005511 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5512 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00005513 }
5514
Richard Smith1fde8ec2012-09-07 02:06:42 +00005515 TemplateParameterList *Params = Param->getTemplateParameters();
5516 if (Param->isExpandedParameterPack())
5517 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5518
Douglas Gregor85e0f662009-02-10 00:24:35 +00005519 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005520 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005521 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005522 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005523 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005524}
5525
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005526/// \brief Given a non-type template argument that refers to a
5527/// declaration and the type of its corresponding non-type template
5528/// parameter, produce an expression that properly refers to that
5529/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005530ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005531Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5532 QualType ParamType,
5533 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005534 // C++ [temp.param]p8:
5535 //
5536 // A non-type template-parameter of type "array of T" or
5537 // "function returning T" is adjusted to be of type "pointer to
5538 // T" or "pointer to function returning T", respectively.
5539 if (ParamType->isArrayType())
5540 ParamType = Context.getArrayDecayedType(ParamType);
5541 else if (ParamType->isFunctionType())
5542 ParamType = Context.getPointerType(ParamType);
5543
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005544 // For a NULL non-type template argument, return nullptr casted to the
5545 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005546 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005547 return ImpCastExprToType(
5548 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5549 ParamType,
5550 ParamType->getAs<MemberPointerType>()
5551 ? CK_NullToMemberPointer
5552 : CK_NullToPointer);
5553 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005554 assert(Arg.getKind() == TemplateArgument::Declaration &&
5555 "Only declaration template arguments permitted here");
5556
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005557 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5558
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005559 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005560 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5561 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005562 // If the value is a class member, we might have a pointer-to-member.
5563 // Determine whether the non-type template template parameter is of
5564 // pointer-to-member type. If so, we need to build an appropriate
5565 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5566 // would refer to the member itself.
5567 if (ParamType->isMemberPointerType()) {
5568 QualType ClassType
5569 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5570 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005571 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005572 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005573 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005574 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005575
5576 // The actual value-ness of this is unimportant, but for
5577 // internal consistency's sake, references to instance methods
5578 // are r-values.
5579 ExprValueKind VK = VK_LValue;
5580 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5581 VK = VK_RValue;
5582
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005583 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005584 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005585 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005586 Loc,
5587 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005588 if (RefExpr.isInvalid())
5589 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005590
John McCalle3027922010-08-25 11:45:40 +00005591 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005592
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005593 // We might need to perform a trailing qualification conversion, since
5594 // the element type on the parameter could be more qualified than the
5595 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005596 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005597 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005598 ParamType.getUnqualifiedType(), false,
5599 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005600 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005601
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005602 assert(!RefExpr.isInvalid() &&
5603 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005604 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005605 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005606 }
5607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005609 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005610
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005611 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005612 // When the non-type template parameter is a pointer, take the
5613 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005614 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005615 if (RefExpr.isInvalid())
5616 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005617
5618 if (T->isFunctionType() || T->isArrayType()) {
5619 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005620 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005621 if (RefExpr.isInvalid())
5622 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005623
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005624 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005626
Douglas Gregorb242683d2010-04-01 18:32:35 +00005627 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005628 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005629 }
5630
John McCall7decc9e2010-11-18 06:31:45 +00005631 ExprValueKind VK = VK_RValue;
5632
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005633 // If the non-type template parameter has reference type, qualify the
5634 // resulting declaration reference with the extra qualifiers on the
5635 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005636 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5637 VK = VK_LValue;
5638 T = Context.getQualifiedType(T,
5639 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005640 } else if (isa<FunctionDecl>(VD)) {
5641 // References to functions are always lvalues.
5642 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005644
John McCall7decc9e2010-11-18 06:31:45 +00005645 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005646}
5647
5648/// \brief Construct a new expression that refers to the given
5649/// integral template argument with the given source-location
5650/// information.
5651///
5652/// This routine takes care of the mapping from an integral template
5653/// argument (which may have any integral type) to the appropriate
5654/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005655ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005656Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5657 SourceLocation Loc) {
5658 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005659 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005660 QualType OrigT = Arg.getIntegralType();
5661
5662 // If this is an enum type that we're instantiating, we need to use an integer
5663 // type the same size as the enumerator. We don't want to build an
5664 // IntegerLiteral with enum type. The integer type of an enum type can be of
5665 // any integral type with C++11 enum classes, make sure we create the right
5666 // type of literal for it.
5667 QualType T = OrigT;
5668 if (const EnumType *ET = OrigT->getAs<EnumType>())
5669 T = ET->getDecl()->getIntegerType();
5670
5671 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005672 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005673 // This does not need to handle u8 character literals because those are
5674 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005675 CharacterLiteral::CharacterKind Kind;
5676 if (T->isWideCharType())
5677 Kind = CharacterLiteral::Wide;
5678 else if (T->isChar16Type())
5679 Kind = CharacterLiteral::UTF16;
5680 else if (T->isChar32Type())
5681 Kind = CharacterLiteral::UTF32;
5682 else
5683 Kind = CharacterLiteral::Ascii;
5684
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005685 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5686 Kind, T, Loc);
5687 } else if (T->isBooleanType()) {
5688 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5689 T, Loc);
5690 } else if (T->isNullPtrType()) {
5691 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5692 } else {
5693 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005694 }
5695
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005696 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005697 // FIXME: This is a hack. We need a better way to handle substituted
5698 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005699 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5700 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005701 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005702 Loc, Loc);
5703 }
5704
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005705 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005706}
5707
Douglas Gregor641040a2011-01-12 23:45:44 +00005708/// \brief Match two template parameters within template parameter lists.
5709static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5710 bool Complain,
5711 Sema::TemplateParameterListEqualKind Kind,
5712 SourceLocation TemplateArgLoc) {
5713 // Check the actual kind (type, non-type, template).
5714 if (Old->getKind() != New->getKind()) {
5715 if (Complain) {
5716 unsigned NextDiag = diag::err_template_param_different_kind;
5717 if (TemplateArgLoc.isValid()) {
5718 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5719 NextDiag = diag::note_template_param_different_kind;
5720 }
5721 S.Diag(New->getLocation(), NextDiag)
5722 << (Kind != Sema::TPL_TemplateMatch);
5723 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5724 << (Kind != Sema::TPL_TemplateMatch);
5725 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005726
Douglas Gregor641040a2011-01-12 23:45:44 +00005727 return false;
5728 }
5729
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005730 // Check that both are parameter packs are neither are parameter packs.
5731 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005732 // template template parameter, the template template parameter can have
5733 // a parameter pack where the template template argument does not.
5734 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5735 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5736 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005737 if (Complain) {
5738 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5739 if (TemplateArgLoc.isValid()) {
5740 S.Diag(TemplateArgLoc,
5741 diag::err_template_arg_template_params_mismatch);
5742 NextDiag = diag::note_template_parameter_pack_non_pack;
5743 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005744
Douglas Gregor641040a2011-01-12 23:45:44 +00005745 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5746 : isa<NonTypeTemplateParmDecl>(New)? 1
5747 : 2;
5748 S.Diag(New->getLocation(), NextDiag)
5749 << ParamKind << New->isParameterPack();
5750 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5751 << ParamKind << Old->isParameterPack();
5752 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753
Douglas Gregor641040a2011-01-12 23:45:44 +00005754 return false;
5755 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005756
Douglas Gregor641040a2011-01-12 23:45:44 +00005757 // For non-type template parameters, check the type of the parameter.
5758 if (NonTypeTemplateParmDecl *OldNTTP
5759 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5760 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005761
Douglas Gregor641040a2011-01-12 23:45:44 +00005762 // If we are matching a template template argument to a template
5763 // template parameter and one of the non-type template parameter types
5764 // is dependent, then we must wait until template instantiation time
5765 // to actually compare the arguments.
5766 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5767 (OldNTTP->getType()->isDependentType() ||
5768 NewNTTP->getType()->isDependentType()))
5769 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005770
Douglas Gregor641040a2011-01-12 23:45:44 +00005771 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5772 if (Complain) {
5773 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5774 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005775 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005776 diag::err_template_arg_template_params_mismatch);
5777 NextDiag = diag::note_template_nontype_parm_different_type;
5778 }
5779 S.Diag(NewNTTP->getLocation(), NextDiag)
5780 << NewNTTP->getType()
5781 << (Kind != Sema::TPL_TemplateMatch);
5782 S.Diag(OldNTTP->getLocation(),
5783 diag::note_template_nontype_parm_prev_declaration)
5784 << OldNTTP->getType();
5785 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005786
Douglas Gregor641040a2011-01-12 23:45:44 +00005787 return false;
5788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005789
Douglas Gregor641040a2011-01-12 23:45:44 +00005790 return true;
5791 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005792
Douglas Gregor641040a2011-01-12 23:45:44 +00005793 // For template template parameters, check the template parameter types.
5794 // The template parameter lists of template template
5795 // parameters must agree.
5796 if (TemplateTemplateParmDecl *OldTTP
5797 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005798 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005799 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5800 OldTTP->getTemplateParameters(),
5801 Complain,
5802 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005803 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005804 : Kind),
5805 TemplateArgLoc);
5806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005807
Douglas Gregor641040a2011-01-12 23:45:44 +00005808 return true;
5809}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005810
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005811/// \brief Diagnose a known arity mismatch when comparing template argument
5812/// lists.
5813static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005814void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005815 TemplateParameterList *New,
5816 TemplateParameterList *Old,
5817 Sema::TemplateParameterListEqualKind Kind,
5818 SourceLocation TemplateArgLoc) {
5819 unsigned NextDiag = diag::err_template_param_list_different_arity;
5820 if (TemplateArgLoc.isValid()) {
5821 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5822 NextDiag = diag::note_template_param_list_different_arity;
5823 }
5824 S.Diag(New->getTemplateLoc(), NextDiag)
5825 << (New->size() > Old->size())
5826 << (Kind != Sema::TPL_TemplateMatch)
5827 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5828 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5829 << (Kind != Sema::TPL_TemplateMatch)
5830 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5831}
5832
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005833/// \brief Determine whether the given template parameter lists are
5834/// equivalent.
5835///
Mike Stump11289f42009-09-09 15:08:12 +00005836/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005837/// source code as part of a new template declaration.
5838///
5839/// \param Old The old template parameter list, typically found via
5840/// name lookup of the template declared with this template parameter
5841/// list.
5842///
5843/// \param Complain If true, this routine will produce a diagnostic if
5844/// the template parameter lists are not equivalent.
5845///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005846/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005847///
5848/// \param TemplateArgLoc If this source location is valid, then we
5849/// are actually checking the template parameter list of a template
5850/// argument (New) against the template parameter list of its
5851/// corresponding template template parameter (Old). We produce
5852/// slightly different diagnostics in this scenario.
5853///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005854/// \returns True if the template parameter lists are equal, false
5855/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005856bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005857Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5858 TemplateParameterList *Old,
5859 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005860 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005861 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005862 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5863 if (Complain)
5864 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5865 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005866
5867 return false;
5868 }
5869
Douglas Gregor641040a2011-01-12 23:45:44 +00005870 // C++0x [temp.arg.template]p3:
5871 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005872 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005873 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005874 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005875 // template-parameter-list of P. [...]
5876 TemplateParameterList::iterator NewParm = New->begin();
5877 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005878 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005879 OldParmEnd = Old->end();
5880 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005881 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5882 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005883 if (NewParm == NewParmEnd) {
5884 if (Complain)
5885 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5886 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005887
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005888 return false;
5889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005890
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005891 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5892 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005893 return false;
5894
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005895 ++NewParm;
5896 continue;
5897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005898
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005899 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005900 // [...] When P's template- parameter-list contains a template parameter
5901 // pack (14.5.3), the template parameter pack will match zero or more
5902 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005903 // template-parameter-list of A with the same type and form as the
5904 // template parameter pack in P (ignoring whether those template
5905 // parameters are template parameter packs).
5906 for (; NewParm != NewParmEnd; ++NewParm) {
5907 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5908 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005909 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005910 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005911 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005912
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005913 // Make sure we exhausted all of the arguments.
5914 if (NewParm != NewParmEnd) {
5915 if (Complain)
5916 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5917 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005918
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005919 return false;
5920 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005921
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005922 return true;
5923}
5924
5925/// \brief Check whether a template can be declared within this scope.
5926///
5927/// If the template declaration is valid in this scope, returns
5928/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005929bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005930Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005931 if (!S)
5932 return false;
5933
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005934 // Find the nearest enclosing declaration scope.
5935 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5936 (S->getFlags() & Scope::TemplateParamScope) != 0)
5937 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005938
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005939 // C++ [temp]p4:
5940 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005941 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00005942 if (Ctx && Ctx->isExternCContext()) {
5943 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5944 << TemplateParams->getSourceRange();
5945 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
5946 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
5947 return true;
5948 }
Richard Smith8df390f2016-09-08 23:14:54 +00005949 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005950
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005951 // C++ [temp]p2:
5952 // A template-declaration can appear only as a namespace scope or
5953 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005954 if (Ctx) {
5955 if (Ctx->isFileContext())
5956 return false;
5957 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5958 // C++ [temp.mem]p2:
5959 // A local class shall not have member templates.
5960 if (RD->isLocalClass())
5961 return Diag(TemplateParams->getTemplateLoc(),
5962 diag::err_template_inside_local_class)
5963 << TemplateParams->getSourceRange();
5964 else
5965 return false;
5966 }
5967 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005968
Mike Stump11289f42009-09-09 15:08:12 +00005969 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005970 diag::err_template_outside_namespace_or_class_scope)
5971 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005972}
Douglas Gregor67a65642009-02-17 23:15:12 +00005973
Douglas Gregor54888652009-10-07 00:13:32 +00005974/// \brief Determine what kind of template specialization the given declaration
5975/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005976static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005977 if (!D)
5978 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005979
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005980 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5981 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005982 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5983 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005984 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5985 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005986
Douglas Gregor54888652009-10-07 00:13:32 +00005987 return TSK_Undeclared;
5988}
5989
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005990/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005991/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005992///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005993/// This routine determines whether a template specialization can be declared
5994/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005995///
5996/// \param S the semantic analysis object for which this check is being
5997/// performed.
5998///
5999/// \param Specialized the entity being specialized or instantiated, which
6000/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006001/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00006002/// member class).
6003///
6004/// \param PrevDecl the previous declaration of this entity, if any.
6005///
6006/// \param Loc the location of the explicit specialization or instantiation of
6007/// this entity.
6008///
6009/// \param IsPartialSpecialization whether this is a partial specialization of
6010/// a class template.
6011///
Douglas Gregor54888652009-10-07 00:13:32 +00006012/// \returns true if there was an error that we cannot recover from, false
6013/// otherwise.
6014static bool CheckTemplateSpecializationScope(Sema &S,
6015 NamedDecl *Specialized,
6016 NamedDecl *PrevDecl,
6017 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006018 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00006019 // Keep these "kind" numbers in sync with the %select statements in the
6020 // various diagnostics emitted by this routine.
6021 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006022 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006023 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006024 else if (isa<VarTemplateDecl>(Specialized))
6025 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006026 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006027 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006028 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006029 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006030 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00006031 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006032 else if (isa<RecordDecl>(Specialized))
6033 EntityKind = 7;
6034 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6035 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00006036 else {
Richard Smith7d137e32012-03-23 03:33:32 +00006037 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006038 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006039 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00006040 return true;
6041 }
6042
Douglas Gregorf47b9112009-02-25 22:02:03 +00006043 // C++ [temp.expl.spec]p2:
6044 // An explicit specialization shall be declared in the namespace
6045 // of which the template is a member, or, for member templates, in
6046 // the namespace of which the enclosing class or enclosing class
6047 // template is a member. An explicit specialization of a member
6048 // function, member class or static data member of a class
6049 // template shall be declared in the namespace of which the class
6050 // template is a member. Such a declaration may also be a
6051 // definition. If the declaration is not a definition, the
6052 // specialization may be defined later in the name- space in which
6053 // the explicit specialization was declared, or in a namespace
6054 // that encloses the one in which the explicit specialization was
6055 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00006056 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00006057 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006058 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006059 return true;
6060 }
Douglas Gregore4b05162009-10-07 17:21:34 +00006061
Douglas Gregor40fb7442009-10-07 17:30:37 +00006062 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006063 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006064 // Do not warn for class scope explicit specialization during
6065 // instantiation, warning was already emitted during pattern
6066 // semantic analysis.
6067 if (!S.ActiveTemplateInstantiations.size())
6068 S.Diag(Loc, diag::ext_function_specialization_in_class)
6069 << Specialized;
6070 } else {
6071 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6072 << Specialized;
6073 return true;
6074 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006076
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006077 if (S.CurContext->isRecord() &&
6078 !S.CurContext->Equals(Specialized->getDeclContext())) {
6079 // Make sure that we're specializing in the right record context.
6080 // Otherwise, things can go horribly wrong.
6081 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6082 << Specialized;
6083 return true;
6084 }
6085
Douglas Gregore4b05162009-10-07 17:21:34 +00006086 // C++ [temp.class.spec]p6:
6087 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006088 // in any namespace scope in which its definition may be defined (14.5.1
6089 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00006090 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00006091 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00006092 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00006093
6094 // Make sure that this redeclaration (or definition) occurs in an enclosing
6095 // namespace.
6096 // Note that HandleDeclarator() performs this check for explicit
6097 // specializations of function templates, static data members, and member
6098 // functions, so we skip the check here for those kinds of entities.
6099 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6100 // Should we refactor that check, so that it occurs later?
6101 if (!DC->Encloses(SpecializedContext) &&
6102 !(isa<FunctionTemplateDecl>(Specialized) ||
6103 isa<FunctionDecl>(Specialized) ||
6104 isa<VarTemplateDecl>(Specialized) ||
6105 isa<VarDecl>(Specialized))) {
6106 if (isa<TranslationUnitDecl>(SpecializedContext))
6107 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6108 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00006109 else if (isa<NamespaceDecl>(SpecializedContext)) {
6110 int Diag = diag::err_template_spec_redecl_out_of_scope;
6111 if (S.getLangOpts().MicrosoftExt)
6112 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6113 S.Diag(Loc, Diag) << EntityKind << Specialized
6114 << cast<NamedDecl>(SpecializedContext);
6115 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00006116 llvm_unreachable("unexpected namespace context for specialization");
6117
6118 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6119 } else if ((!PrevDecl ||
6120 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6121 getTemplateSpecializationKind(PrevDecl) ==
6122 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006123 // C++ [temp.exp.spec]p2:
6124 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006125 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006126 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006127 // An explicit specialization of a member function, member class or
6128 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006129 // namespace of which the class template is a member.
6130 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006131 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006132 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006133 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006134 // C++11 [temp.explicit]p3:
6135 // An explicit instantiation shall appear in an enclosing namespace of its
6136 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006137 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006138 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006139 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006140 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006141 "DC encloses TU but isn't in enclosing namespace set");
6142 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006143 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006144 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6145 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006146 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006147 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006148 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006149 Diag = diag::ext_template_spec_decl_out_of_scope;
6150 else
6151 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6152 S.Diag(Loc, Diag)
6153 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6154 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006155
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006156 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006157 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006159
Douglas Gregorf47b9112009-02-25 22:02:03 +00006160 return false;
6161}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006162
Richard Smith6056d5e2014-02-09 00:54:43 +00006163static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
6164 if (!E->isInstantiationDependent())
6165 return SourceLocation();
6166 DependencyChecker Checker(Depth);
6167 Checker.TraverseStmt(E);
6168 if (Checker.Match && Checker.MatchLoc.isInvalid())
6169 return E->getSourceRange();
6170 return Checker.MatchLoc;
6171}
6172
6173static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6174 if (!TL.getType()->isDependentType())
6175 return SourceLocation();
6176 DependencyChecker Checker(Depth);
6177 Checker.TraverseTypeLoc(TL);
6178 if (Checker.Match && Checker.MatchLoc.isInvalid())
6179 return TL.getSourceRange();
6180 return Checker.MatchLoc;
6181}
6182
Larisse Voufo39a1e502013-08-06 01:03:05 +00006183/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006184/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006185static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006186 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6187 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006188 for (unsigned I = 0; I != NumArgs; ++I) {
6189 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006190 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006191 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6192 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006193 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006194
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006195 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006197
Eli Friedmanb826a002012-09-26 02:36:12 +00006198 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006199 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006200
6201 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006202
Douglas Gregor98318c22011-01-03 21:37:45 +00006203 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006204 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6205 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006206
6207 // Strip off any implicit casts we added as part of type checking.
6208 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6209 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006210
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006211 // C++ [temp.class.spec]p8:
6212 // A non-type argument is non-specialized if it is the name of a
6213 // non-type parameter. All other non-type arguments are
6214 // specialized.
6215 //
6216 // Below, we check the two conditions that only apply to
6217 // specialized non-type arguments, so skip any non-specialized
6218 // arguments.
6219 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006220 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006221 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006222
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006223 // C++ [temp.class.spec]p9:
6224 // Within the argument list of a class template partial
6225 // specialization, the following restrictions apply:
6226 // -- A partially specialized non-type argument expression
6227 // shall not involve a template parameter of the partial
6228 // specialization except when the argument expression is a
6229 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006230 SourceRange ParamUseRange =
6231 findTemplateParameter(Param->getDepth(), ArgExpr);
6232 if (ParamUseRange.isValid()) {
6233 if (IsDefaultArgument) {
6234 S.Diag(TemplateNameLoc,
6235 diag::err_dependent_non_type_arg_in_partial_spec);
6236 S.Diag(ParamUseRange.getBegin(),
6237 diag::note_dependent_non_type_default_arg_in_partial_spec)
6238 << ParamUseRange;
6239 } else {
6240 S.Diag(ParamUseRange.getBegin(),
6241 diag::err_dependent_non_type_arg_in_partial_spec)
6242 << ParamUseRange;
6243 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006244 return true;
6245 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006246
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006247 // -- The type of a template parameter corresponding to a
6248 // specialized non-type argument shall not be dependent on a
6249 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006250 //
6251 // FIXME: We need to delay this check until instantiation in some cases:
6252 //
6253 // template<template<typename> class X> struct A {
6254 // template<typename T, X<T> N> struct B;
6255 // template<typename T> struct B<T, 0>;
6256 // };
6257 // template<typename> using X = int;
6258 // A<X>::B<int, 0> b;
6259 ParamUseRange = findTemplateParameter(
6260 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6261 if (ParamUseRange.isValid()) {
6262 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6263 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6264 << Param->getType() << ParamUseRange;
6265 S.Diag(Param->getLocation(), diag::note_template_param_here)
6266 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006267 return true;
6268 }
6269 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006270
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006271 return false;
6272}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006273
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006274/// \brief Check the non-type template arguments of a class template
6275/// partial specialization according to C++ [temp.class.spec]p9.
6276///
Richard Smith6056d5e2014-02-09 00:54:43 +00006277/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006278/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006279/// template.
6280/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006281/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006282/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006283///
Richard Smith6056d5e2014-02-09 00:54:43 +00006284/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006285static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006286 Sema &S, SourceLocation TemplateNameLoc,
6287 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006288 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006289 const TemplateArgument *ArgList = TemplateArgs.data();
6290
6291 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6292 NonTypeTemplateParmDecl *Param
6293 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6294 if (!Param)
6295 continue;
6296
Richard Smith6056d5e2014-02-09 00:54:43 +00006297 if (CheckNonTypeTemplatePartialSpecializationArgs(
6298 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006299 return true;
6300 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006301
6302 return false;
6303}
6304
John McCall48871652010-08-21 09:40:31 +00006305DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006306Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6307 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006308 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006309 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006310 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006311 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006312 MultiTemplateParamsArg
6313 TemplateParameterLists,
6314 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006315 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006316
Richard Smith4b55a9c2014-04-17 03:29:33 +00006317 CXXScopeSpec &SS = TemplateId.SS;
6318
Abramo Bagnara60804e12011-03-18 15:16:37 +00006319 // NOTE: KWLoc is the location of the tag keyword. This will instead
6320 // store the location of the outermost template keyword in the declaration.
6321 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006322 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6323 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6324 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6325 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006326
Douglas Gregor67a65642009-02-17 23:15:12 +00006327 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006328 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006329 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006330 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6331
6332 if (!ClassTemplate) {
6333 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006334 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006335 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6336 return true;
6337 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006338
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006339 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006340 bool isPartialSpecialization = false;
6341
Douglas Gregorf47b9112009-02-25 22:02:03 +00006342 // Check the validity of the template headers that introduce this
6343 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006344 // FIXME: We probably shouldn't complain about these headers for
6345 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006346 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006347 TemplateParameterList *TemplateParams =
6348 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006349 KWLoc, TemplateNameLoc, SS, &TemplateId,
6350 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6351 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006352 if (Invalid)
6353 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006354
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006355 if (TemplateParams && TemplateParams->size() > 0) {
6356 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006357
Douglas Gregorec9518b2010-12-21 08:14:57 +00006358 if (TUK == TUK_Friend) {
6359 Diag(KWLoc, diag::err_partial_specialization_friend)
6360 << SourceRange(LAngleLoc, RAngleLoc);
6361 return true;
6362 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006363
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006364 // C++ [temp.class.spec]p10:
6365 // The template parameter list of a specialization shall not
6366 // contain default template argument values.
6367 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6368 Decl *Param = TemplateParams->getParam(I);
6369 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6370 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006371 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006372 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006373 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006374 }
6375 } else if (NonTypeTemplateParmDecl *NTTP
6376 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6377 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006378 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006379 diag::err_default_arg_in_partial_spec)
6380 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006381 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006382 }
6383 } else {
6384 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006385 if (TTP->hasDefaultArgument()) {
6386 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006387 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006388 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006389 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006390 }
6391 }
6392 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006393 } else if (TemplateParams) {
6394 if (TUK == TUK_Friend)
6395 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006396 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006397 SourceRange(TemplateParams->getTemplateLoc(),
6398 TemplateParams->getRAngleLoc()))
6399 << SourceRange(LAngleLoc, RAngleLoc);
6400 else
6401 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006402 } else {
6403 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006404 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006405
Douglas Gregor67a65642009-02-17 23:15:12 +00006406 // Check that the specialization uses the same tag kind as the
6407 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006408 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6409 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006410 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006411 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006412 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006413 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006414 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006415 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006416 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006417 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006418 diag::note_previous_use);
6419 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6420 }
6421
Douglas Gregorc40290e2009-03-09 23:48:35 +00006422 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006423 TemplateArgumentListInfo TemplateArgs =
6424 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006425
Douglas Gregor14406932011-01-03 20:35:03 +00006426 // Check for unexpanded parameter packs in any of the template arguments.
6427 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006428 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006429 UPPC_PartialSpecialization))
6430 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006431
Douglas Gregor67a65642009-02-17 23:15:12 +00006432 // Check that the template argument list is well-formed for this
6433 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006434 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006435 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6436 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006437 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006438
Douglas Gregor2373c592009-05-31 09:31:02 +00006439 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006440 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006441 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006442 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006443 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6444 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006445 return true;
6446
Douglas Gregor678d76c2011-07-01 01:22:09 +00006447 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006448 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006449 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00006450 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006451 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6452 << ClassTemplate->getDeclName();
6453 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006454 }
6455 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006456
Craig Topperc3ec1492014-05-26 06:22:03 +00006457 void *InsertPos = nullptr;
6458 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006459
6460 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006461 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006462 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006463 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006464 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006465
Craig Topperc3ec1492014-05-26 06:22:03 +00006466 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006467
Douglas Gregorf47b9112009-02-25 22:02:03 +00006468 // Check whether we can declare a class template specialization in
6469 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006470 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006471 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6472 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006473 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006474 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006475
Douglas Gregor15301382009-07-30 17:40:51 +00006476 // The canonical type
6477 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006478 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006479 // Build the canonical type that describes the converted template
6480 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006481 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6482 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00006483 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006484
6485 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006486 ClassTemplate->getInjectedClassNameSpecialization())) {
6487 // C++ [temp.class.spec]p9b3:
6488 //
6489 // -- The argument list of the specialization shall not be identical
6490 // to the implicit argument list of the primary template.
6491 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006492 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006493 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006494 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6495 ClassTemplate->getIdentifier(),
6496 TemplateNameLoc,
6497 Attr,
6498 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006499 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006500 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006501 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006502 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006503 }
Douglas Gregor15301382009-07-30 17:40:51 +00006504
Douglas Gregor2373c592009-05-31 09:31:02 +00006505 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006506 ClassTemplatePartialSpecializationDecl *PrevPartial
6507 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006508 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006509 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006510 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006511 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006512 TemplateParams,
6513 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006514 Converted,
John McCall6b51f282009-11-23 01:53:49 +00006515 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006516 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006517 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006518 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006519 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006520 Partial->setTemplateParameterListsInfo(
6521 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006522 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006523
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006524 if (!PrevPartial)
6525 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006526 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006527
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006528 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006529 // template specialization, make a note of that.
6530 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6531 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006532
Douglas Gregor91772d12009-06-13 00:26:55 +00006533 // Check that all of the template parameters of the class template
6534 // partial specialization are deducible from the template
6535 // arguments. If not, this class template partial specialization
6536 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006537 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006538 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006539 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006540 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006541
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006542 if (!DeducibleParams.all()) {
6543 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006544 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006545 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006546 << SourceRange(TemplateNameLoc, RAngleLoc);
6547 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6548 if (!DeducibleParams[I]) {
6549 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6550 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006551 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006552 diag::note_partial_spec_unused_parameter)
6553 << Param->getDeclName();
6554 else
Mike Stump11289f42009-09-09 15:08:12 +00006555 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006556 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006557 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006558 }
6559 }
6560 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006561 } else {
6562 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006563 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006564 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006565 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006566 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006567 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006568 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006569 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00006570 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006571 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006572 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006573 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006574 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006575 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006576
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006577 if (!PrevDecl)
6578 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006579
David Majnemer678f50b2015-11-18 19:49:19 +00006580 if (CurContext->isDependentContext()) {
6581 // -fms-extensions permits specialization of nested classes without
6582 // fully specializing the outer class(es).
6583 assert(getLangOpts().MicrosoftExt &&
6584 "Only possible with -fms-extensions!");
6585 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6586 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00006587 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00006588 } else {
6589 CanonType = Context.getTypeDeclType(Specialization);
6590 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006591 }
6592
Douglas Gregor06db9f52009-10-12 20:18:28 +00006593 // C++ [temp.expl.spec]p6:
6594 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006595 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006596 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006597 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006598 // use occurs; no diagnostic is required.
6599 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006600 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006601 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006602 // Is there any previous explicit specialization declaration?
6603 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6604 Okay = true;
6605 break;
6606 }
6607 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006608
Douglas Gregorc854c662010-02-26 06:03:23 +00006609 if (!Okay) {
6610 SourceRange Range(TemplateNameLoc, RAngleLoc);
6611 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6612 << Context.getTypeDeclType(Specialization) << Range;
6613
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006614 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006615 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006616 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006617 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006618 return true;
6619 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006621
Douglas Gregor2208a292009-09-26 20:57:03 +00006622 // If this is not a friend, note that this is an explicit specialization.
6623 if (TUK != TUK_Friend)
6624 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006625
6626 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006627 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006628 RecordDecl *Def = Specialization->getDefinition();
6629 NamedDecl *Hidden = nullptr;
6630 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6631 SkipBody->ShouldSkip = true;
6632 makeMergedDefinitionVisible(Hidden, KWLoc);
6633 // From here on out, treat this as just a redeclaration.
6634 TUK = TUK_Declaration;
6635 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006636 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006637 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006638 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006639 Diag(Def->getLocation(), diag::note_previous_definition);
6640 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006641 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006642 }
6643 }
6644
John McCall659a3372010-12-18 03:30:47 +00006645 if (Attr)
6646 ProcessDeclAttributeList(S, Specialization, Attr);
6647
Richard Smith034b94a2012-08-17 03:20:55 +00006648 // Add alignment attributes if necessary; these attributes are checked when
6649 // the ASTContext lays out the structure.
6650 if (TUK == TUK_Definition) {
6651 AddAlignmentAttributesForRecord(Specialization);
6652 AddMsStructLayoutForRecord(Specialization);
6653 }
6654
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006655 if (ModulePrivateLoc.isValid())
6656 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6657 << (isPartialSpecialization? 1 : 0)
6658 << FixItHint::CreateRemoval(ModulePrivateLoc);
6659
Douglas Gregord56a91e2009-02-26 22:19:44 +00006660 // Build the fully-sugared type for this class template
6661 // specialization as the user wrote in the specialization
6662 // itself. This means that we'll pretty-print the type retrieved
6663 // from the specialization's declaration the way that the user
6664 // actually wrote the specialization, rather than formatting the
6665 // name based on the "canonical" representation used to store the
6666 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006667 TypeSourceInfo *WrittenTy
6668 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6669 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006670 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006671 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006672 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006673 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006674
Douglas Gregor1e249f82009-02-25 22:18:32 +00006675 // C++ [temp.expl.spec]p9:
6676 // A template explicit specialization is in the scope of the
6677 // namespace in which the template was defined.
6678 //
6679 // We actually implement this paragraph where we set the semantic
6680 // context (in the creation of the ClassTemplateSpecializationDecl),
6681 // but we also maintain the lexical context where the actual
6682 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006683 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006684
Douglas Gregor67a65642009-02-17 23:15:12 +00006685 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006686 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006687 Specialization->startDefinition();
6688
Douglas Gregor2208a292009-09-26 20:57:03 +00006689 if (TUK == TUK_Friend) {
6690 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6691 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006692 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006693 /*FIXME:*/KWLoc);
6694 Friend->setAccess(AS_public);
6695 CurContext->addDecl(Friend);
6696 } else {
6697 // Add the specialization into its lexical context, so that it can
6698 // be seen when iterating through the list of declarations in that
6699 // context. However, specializations are not found by name lookup.
6700 CurContext->addDecl(Specialization);
6701 }
John McCall48871652010-08-21 09:40:31 +00006702 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006703}
Douglas Gregor333489b2009-03-27 23:10:48 +00006704
John McCall48871652010-08-21 09:40:31 +00006705Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006706 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006707 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006708 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006709 ActOnDocumentableDecl(NewDecl);
6710 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006711}
6712
John McCall4f7ced62010-02-11 01:33:53 +00006713/// \brief Strips various properties off an implicit instantiation
6714/// that has just been explicitly specialized.
6715static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006716 D->dropAttr<DLLImportAttr>();
6717 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006718
Nico Webere4974382014-12-19 23:52:45 +00006719 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006720 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006721}
6722
Nico Webera8f80b32012-01-09 19:52:25 +00006723/// \brief Compute the diagnostic location for an explicit instantiation
6724// declaration or definition.
6725static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006726 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006727 // Explicit instantiations following a specialization have no effect and
6728 // hence no PointOfInstantiation. In that case, walk decl backwards
6729 // until a valid name loc is found.
6730 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006731 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6732 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006733 PrevDiagLoc = Prev->getLocation();
6734 }
6735 assert(PrevDiagLoc.isValid() &&
6736 "Explicit instantiation without point of instantiation?");
6737 return PrevDiagLoc;
6738}
6739
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006740/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006741/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006742/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006743/// new specialization/instantiation will have any effect.
6744///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006745/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006746/// instantiation.
6747///
6748/// \param NewTSK the kind of the new explicit specialization or instantiation.
6749///
6750/// \param PrevDecl the previous declaration of the entity.
6751///
6752/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6753///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006754/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006755/// declaration was instantiated (either implicitly or explicitly).
6756///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006757/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006758/// specialization or instantiation has no effect and should be ignored.
6759///
6760/// \returns true if there was an error that should prevent the introduction of
6761/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006762bool
6763Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6764 TemplateSpecializationKind NewTSK,
6765 NamedDecl *PrevDecl,
6766 TemplateSpecializationKind PrevTSK,
6767 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006768 bool &HasNoEffect) {
6769 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006771 switch (NewTSK) {
6772 case TSK_Undeclared:
6773 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006774 assert(
6775 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6776 "previous declaration must be implicit!");
6777 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006778
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006779 case TSK_ExplicitSpecialization:
6780 switch (PrevTSK) {
6781 case TSK_Undeclared:
6782 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006783 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006784 // explicitly specialized or has merely been mentioned without any
6785 // instantiation.
6786 return false;
6787
6788 case TSK_ImplicitInstantiation:
6789 if (PrevPointOfInstantiation.isInvalid()) {
6790 // The declaration itself has not actually been instantiated, so it is
6791 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006792 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006793 return false;
6794 }
6795 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006796
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006797 case TSK_ExplicitInstantiationDeclaration:
6798 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006799 assert((PrevTSK == TSK_ImplicitInstantiation ||
6800 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006801 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006802
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006803 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006804 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006805 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006806 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006807 // implicit instantiation to take place, in every translation unit in
6808 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006809 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006810 // Is there any previous explicit specialization declaration?
6811 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6812 return false;
6813 }
6814
Douglas Gregor1d957a32009-10-27 18:42:08 +00006815 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006816 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006817 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006818 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006819
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006820 return true;
6821 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006822
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006823 case TSK_ExplicitInstantiationDeclaration:
6824 switch (PrevTSK) {
6825 case TSK_ExplicitInstantiationDeclaration:
6826 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006827 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006828 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006829
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006830 case TSK_Undeclared:
6831 case TSK_ImplicitInstantiation:
6832 // We're explicitly instantiating something that may have already been
6833 // implicitly instantiated; that's fine.
6834 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006835
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006836 case TSK_ExplicitSpecialization:
6837 // C++0x [temp.explicit]p4:
6838 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006839 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006840 // specialization for that template, the explicit instantiation has no
6841 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006842 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006843 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006844
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006845 case TSK_ExplicitInstantiationDefinition:
6846 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006847 // If an entity is the subject of both an explicit instantiation
6848 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006849 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006850 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006851 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006852
6853 // Explicit instantiations following a specialization have no effect and
6854 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6855 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006856 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6857 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006858 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006859 return false;
6860 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006861
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006862 case TSK_ExplicitInstantiationDefinition:
6863 switch (PrevTSK) {
6864 case TSK_Undeclared:
6865 case TSK_ImplicitInstantiation:
6866 // We're explicitly instantiating something that may have already been
6867 // implicitly instantiated; that's fine.
6868 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006869
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006870 case TSK_ExplicitSpecialization:
6871 // C++ DR 259, C++0x [temp.explicit]p4:
6872 // For a given set of template parameters, if an explicit
6873 // instantiation of a template appears after a declaration of
6874 // an explicit specialization for that template, the explicit
6875 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00006876 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006877 << PrevDecl;
6878 Diag(PrevDecl->getLocation(),
6879 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006880 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006881 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006882
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006883 case TSK_ExplicitInstantiationDeclaration:
6884 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006885 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006886
6887 // C++0x [temp.explicit]p4:
6888 // For a given set of template parameters, if an explicit instantiation
6889 // of a template appears after a declaration of an explicit
6890 // specialization for that template, the explicit instantiation has no
6891 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006892 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006893 // Is there any previous explicit specialization declaration?
6894 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6895 HasNoEffect = true;
6896 break;
6897 }
6898 }
6899
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006900 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006901
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006902 case TSK_ExplicitInstantiationDefinition:
6903 // C++0x [temp.spec]p5:
6904 // For a given template and a given set of template-arguments,
6905 // - an explicit instantiation definition shall appear at most once
6906 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006907
6908 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6909 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006910 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006911 : diag::err_explicit_instantiation_duplicate)
6912 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006913 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006914 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006915 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006916 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006917 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006918 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006919
David Blaikie83d382b2011-09-23 05:06:16 +00006920 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006921}
6922
John McCallb9c78482010-04-08 09:05:18 +00006923/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006924/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006925///
James Dennettf14a6e52012-06-15 22:23:43 +00006926/// The only possible way to get a dependent function template specialization
6927/// is with a friend declaration, like so:
6928///
6929/// \code
6930/// template \<class T> void foo(T);
6931/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006932/// friend void foo<>(T);
6933/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006934/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006935///
6936/// There really isn't any useful analysis we can do here, so we
6937/// just store the information.
6938bool
6939Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6940 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6941 LookupResult &Previous) {
6942 // Remove anything from Previous that isn't a function template in
6943 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006944 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006945 LookupResult::Filter F = Previous.makeFilter();
6946 while (F.hasNext()) {
6947 NamedDecl *D = F.next()->getUnderlyingDecl();
6948 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006949 !FDLookupContext->InEnclosingNamespaceSetOf(
6950 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006951 F.erase();
6952 }
6953 F.done();
6954
6955 // Should this be diagnosed here?
6956 if (Previous.empty()) return true;
6957
6958 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6959 ExplicitTemplateArgs);
6960 return false;
6961}
6962
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006963/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006964/// specialization.
6965///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006966/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006967/// explicit function template specialization. On successful completion,
6968/// the function declaration \p FD will become a function template
6969/// specialization.
6970///
6971/// \param FD the function declaration, which will be updated to become a
6972/// function template specialization.
6973///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006974/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6975/// if any. Note that this may be valid info even when 0 arguments are
6976/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6977/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006978///
Francois Pichet3a44e432011-07-08 06:21:47 +00006979/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006980/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006981bool Sema::CheckFunctionTemplateSpecialization(
6982 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6983 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006984 // The set of function template specializations that could match this
6985 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006986 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006987 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6988 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006989
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006990 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6991 ConvertedTemplateArgs;
6992
Sebastian Redl50c68252010-08-31 00:36:30 +00006993 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006994 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6995 I != E; ++I) {
6996 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6997 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006998 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006999 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007000 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7001 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007002 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007003
Richard Smith574f4f62013-01-14 05:37:29 +00007004 // When matching a constexpr member function template specialization
7005 // against the primary template, we don't yet know whether the
7006 // specialization has an implicit 'const' (because we don't know whether
7007 // it will be a static member function until we know which template it
7008 // specializes), so adjust it now assuming it specializes this template.
7009 QualType FT = FD->getType();
7010 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007011 CXXMethodDecl *OldMD =
7012 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00007013 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007014 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00007015 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7016 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007017 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007018 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00007019 }
7020 }
7021
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007022 TemplateArgumentListInfo Args;
7023 if (ExplicitTemplateArgs)
7024 Args = *ExplicitTemplateArgs;
7025
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007026 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007027 // A trailing template-argument can be left unspecified in the
7028 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007029 // provided it can be deduced from the function argument type.
7030 // Perform template argument deduction to determine whether we may be
7031 // specializing this template.
7032 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00007033 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007034 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00007035 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7036 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00007037 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7038 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007039 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007040 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00007041 FailedCandidates.addCandidate().set(
7042 I.getPair(), FunTmpl->getTemplatedDecl(),
7043 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007044 (void)TDK;
7045 continue;
7046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007047
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007048 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007049 if (ExplicitTemplateArgs)
7050 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00007051 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007052 }
7053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007054
Douglas Gregor5de279c2009-09-26 03:41:46 +00007055 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007056 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007057 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007058 FD->getLocation(),
7059 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7060 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00007061 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007062 PDiag(diag::note_function_template_spec_matched));
7063
John McCall58cc69d2010-01-27 01:50:18 +00007064 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007065 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007066
7067 // Ignore access information; it doesn't figure into redeclaration checking.
7068 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007069
Nathan Wilson83839122016-04-09 02:55:27 +00007070 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7071 // an explicit specialization (14.8.3) [...] of a concept definition.
7072 if (Specialization->getPrimaryTemplate()->isConcept()) {
7073 Diag(FD->getLocation(), diag::err_concept_specialized)
7074 << 0 /*function*/ << 1 /*explicitly specialized*/;
7075 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7076 return true;
7077 }
7078
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007079 FunctionTemplateSpecializationInfo *SpecInfo
7080 = Specialization->getTemplateSpecializationInfo();
7081 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007082
7083 // Note: do not overwrite location info if previous template
7084 // specialization kind was explicit.
7085 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00007086 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00007087 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00007088 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7089 // function can differ from the template declaration with respect to
7090 // the constexpr specifier.
7091 Specialization->setConstexpr(FD->isConstexpr());
7092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007093
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007094 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00007095 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00007096
7097 // If this is a friend declaration, then we're not really declaring
7098 // an explicit specialization.
7099 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007100
Douglas Gregor54888652009-10-07 00:13:32 +00007101 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00007102 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007103 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00007104 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007105 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007106 false))
Douglas Gregor54888652009-10-07 00:13:32 +00007107 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007108
7109 // C++ [temp.expl.spec]p6:
7110 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007111 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007112 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007113 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007114 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007115 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007116 if (!isFriend &&
7117 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007118 TSK_ExplicitSpecialization,
7119 Specialization,
7120 SpecInfo->getTemplateSpecializationKind(),
7121 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007122 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007123 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007124
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007125 // Mark the prior declaration as an explicit specialization, so that later
7126 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007127 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007128 // Since explicit specializations do not inherit '=delete' from their
7129 // primary function template - check if the 'specialization' that was
7130 // implicitly generated (during template argument deduction for partial
7131 // ordering) from the most specialized of all the function templates that
7132 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7133 // first check that it was implicitly generated during template argument
7134 // deduction by making sure it wasn't referenced, and then reset the deleted
7135 // flag to not-deleted, so that we can inherit that information from 'FD'.
7136 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7137 !Specialization->getCanonicalDecl()->isReferenced()) {
7138 assert(
7139 Specialization->getCanonicalDecl() == Specialization &&
7140 "This must be the only existing declaration of this specialization");
7141 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007142 }
John McCall816d75b2010-03-24 07:46:06 +00007143 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007144 MarkUnusedFileScopedDecl(Specialization);
7145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007146
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007147 // Turn the given function declaration into a function template
7148 // specialization, with the template arguments from the previous
7149 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007150 // Take copies of (semantic and syntactic) template argument lists.
7151 const TemplateArgumentList* TemplArgs = new (Context)
7152 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007153 FD->setFunctionTemplateSpecialization(
7154 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7155 SpecInfo->getTemplateSpecializationKind(),
7156 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007157
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007158 // The "previous declaration" for this function template specialization is
7159 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007160 Previous.clear();
7161 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007162 return false;
7163}
7164
Douglas Gregor86d142a2009-10-08 07:24:58 +00007165/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007166/// specialization.
7167///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007168/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007169/// explicit member function specialization. On successful completion,
7170/// the function declaration \p FD will become a member function
7171/// specialization.
7172///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007173/// \param Member the member declaration, which will be updated to become a
7174/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007175///
John McCall1f82f242009-11-18 22:49:29 +00007176/// \param Previous the set of declarations, one of which may be specialized
7177/// by this function specialization; the set will be modified to contain the
7178/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007179bool
John McCall1f82f242009-11-18 22:49:29 +00007180Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007181 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007182
Douglas Gregor86d142a2009-10-08 07:24:58 +00007183 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007184 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007185 NamedDecl *Instantiation = nullptr;
7186 NamedDecl *InstantiatedFrom = nullptr;
7187 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007188
John McCall1f82f242009-11-18 22:49:29 +00007189 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007190 // Nowhere to look anyway.
7191 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007192 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7193 I != E; ++I) {
7194 NamedDecl *D = (*I)->getUnderlyingDecl();
7195 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007196 QualType Adjusted = Function->getType();
7197 if (!hasExplicitCallingConv(Adjusted))
7198 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7199 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007200 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007201 Instantiation = Method;
7202 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007203 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007204 break;
7205 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007206 }
7207 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007208 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007209 VarDecl *PrevVar;
7210 if (Previous.isSingleResult() &&
7211 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007212 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007213 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007214 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007215 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007216 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007217 }
7218 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007219 CXXRecordDecl *PrevRecord;
7220 if (Previous.isSingleResult() &&
7221 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007222 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007223 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007224 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007225 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007226 }
Richard Smith7d137e32012-03-23 03:33:32 +00007227 } else if (isa<EnumDecl>(Member)) {
7228 EnumDecl *PrevEnum;
7229 if (Previous.isSingleResult() &&
7230 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007231 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007232 Instantiation = PrevEnum;
7233 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7234 MSInfo = PrevEnum->getMemberSpecializationInfo();
7235 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007237
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007238 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007239 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007240 // specializations are always out-of-line, the caller will complain about
7241 // this mismatch later.
7242 return false;
7243 }
John McCalle820e5e2010-04-13 20:37:33 +00007244
7245 // If this is a friend, just bail out here before we start turning
7246 // things into explicit specializations.
7247 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7248 // Preserve instantiation information.
7249 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7250 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7251 cast<CXXMethodDecl>(InstantiatedFrom),
7252 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7253 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7254 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7255 cast<CXXRecordDecl>(InstantiatedFrom),
7256 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7257 }
7258
7259 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007260 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007261 return false;
7262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007263
Douglas Gregor86d142a2009-10-08 07:24:58 +00007264 // Make sure that this is a specialization of a member.
7265 if (!InstantiatedFrom) {
7266 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7267 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007268 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7269 return true;
7270 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007271
Douglas Gregor06db9f52009-10-12 20:18:28 +00007272 // C++ [temp.expl.spec]p6:
7273 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007274 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007275 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007276 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007277 // use occurs; no diagnostic is required.
7278 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007279
Abramo Bagnara8075c852010-06-12 07:44:57 +00007280 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007281 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7282 TSK_ExplicitSpecialization,
7283 Instantiation,
7284 MSInfo->getTemplateSpecializationKind(),
7285 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007286 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007287 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007288
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007289 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007290 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007291 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007292 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007293 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007294 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007295
Douglas Gregor86d142a2009-10-08 07:24:58 +00007296 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007297 // the original declaration to note that it is an explicit specialization
7298 // (if it was previously an implicit instantiation). This latter step
7299 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007300 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007301 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7302 if (InstantiationFunction->getTemplateSpecializationKind() ==
7303 TSK_ImplicitInstantiation) {
7304 InstantiationFunction->setTemplateSpecializationKind(
7305 TSK_ExplicitSpecialization);
7306 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007307 // Explicit specializations of member functions of class templates do not
7308 // inherit '=delete' from the member function they are specializing.
7309 if (InstantiationFunction->isDeleted()) {
7310 assert(InstantiationFunction->getCanonicalDecl() ==
7311 InstantiationFunction);
Richard Smith5f274382016-09-28 23:55:27 +00007312 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007313 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007314 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007315
Douglas Gregor86d142a2009-10-08 07:24:58 +00007316 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7317 cast<CXXMethodDecl>(InstantiatedFrom),
7318 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007319 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007320 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007321 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7322 if (InstantiationVar->getTemplateSpecializationKind() ==
7323 TSK_ImplicitInstantiation) {
7324 InstantiationVar->setTemplateSpecializationKind(
7325 TSK_ExplicitSpecialization);
7326 InstantiationVar->setLocation(Member->getLocation());
7327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007328
Larisse Voufo39a1e502013-08-06 01:03:05 +00007329 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7330 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007331 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007332 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007333 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7334 if (InstantiationClass->getTemplateSpecializationKind() ==
7335 TSK_ImplicitInstantiation) {
7336 InstantiationClass->setTemplateSpecializationKind(
7337 TSK_ExplicitSpecialization);
7338 InstantiationClass->setLocation(Member->getLocation());
7339 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007340
Douglas Gregor86d142a2009-10-08 07:24:58 +00007341 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007342 cast<CXXRecordDecl>(InstantiatedFrom),
7343 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007344 } else {
7345 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7346 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7347 if (InstantiationEnum->getTemplateSpecializationKind() ==
7348 TSK_ImplicitInstantiation) {
7349 InstantiationEnum->setTemplateSpecializationKind(
7350 TSK_ExplicitSpecialization);
7351 InstantiationEnum->setLocation(Member->getLocation());
7352 }
7353
7354 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7355 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007356 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007357
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007358 // Save the caller the trouble of having to figure out which declaration
7359 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007360 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007361 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007362 return false;
7363}
7364
Douglas Gregore47f5a72009-10-14 23:41:34 +00007365/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007366///
7367/// \returns true if a serious error occurs, false otherwise.
7368static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007369 SourceLocation InstLoc,
7370 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007371 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7372 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007373
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007374 if (CurContext->isRecord()) {
7375 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7376 << D;
7377 return true;
7378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007379
Richard Smith050d2612011-10-18 02:28:33 +00007380 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007381 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007382 // template. If the name declared in the explicit instantiation is an
7383 // unqualified name, the explicit instantiation shall appear in the
7384 // namespace where its template is declared or, if that namespace is inline
7385 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007386 //
7387 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007388 if (WasQualifiedName) {
7389 if (CurContext->Encloses(OrigContext))
7390 return false;
7391 } else {
7392 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7393 return false;
7394 }
7395
7396 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7397 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007398 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007399 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007400 diag::err_explicit_instantiation_out_of_scope :
7401 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007402 << D << NS;
7403 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007404 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007405 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007406 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7407 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7408 << D << NS;
7409 } else
7410 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007411 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007412 diag::err_explicit_instantiation_must_be_global :
7413 diag::warn_explicit_instantiation_must_be_global_0x)
7414 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007415 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007416 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007417}
7418
7419/// \brief Determine whether the given scope specifier has a template-id in it.
7420static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7421 if (!SS.isSet())
7422 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007423
Richard Smith050d2612011-10-18 02:28:33 +00007424 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007425 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007426 // or a static data member of a class template specialization, the name of
7427 // the class template specialization in the qualified-id for the member
7428 // name shall be a simple-template-id.
7429 //
7430 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007431 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7432 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007433 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007434 if (isa<TemplateSpecializationType>(T))
7435 return true;
7436
7437 return false;
7438}
7439
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007440// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007441DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007442Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007443 SourceLocation ExternLoc,
7444 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007445 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007446 SourceLocation KWLoc,
7447 const CXXScopeSpec &SS,
7448 TemplateTy TemplateD,
7449 SourceLocation TemplateNameLoc,
7450 SourceLocation LAngleLoc,
7451 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007452 SourceLocation RAngleLoc,
7453 AttributeList *Attr) {
7454 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007455 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007456 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007457 // Check that the specialization uses the same tag kind as the
7458 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007459 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7460 assert(Kind != TTK_Enum &&
7461 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007462
Richard Trieu265c3442016-04-05 21:13:54 +00007463 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7464
7465 if (!ClassTemplate) {
Reid Klecknerf33bfcb02016-10-03 18:34:23 +00007466 NonTagKind NTK = getNonTagTypeDeclKind(TD);
7467 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << NTK;
Richard Trieu265c3442016-04-05 21:13:54 +00007468 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00007469 return true;
7470 }
7471
Douglas Gregord9034f02009-05-14 16:41:31 +00007472 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007473 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007474 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007475 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007476 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007477 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007478 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007479 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007480 diag::note_previous_use);
7481 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7482 }
7483
Douglas Gregore47f5a72009-10-14 23:41:34 +00007484 // C++0x [temp.explicit]p2:
7485 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007486 // definition and an explicit instantiation declaration. An explicit
7487 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007488 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7489 ? TSK_ExplicitInstantiationDefinition
7490 : TSK_ExplicitInstantiationDeclaration;
7491
7492 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7493 // Check for dllexport class template instantiation declarations.
7494 for (AttributeList *A = Attr; A; A = A->getNext()) {
7495 if (A->getKind() == AttributeList::AT_DLLExport) {
7496 Diag(ExternLoc,
7497 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7498 Diag(A->getLoc(), diag::note_attribute);
7499 break;
7500 }
7501 }
7502
7503 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7504 Diag(ExternLoc,
7505 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7506 Diag(A->getLocation(), diag::note_attribute);
7507 }
7508 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007509
Hans Wennborga86a83b2016-05-26 19:42:56 +00007510 // In MSVC mode, dllimported explicit instantiation definitions are treated as
7511 // instantiation declarations for most purposes.
7512 bool DLLImportExplicitInstantiationDef = false;
7513 if (TSK == TSK_ExplicitInstantiationDefinition &&
7514 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7515 // Check for dllimport class template instantiation definitions.
7516 bool DLLImport =
7517 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7518 for (AttributeList *A = Attr; A; A = A->getNext()) {
7519 if (A->getKind() == AttributeList::AT_DLLImport)
7520 DLLImport = true;
7521 if (A->getKind() == AttributeList::AT_DLLExport) {
7522 // dllexport trumps dllimport here.
7523 DLLImport = false;
7524 break;
7525 }
7526 }
7527 if (DLLImport) {
7528 TSK = TSK_ExplicitInstantiationDeclaration;
7529 DLLImportExplicitInstantiationDef = true;
7530 }
7531 }
7532
Douglas Gregora1f49972009-05-13 00:25:59 +00007533 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007534 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007535 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007536
7537 // Check that the template argument list is well-formed for this
7538 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007539 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007540 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7541 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007542 return true;
7543
Douglas Gregora1f49972009-05-13 00:25:59 +00007544 // Find the class template specialization declaration that
7545 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007546 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007547 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007548 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007549
Abramo Bagnara8075c852010-06-12 07:44:57 +00007550 TemplateSpecializationKind PrevDecl_TSK
7551 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7552
Douglas Gregor54888652009-10-07 00:13:32 +00007553 // C++0x [temp.explicit]p2:
7554 // [...] An explicit instantiation shall appear in an enclosing
7555 // namespace of its template. [...]
7556 //
7557 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007558 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7559 SS.isSet()))
7560 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007561
Craig Topperc3ec1492014-05-26 06:22:03 +00007562 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007563
Abramo Bagnara8075c852010-06-12 07:44:57 +00007564 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007565 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007566 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007567 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007568 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007569 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007570 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007571
Abramo Bagnara8075c852010-06-12 07:44:57 +00007572 // Even though HasNoEffect == true means that this explicit instantiation
7573 // has no effect on semantics, we go on to put its syntax in the AST.
7574
7575 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7576 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007577 // Since the only prior class template specialization with these
7578 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007579 // declaration node as our own, updating the source location
7580 // for the template name to reflect our new declaration.
7581 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007582 Specialization = PrevDecl;
7583 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007584 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007585 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00007586
7587 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7588 DLLImportExplicitInstantiationDef) {
7589 // The new specialization might add a dllimport attribute.
7590 HasNoEffect = false;
7591 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007592 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007593
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007594 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007595 // Create a new class template specialization declaration node for
7596 // this explicit specialization.
7597 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007598 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007599 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007600 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007601 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007602 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007603 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007604 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007605
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007606 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007607 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007608 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007609 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007610 }
7611
7612 // Build the fully-sugared type for this explicit instantiation as
7613 // the user wrote in the explicit instantiation itself. This means
7614 // that we'll pretty-print the type retrieved from the
7615 // specialization's declaration the way that the user actually wrote
7616 // the explicit instantiation, rather than formatting the name based
7617 // on the "canonical" representation used to store the template
7618 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007619 TypeSourceInfo *WrittenTy
7620 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7621 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007622 Context.getTypeDeclType(Specialization));
7623 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007624
Abramo Bagnara8075c852010-06-12 07:44:57 +00007625 // Set source locations for keywords.
7626 Specialization->setExternLoc(ExternLoc);
7627 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00007628 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007629
Rafael Espindola0b062072012-01-03 06:04:21 +00007630 if (Attr)
7631 ProcessDeclAttributeList(S, Specialization, Attr);
7632
Abramo Bagnara8075c852010-06-12 07:44:57 +00007633 // Add the explicit instantiation into its lexical context. However,
7634 // since explicit instantiations are never found by name lookup, we
7635 // just put it into the declaration context directly.
7636 Specialization->setLexicalDeclContext(CurContext);
7637 CurContext->addDecl(Specialization);
7638
7639 // Syntax is now OK, so return if it has no other effect on semantics.
7640 if (HasNoEffect) {
7641 // Set the template specialization kind.
7642 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007643 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007644 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007645
7646 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007647 // A definition of a class template or class member template
7648 // shall be in scope at the point of the explicit instantiation of
7649 // the class template or class member template.
7650 //
7651 // This check comes when we actually try to perform the
7652 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007653 ClassTemplateSpecializationDecl *Def
7654 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007655 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007656 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007657 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007658 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007659 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007660 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7661 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007662
Douglas Gregor1d957a32009-10-27 18:42:08 +00007663 // Instantiate the members of this class template specialization.
7664 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007665 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007666 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007667 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007668 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7669 // TSK_ExplicitInstantiationDefinition
7670 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00007671 (TSK == TSK_ExplicitInstantiationDefinition ||
7672 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007673 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007674 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007675
Hans Wennborgc0875502015-06-09 00:39:05 +00007676 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7677 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7678 // In the MS ABI, an explicit instantiation definition can add a dll
7679 // attribute to a template with a previous instantiation declaration.
7680 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007681 auto *A = cast<InheritableAttr>(
7682 getDLLAttr(Specialization)->clone(getASTContext()));
7683 A->setInherited(true);
7684 Def->addAttr(A);
Reid Kleckner5b640342016-02-26 19:51:02 +00007685
7686 // We reject explicit instantiations in class scope, so there should
7687 // never be any delayed exported classes to worry about.
7688 assert(DelayedDllExportClasses.empty() &&
7689 "delayed exports present at explicit instantiation");
Hans Wennborg17f9b442015-05-27 00:06:45 +00007690 checkClassLevelDLLAttribute(Def);
Reid Kleckner5b640342016-02-26 19:51:02 +00007691 referenceDLLExportedClassMethods();
Hans Wennborgfce87ca2015-06-09 00:39:09 +00007692
7693 // Propagate attribute to base class templates.
7694 for (auto &B : Def->bases()) {
7695 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7696 B.getType()->getAsCXXRecordDecl()))
7697 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7698 }
Hans Wennborg17f9b442015-05-27 00:06:45 +00007699 }
7700 }
7701
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007702 // Set the template specialization kind. Make sure it is set before
7703 // instantiating the members which will trigger ASTConsumer callbacks.
7704 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007705 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007706 } else {
7707
7708 // Set the template specialization kind.
7709 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007710 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007711
John McCall48871652010-08-21 09:40:31 +00007712 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007713}
7714
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007715// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007716DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007717Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007718 SourceLocation ExternLoc,
7719 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007720 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007721 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007722 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007723 IdentifierInfo *Name,
7724 SourceLocation NameLoc,
7725 AttributeList *Attr) {
7726
Douglas Gregord6ab8742009-05-28 23:31:59 +00007727 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007728 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007729 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007730 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007731 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007732 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007733 SourceLocation(), false, TypeResult(),
7734 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007735 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7736
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007737 if (!TagD)
7738 return true;
7739
John McCall48871652010-08-21 09:40:31 +00007740 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007741 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007742
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007743 if (Tag->isInvalidDecl())
7744 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007745
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007746 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7747 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7748 if (!Pattern) {
7749 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7750 << Context.getTypeDeclType(Record);
7751 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7752 return true;
7753 }
7754
Douglas Gregore47f5a72009-10-14 23:41:34 +00007755 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007756 // If the explicit instantiation is for a class or member class, the
7757 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007758 // simple-template-id.
7759 //
7760 // C++98 has the same restriction, just worded differently.
7761 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007762 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007763 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007764
Douglas Gregore47f5a72009-10-14 23:41:34 +00007765 // C++0x [temp.explicit]p2:
7766 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007767 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007768 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007769 TemplateSpecializationKind TSK
7770 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7771 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007772
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007773 // C++0x [temp.explicit]p2:
7774 // [...] An explicit instantiation shall appear in an enclosing
7775 // namespace of its template. [...]
7776 //
7777 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007778 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007779
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007780 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007781 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007782 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007783 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007784 PrevDecl = Record;
7785 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007786 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007787 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007788 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007789 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007790 PrevDecl,
7791 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007792 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007793 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007794 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007795 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007796 return TagD;
7797 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007798
Douglas Gregor12e49d32009-10-15 22:53:21 +00007799 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007800 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007801 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007802 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007803 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007804 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007805 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007806 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007807 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007808 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7809 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007810 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7811 << Pattern;
7812 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007813 } else {
7814 if (InstantiateClass(NameLoc, Record, Def,
7815 getTemplateInstantiationArgs(Record),
7816 TSK))
7817 return true;
7818
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007819 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007820 if (!RecordDef)
7821 return true;
7822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007823 }
7824
Douglas Gregor1d957a32009-10-27 18:42:08 +00007825 // Instantiate all of the members of the class.
7826 InstantiateClassMembers(NameLoc, RecordDef,
7827 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007828
Douglas Gregor88d292c2010-05-13 16:44:06 +00007829 if (TSK == TSK_ExplicitInstantiationDefinition)
7830 MarkVTableUsed(NameLoc, RecordDef, true);
7831
Mike Stump87c57ac2009-05-16 07:39:55 +00007832 // FIXME: We don't have any representation for explicit instantiations of
7833 // member classes. Such a representation is not needed for compilation, but it
7834 // should be available for clients that want to see all of the declarations in
7835 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007836 return TagD;
7837}
7838
John McCallfaf5fb42010-08-26 23:41:50 +00007839DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7840 SourceLocation ExternLoc,
7841 SourceLocation TemplateLoc,
7842 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007843 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007844 // TODO: check if/when DNInfo should replace Name.
7845 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7846 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007847 if (!Name) {
7848 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007849 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007850 diag::err_explicit_instantiation_requires_name)
7851 << D.getDeclSpec().getSourceRange()
7852 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007853
Douglas Gregor450f00842009-09-25 18:43:00 +00007854 return true;
7855 }
7856
7857 // The scope passed in may not be a decl scope. Zip up the scope tree until
7858 // we find one that is.
7859 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7860 (S->getFlags() & Scope::TemplateParamScope) != 0)
7861 S = S->getParent();
7862
7863 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007864 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7865 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007866 if (R.isNull())
7867 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007868
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007869 // C++ [dcl.stc]p1:
7870 // A storage-class-specifier shall not be specified in [...] an explicit
7871 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007872 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007873 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7874 << Name;
7875 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007876 } else if (D.getDeclSpec().getStorageClassSpec()
7877 != DeclSpec::SCS_unspecified) {
7878 // Complain about then remove the storage class specifier.
7879 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7880 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7881
7882 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007883 }
7884
Douglas Gregor3c74d412009-10-14 20:14:33 +00007885 // C++0x [temp.explicit]p1:
7886 // [...] An explicit instantiation of a function template shall not use the
7887 // inline or constexpr specifiers.
7888 // Presumably, this also applies to member functions of class templates as
7889 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007890 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007891 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007892 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007893 diag::err_explicit_instantiation_inline :
7894 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007895 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007896 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007897 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7898 // not already specified.
7899 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7900 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007901
Nathan Wilsonde498452016-02-08 05:34:00 +00007902 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7903 // applied only to the definition of a function template or variable template,
7904 // declared in namespace scope.
7905 if (D.getDeclSpec().isConceptSpecified()) {
7906 Diag(D.getDeclSpec().getConceptSpecLoc(),
7907 diag::err_concept_specified_specialization) << 0;
7908 return true;
7909 }
7910
Douglas Gregore47f5a72009-10-14 23:41:34 +00007911 // C++0x [temp.explicit]p2:
7912 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007913 // definition and an explicit instantiation declaration. An explicit
7914 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007915 TemplateSpecializationKind TSK
7916 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7917 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007918
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007919 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007920 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007921
7922 if (!R->isFunctionType()) {
7923 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007924 // A [...] static data member of a class template can be explicitly
7925 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007926 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007927 // C++1y [temp.explicit]p1:
7928 // A [...] variable [...] template specialization can be explicitly
7929 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007930 if (Previous.isAmbiguous())
7931 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007932
John McCall67c00872009-12-02 08:25:40 +00007933 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007934 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007935
Larisse Voufo39a1e502013-08-06 01:03:05 +00007936 if (!PrevTemplate) {
7937 if (!Prev || !Prev->isStaticDataMember()) {
7938 // We expect to see a data data member here.
7939 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7940 << Name;
7941 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7942 P != PEnd; ++P)
7943 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7944 return true;
7945 }
7946
7947 if (!Prev->getInstantiatedFromStaticDataMember()) {
7948 // FIXME: Check for explicit specialization?
7949 Diag(D.getIdentifierLoc(),
7950 diag::err_explicit_instantiation_data_member_not_instantiated)
7951 << Prev;
7952 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7953 // FIXME: Can we provide a note showing where this was declared?
7954 return true;
7955 }
7956 } else {
7957 // Explicitly instantiate a variable template.
7958
7959 // C++1y [dcl.spec.auto]p6:
7960 // ... A program that uses auto or decltype(auto) in a context not
7961 // explicitly allowed in this section is ill-formed.
7962 //
7963 // This includes auto-typed variable template instantiations.
7964 if (R->isUndeducedType()) {
7965 Diag(T->getTypeLoc().getLocStart(),
7966 diag::err_auto_not_allowed_var_inst);
7967 return true;
7968 }
7969
Richard Smithef985ac2013-09-18 02:10:12 +00007970 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7971 // C++1y [temp.explicit]p3:
7972 // If the explicit instantiation is for a variable, the unqualified-id
7973 // in the declaration shall be a template-id.
7974 Diag(D.getIdentifierLoc(),
7975 diag::err_explicit_instantiation_without_template_id)
7976 << PrevTemplate;
7977 Diag(PrevTemplate->getLocation(),
7978 diag::note_explicit_instantiation_here);
7979 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007980 }
7981
Nathan Wilson83839122016-04-09 02:55:27 +00007982 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
7983 // explicit instantiation (14.8.2) [...] of a concept definition.
7984 if (PrevTemplate->isConcept()) {
7985 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
7986 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
7987 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
7988 return true;
7989 }
7990
Richard Smithef985ac2013-09-18 02:10:12 +00007991 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007992 TemplateArgumentListInfo TemplateArgs =
7993 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007994
Larisse Voufo39a1e502013-08-06 01:03:05 +00007995 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7996 D.getIdentifierLoc(), TemplateArgs);
7997 if (Res.isInvalid())
7998 return true;
7999
8000 // Ignore access control bits, we don't need them for redeclaration
8001 // checking.
8002 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00008003 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008004
Douglas Gregore47f5a72009-10-14 23:41:34 +00008005 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008006 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008007 // or a static data member of a class template specialization, the name of
8008 // the class template specialization in the qualified-id for the member
8009 // name shall be a simple-template-id.
8010 //
8011 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008012 //
Richard Smith5977d872013-09-18 21:55:14 +00008013 // This does not apply to variable template specializations, where the
8014 // template-id is in the unqualified-id instead.
8015 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008016 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008017 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008018 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008019
Douglas Gregore47f5a72009-10-14 23:41:34 +00008020 // Check the scope of this explicit instantiation.
8021 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008022
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008023 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00008024 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8025 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008026 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008027 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00008028 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008029 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008030
Larisse Voufo39a1e502013-08-06 01:03:05 +00008031 if (!HasNoEffect) {
8032 // Instantiate static data member or variable template.
8033
8034 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8035 if (PrevTemplate) {
8036 // Merge attributes.
8037 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8038 ProcessDeclAttributeList(S, Prev, Attr);
8039 }
8040 if (TSK == TSK_ExplicitInstantiationDefinition)
8041 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8042 }
8043
8044 // Check the new variable specialization against the parsed input.
8045 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8046 Diag(T->getTypeLoc().getLocStart(),
8047 diag::err_invalid_var_template_spec_type)
8048 << 0 << PrevTemplate << R << Prev->getType();
8049 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8050 << 2 << PrevTemplate->getDeclName();
8051 return true;
8052 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008053
Douglas Gregor450f00842009-09-25 18:43:00 +00008054 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00008055 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008056 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008057
8058 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00008059 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00008060 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00008061 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00008062 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00008063 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00008064 HasExplicitTemplateArgs = true;
8065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008066
Douglas Gregor450f00842009-09-25 18:43:00 +00008067 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008068 // A [...] function [...] can be explicitly instantiated from its template.
8069 // A member function [...] of a class template can be explicitly
8070 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008071 // template.
John McCall58cc69d2010-01-27 01:50:18 +00008072 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00008073 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00008074 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8075 P != PEnd; ++P) {
8076 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00008077 if (!HasExplicitTemplateArgs) {
8078 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00008079 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
8080 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00008081 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008082
John McCall58cc69d2010-01-27 01:50:18 +00008083 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008084 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8085 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00008086 }
Douglas Gregor450f00842009-09-25 18:43:00 +00008087 }
8088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008089
Douglas Gregor450f00842009-09-25 18:43:00 +00008090 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8091 if (!FunTmpl)
8092 continue;
8093
Larisse Voufo98b20f12013-07-19 23:00:19 +00008094 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008095 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008096 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008097 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00008098 (HasExplicitTemplateArgs ? &TemplateArgs
8099 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00008100 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008101 // Keep track of almost-matches.
8102 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00008103 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008104 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008105 (void)TDK;
8106 continue;
8107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008108
John McCall58cc69d2010-01-27 01:50:18 +00008109 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008111
Douglas Gregor450f00842009-09-25 18:43:00 +00008112 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008113 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008114 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008115 D.getIdentifierLoc(),
8116 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8117 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8118 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008119
John McCall58cc69d2010-01-27 01:50:18 +00008120 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008121 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008122
8123 // Ignore access control bits, we don't need them for redeclaration checking.
8124 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008125
Alexey Bataev73983912014-11-06 10:10:50 +00008126 // C++11 [except.spec]p4
8127 // In an explicit instantiation an exception-specification may be specified,
8128 // but is not required.
8129 // If an exception-specification is specified in an explicit instantiation
8130 // directive, it shall be compatible with the exception-specifications of
8131 // other declarations of that function.
8132 if (auto *FPT = R->getAs<FunctionProtoType>())
8133 if (FPT->hasExceptionSpec()) {
8134 unsigned DiagID =
8135 diag::err_mismatched_exception_spec_explicit_instantiation;
8136 if (getLangOpts().MicrosoftExt)
8137 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8138 bool Result = CheckEquivalentExceptionSpec(
8139 PDiag(DiagID) << Specialization->getType(),
8140 PDiag(diag::note_explicit_instantiation_here),
8141 Specialization->getType()->getAs<FunctionProtoType>(),
8142 Specialization->getLocation(), FPT, D.getLocStart());
8143 // In Microsoft mode, mismatching exception specifications just cause a
8144 // warning.
8145 if (!getLangOpts().MicrosoftExt && Result)
8146 return true;
8147 }
8148
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008149 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008150 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008151 diag::err_explicit_instantiation_member_function_not_instantiated)
8152 << Specialization
8153 << (Specialization->getTemplateSpecializationKind() ==
8154 TSK_ExplicitSpecialization);
8155 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8156 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008157 }
8158
Douglas Gregorec9fd132012-01-14 16:38:05 +00008159 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008160 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8161 PrevDecl = Specialization;
8162
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008163 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008164 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008165 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008166 PrevDecl,
8167 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008168 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008169 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008170 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008171
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008172 // FIXME: We may still want to build some representation of this
8173 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008174 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008175 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008176 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008177
8178 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008179 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
8180 if (Attr)
8181 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008182
Richard Smitheb36ddf2014-04-24 22:45:46 +00008183 if (Specialization->isDefined()) {
8184 // Let the ASTConsumer know that this function has been explicitly
8185 // instantiated now, and its linkage might have changed.
8186 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8187 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008188 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008189
Douglas Gregore47f5a72009-10-14 23:41:34 +00008190 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008191 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008192 // or a static data member of a class template specialization, the name of
8193 // the class template specialization in the qualified-id for the member
8194 // name shall be a simple-template-id.
8195 //
8196 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008197 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008198 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008199 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008200 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008201 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008202 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008203 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008204
Nathan Wilson83839122016-04-09 02:55:27 +00008205 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8206 // explicit instantiation (14.8.2) [...] of a concept definition.
8207 if (FunTmpl && FunTmpl->isConcept() &&
8208 !D.getDeclSpec().isConceptSpecified()) {
8209 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8210 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8211 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8212 return true;
8213 }
8214
Douglas Gregore47f5a72009-10-14 23:41:34 +00008215 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008216 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008217 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008218 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008219 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008220
Douglas Gregor450f00842009-09-25 18:43:00 +00008221 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008222 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008223}
8224
John McCallfaf5fb42010-08-26 23:41:50 +00008225TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008226Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8227 const CXXScopeSpec &SS, IdentifierInfo *Name,
8228 SourceLocation TagLoc, SourceLocation NameLoc) {
8229 // This has to hold, because SS is expected to be defined.
8230 assert(Name && "Expected a name in a dependent tag");
8231
Aaron Ballman4a979672014-01-03 13:56:08 +00008232 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008233 if (!NNS)
8234 return true;
8235
Abramo Bagnara6150c882010-05-11 21:36:43 +00008236 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008237
Douglas Gregorba41d012010-04-24 16:38:41 +00008238 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8239 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008240 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008241 return true;
8242 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008243
Douglas Gregore7c20652011-03-02 00:47:37 +00008244 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008245 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008246 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8247
8248 // Create type-source location information for this type.
8249 TypeLocBuilder TLB;
8250 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008251 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008252 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8253 TL.setNameLoc(NameLoc);
8254 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008255}
8256
John McCallfaf5fb42010-08-26 23:41:50 +00008257TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008258Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8259 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008260 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008261 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008262 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008263
Richard Smith0bf8a4922011-10-18 20:49:44 +00008264 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8265 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008266 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008267 diag::warn_cxx98_compat_typename_outside_of_template :
8268 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008269 << FixItHint::CreateRemoval(TypenameLoc);
8270
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008271 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008272 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8273 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008274 if (T.isNull())
8275 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008276
8277 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8278 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008279 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008280 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008281 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008282 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008283 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008284 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008285 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008286 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008287 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008288 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008289
John McCallba7bf592010-08-24 05:47:05 +00008290 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008291}
8292
John McCallfaf5fb42010-08-26 23:41:50 +00008293TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008294Sema::ActOnTypenameType(Scope *S,
8295 SourceLocation TypenameLoc,
8296 const CXXScopeSpec &SS,
8297 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008298 TemplateTy TemplateIn,
8299 SourceLocation TemplateNameLoc,
8300 SourceLocation LAngleLoc,
8301 ASTTemplateArgsPtr TemplateArgsIn,
8302 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008303 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8304 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008305 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008306 diag::warn_cxx98_compat_typename_outside_of_template :
8307 diag::ext_typename_outside_of_template)
8308 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008309
8310 // Translate the parser's template argument list in our AST format.
8311 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8312 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8313
8314 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008315 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8316 // Construct a dependent template specialization type.
8317 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008318 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008319 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8320 DTN->getQualifier(),
8321 DTN->getIdentifier(),
8322 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008323
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008324 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008325 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008326 DependentTemplateSpecializationTypeLoc SpecTL
8327 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008328 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8329 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008330 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008331 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008332 SpecTL.setLAngleLoc(LAngleLoc);
8333 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008334 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8335 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008336 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008337 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008338
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008339 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8340 if (T.isNull())
8341 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008342
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008343 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008344 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008345 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008346 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008347 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8348 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008349 SpecTL.setLAngleLoc(LAngleLoc);
8350 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008351 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8352 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8353
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008354 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8355 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008356 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008357 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8358
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008359 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8360 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008361}
8362
Douglas Gregorb09518c2011-02-27 22:46:49 +00008363
Richard Smith6f8d2c62012-05-09 05:17:00 +00008364/// Determine whether this failed name lookup should be treated as being
8365/// disabled by a usage of std::enable_if.
8366static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8367 SourceRange &CondRange) {
8368 // We must be looking for a ::type...
8369 if (!II.isStr("type"))
8370 return false;
8371
8372 // ... within an explicitly-written template specialization...
8373 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8374 return false;
8375 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008376 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8377 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8378 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008379 return false;
8380 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008381 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008382
8383 // ... which names a complete class template declaration...
8384 const TemplateDecl *EnableIfDecl =
8385 EnableIfTST->getTemplateName().getAsTemplateDecl();
8386 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8387 return false;
8388
8389 // ... called "enable_if".
8390 const IdentifierInfo *EnableIfII =
8391 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8392 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8393 return false;
8394
8395 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008396 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008397 return true;
8398}
8399
Douglas Gregor333489b2009-03-27 23:10:48 +00008400/// \brief Build the type that describes a C++ typename specifier,
8401/// e.g., "typename T::type".
8402QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008403Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8404 SourceLocation KeywordLoc,
8405 NestedNameSpecifierLoc QualifierLoc,
8406 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008407 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008408 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008409 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008410
John McCall0b66eb32010-05-01 00:40:08 +00008411 DeclContext *Ctx = computeDeclContext(SS);
8412 if (!Ctx) {
8413 // If the nested-name-specifier is dependent and couldn't be
8414 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008415 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8416 return Context.getDependentNameType(Keyword,
8417 QualifierLoc.getNestedNameSpecifier(),
8418 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008419 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008420
John McCall0b66eb32010-05-01 00:40:08 +00008421 // If the nested-name-specifier refers to the current instantiation,
8422 // the "typename" keyword itself is superfluous. In C++03, the
8423 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8424 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008425 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008426
John McCall0b66eb32010-05-01 00:40:08 +00008427 if (RequireCompleteDeclContext(SS, Ctx))
8428 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008429
8430 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008431 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008432 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008433 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008434 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008435 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008436 case LookupResult::NotFound: {
8437 // If we're looking up 'type' within a template named 'enable_if', produce
8438 // a more specific diagnostic.
8439 SourceRange CondRange;
8440 if (isEnableIf(QualifierLoc, II, CondRange)) {
8441 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8442 << Ctx << CondRange;
8443 return QualType();
8444 }
8445
Douglas Gregore40876a2009-10-13 21:16:44 +00008446 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008447 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008448 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008449
8450 case LookupResult::FoundUnresolvedValue: {
8451 // We found a using declaration that is a value. Most likely, the using
8452 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008453 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008454 IILoc);
8455 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8456 << Name << Ctx << FullRange;
8457 if (UnresolvedUsingValueDecl *Using
8458 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008459 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008460 Diag(Loc, diag::note_using_value_decl_missing_typename)
8461 << FixItHint::CreateInsertion(Loc, "typename ");
8462 }
8463 }
8464 // Fall through to create a dependent typename type, from which we can recover
8465 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008466
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008467 case LookupResult::NotFoundInCurrentInstantiation:
8468 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008469 return Context.getDependentNameType(Keyword,
8470 QualifierLoc.getNestedNameSpecifier(),
8471 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008472
8473 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008474 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008475 // We found a type. Build an ElaboratedType, since the
8476 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008477 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008478 return Context.getElaboratedType(ETK_Typename,
8479 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008480 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008481 }
8482
8483 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008484 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008485 break;
8486
8487 case LookupResult::FoundOverloaded:
8488 DiagID = diag::err_typename_nested_not_type;
8489 Referenced = *Result.begin();
8490 break;
8491
John McCall6538c932009-10-10 05:48:19 +00008492 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008493 return QualType();
8494 }
8495
8496 // If we get here, it's because name lookup did not find a
8497 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008498 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008499 IILoc);
8500 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008501 if (Referenced)
8502 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8503 << Name;
8504 return QualType();
8505}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008506
8507namespace {
8508 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008509 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008510 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008511 SourceLocation Loc;
8512 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008513
Douglas Gregor15acfb92009-08-06 16:20:37 +00008514 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008515 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008516
Mike Stump11289f42009-09-09 15:08:12 +00008517 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008518 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008519 DeclarationName Entity)
8520 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008521 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008522
8523 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008524 /// transformed.
8525 ///
8526 /// For the purposes of type reconstruction, a type has already been
8527 /// transformed if it is NULL or if it is not dependent.
8528 bool AlreadyTransformed(QualType T) {
8529 return T.isNull() || !T->isDependentType();
8530 }
Mike Stump11289f42009-09-09 15:08:12 +00008531
8532 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008533 /// rebuilt.
8534 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008535
Douglas Gregor15acfb92009-08-06 16:20:37 +00008536 /// \brief Returns the name of the entity whose type is being rebuilt.
8537 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008538
Douglas Gregoref6ab412009-10-27 06:26:26 +00008539 /// \brief Sets the "base" location and entity when that
8540 /// information is known based on another transformation.
8541 void setBase(SourceLocation Loc, DeclarationName Entity) {
8542 this->Loc = Loc;
8543 this->Entity = Entity;
8544 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008545
8546 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8547 // Lambdas never need to be transformed.
8548 return E;
8549 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008550 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008551} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008552
Douglas Gregor15acfb92009-08-06 16:20:37 +00008553/// \brief Rebuilds a type within the context of the current instantiation.
8554///
Mike Stump11289f42009-09-09 15:08:12 +00008555/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008556/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008557/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008558/// partial specialization thereof). This routine will rebuild that type now
8559/// that we have entered the declarator's scope, which may produce different
8560/// canonical types, e.g.,
8561///
8562/// \code
8563/// template<typename T>
8564/// struct X {
8565/// typedef T* pointer;
8566/// pointer data();
8567/// };
8568///
8569/// template<typename T>
8570/// typename X<T>::pointer X<T>::data() { ... }
8571/// \endcode
8572///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008573/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008574/// since we do not know that we can look into X<T> when we parsed the type.
8575/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008576/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008577/// as the canonical type of T*, allowing the return types of the out-of-line
8578/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008579TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8580 SourceLocation Loc,
8581 DeclarationName Name) {
8582 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008583 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008584
Douglas Gregor15acfb92009-08-06 16:20:37 +00008585 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8586 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008587}
Douglas Gregorbe999392009-09-15 16:23:51 +00008588
John McCalldadc5752010-08-24 06:29:42 +00008589ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008590 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8591 DeclarationName());
8592 return Rebuilder.TransformExpr(E);
8593}
8594
John McCall99b2fe52010-04-29 23:50:39 +00008595bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008596 if (SS.isInvalid())
8597 return true;
John McCall2408e322010-04-27 00:57:59 +00008598
Douglas Gregor10176412011-02-25 16:07:42 +00008599 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008600 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8601 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008602 NestedNameSpecifierLoc Rebuilt
8603 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8604 if (!Rebuilt)
8605 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008606
Douglas Gregor10176412011-02-25 16:07:42 +00008607 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008608 return false;
John McCall2408e322010-04-27 00:57:59 +00008609}
8610
Douglas Gregor041b0842011-10-14 15:31:12 +00008611/// \brief Rebuild the template parameters now that we know we're in a current
8612/// instantiation.
8613bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8614 TemplateParameterList *Params) {
8615 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8616 Decl *Param = Params->getParam(I);
8617
8618 // There is nothing to rebuild in a type parameter.
8619 if (isa<TemplateTypeParmDecl>(Param))
8620 continue;
8621
8622 // Rebuild the template parameter list of a template template parameter.
8623 if (TemplateTemplateParmDecl *TTP
8624 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8625 if (RebuildTemplateParamsInCurrentInstantiation(
8626 TTP->getTemplateParameters()))
8627 return true;
8628
8629 continue;
8630 }
8631
8632 // Rebuild the type of a non-type template parameter.
8633 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8634 TypeSourceInfo *NewTSI
8635 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8636 NTTP->getLocation(),
8637 NTTP->getDeclName());
8638 if (!NewTSI)
8639 return true;
8640
8641 if (NewTSI != NTTP->getTypeSourceInfo()) {
8642 NTTP->setTypeSourceInfo(NewTSI);
8643 NTTP->setType(NewTSI->getType());
8644 }
8645 }
8646
8647 return false;
8648}
8649
Douglas Gregorbe999392009-09-15 16:23:51 +00008650/// \brief Produces a formatted string that describes the binding of
8651/// template parameters to template arguments.
8652std::string
8653Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8654 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008655 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008656}
8657
8658std::string
8659Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8660 const TemplateArgument *Args,
8661 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008662 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008663 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008664
Douglas Gregore62e6a02009-11-11 19:13:48 +00008665 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008666 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008667
Douglas Gregorbe999392009-09-15 16:23:51 +00008668 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008669 if (I >= NumArgs)
8670 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008671
Douglas Gregorbe999392009-09-15 16:23:51 +00008672 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008673 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008674 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008675 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008676
Douglas Gregorbe999392009-09-15 16:23:51 +00008677 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008678 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008679 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008680 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008681 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008682
Douglas Gregor0192c232010-12-20 16:52:59 +00008683 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008684 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008685 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008686
8687 Out << ']';
8688 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008689}
Francois Pichet1c229c02011-04-22 22:18:13 +00008690
Richard Smithe40f2ba2013-08-07 21:41:30 +00008691void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8692 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008693 if (!FD)
8694 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008695
Justin Lebar28f09c52016-10-10 16:26:08 +00008696 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008697
8698 // Take tokens to avoid allocations
8699 LPT->Toks.swap(Toks);
8700 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00008701 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008702
8703 FD->setLateTemplateParsed(true);
8704}
8705
8706void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8707 if (!FD)
8708 return;
8709 FD->setLateTemplateParsed(false);
8710}
Francois Pichet1c229c02011-04-22 22:18:13 +00008711
8712bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8713 DeclContext *DC = CurContext;
8714
8715 while (DC) {
8716 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8717 const FunctionDecl *FD = RD->isLocalClass();
8718 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8719 } else if (DC->isTranslationUnit() || DC->isNamespace())
8720 return false;
8721
8722 DC = DC->getParent();
8723 }
8724 return false;
8725}
Richard Smith6739a102016-05-05 00:56:12 +00008726
Benjamin Kramera0a13c32016-08-06 11:21:04 +00008727namespace {
Richard Smith6739a102016-05-05 00:56:12 +00008728/// \brief Walk the path from which a declaration was instantiated, and check
8729/// that every explicit specialization along that path is visible. This enforces
8730/// C++ [temp.expl.spec]/6:
8731///
8732/// If a template, a member template or a member of a class template is
8733/// explicitly specialized then that specialization shall be declared before
8734/// the first use of that specialization that would cause an implicit
8735/// instantiation to take place, in every translation unit in which such a
8736/// use occurs; no diagnostic is required.
8737///
8738/// and also C++ [temp.class.spec]/1:
8739///
8740/// A partial specialization shall be declared before the first use of a
8741/// class template specialization that would make use of the partial
8742/// specialization as the result of an implicit or explicit instantiation
8743/// in every translation unit in which such a use occurs; no diagnostic is
8744/// required.
8745class ExplicitSpecializationVisibilityChecker {
8746 Sema &S;
8747 SourceLocation Loc;
8748 llvm::SmallVector<Module *, 8> Modules;
8749
8750public:
8751 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
8752 : S(S), Loc(Loc) {}
8753
8754 void check(NamedDecl *ND) {
8755 if (auto *FD = dyn_cast<FunctionDecl>(ND))
8756 return checkImpl(FD);
8757 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
8758 return checkImpl(RD);
8759 if (auto *VD = dyn_cast<VarDecl>(ND))
8760 return checkImpl(VD);
8761 if (auto *ED = dyn_cast<EnumDecl>(ND))
8762 return checkImpl(ED);
8763 }
8764
8765private:
8766 void diagnose(NamedDecl *D, bool IsPartialSpec) {
8767 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
8768 : Sema::MissingImportKind::ExplicitSpecialization;
8769 const bool Recover = true;
8770
8771 // If we got a custom set of modules (because only a subset of the
8772 // declarations are interesting), use them, otherwise let
8773 // diagnoseMissingImport intelligently pick some.
8774 if (Modules.empty())
8775 S.diagnoseMissingImport(Loc, D, Kind, Recover);
8776 else
8777 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
8778 }
8779
8780 // Check a specific declaration. There are three problematic cases:
8781 //
8782 // 1) The declaration is an explicit specialization of a template
8783 // specialization.
8784 // 2) The declaration is an explicit specialization of a member of an
8785 // templated class.
8786 // 3) The declaration is an instantiation of a template, and that template
8787 // is an explicit specialization of a member of a templated class.
8788 //
8789 // We don't need to go any deeper than that, as the instantiation of the
8790 // surrounding class / etc is not triggered by whatever triggered this
8791 // instantiation, and thus should be checked elsewhere.
8792 template<typename SpecDecl>
8793 void checkImpl(SpecDecl *Spec) {
8794 bool IsHiddenExplicitSpecialization = false;
8795 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
8796 IsHiddenExplicitSpecialization =
8797 Spec->getMemberSpecializationInfo()
8798 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
8799 : !S.hasVisibleDeclaration(Spec);
8800 } else {
8801 checkInstantiated(Spec);
8802 }
8803
8804 if (IsHiddenExplicitSpecialization)
8805 diagnose(Spec->getMostRecentDecl(), false);
8806 }
8807
8808 void checkInstantiated(FunctionDecl *FD) {
8809 if (auto *TD = FD->getPrimaryTemplate())
8810 checkTemplate(TD);
8811 }
8812
8813 void checkInstantiated(CXXRecordDecl *RD) {
8814 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
8815 if (!SD)
8816 return;
8817
8818 auto From = SD->getSpecializedTemplateOrPartial();
8819 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
8820 checkTemplate(TD);
8821 else if (auto *TD =
8822 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
8823 if (!S.hasVisibleDeclaration(TD))
8824 diagnose(TD, true);
8825 checkTemplate(TD);
8826 }
8827 }
8828
8829 void checkInstantiated(VarDecl *RD) {
8830 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
8831 if (!SD)
8832 return;
8833
8834 auto From = SD->getSpecializedTemplateOrPartial();
8835 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
8836 checkTemplate(TD);
8837 else if (auto *TD =
8838 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
8839 if (!S.hasVisibleDeclaration(TD))
8840 diagnose(TD, true);
8841 checkTemplate(TD);
8842 }
8843 }
8844
8845 void checkInstantiated(EnumDecl *FD) {}
8846
8847 template<typename TemplDecl>
8848 void checkTemplate(TemplDecl *TD) {
8849 if (TD->isMemberSpecialization()) {
8850 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
8851 diagnose(TD->getMostRecentDecl(), false);
8852 }
8853 }
8854};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00008855} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00008856
8857void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
8858 if (!getLangOpts().Modules)
8859 return;
8860
8861 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
8862}
8863
8864/// \brief Check whether a template partial specialization that we've discovered
8865/// is hidden, and produce suitable diagnostics if so.
8866void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
8867 NamedDecl *Spec) {
8868 llvm::SmallVector<Module *, 8> Modules;
8869 if (!hasVisibleDeclaration(Spec, &Modules))
8870 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
8871 MissingImportKind::PartialSpecialization,
8872 /*Recover*/true);
8873}